一、定义页面及Servlet

在jsp页面加入以下,避免乱码

<meta charset="utf-8">
<body>
<form action="RegisterServlte" method="post">
姓名:<input type="text" name="name" /><br>
年龄:<input type="text" name="age" /><br>
<input type="submit" value="注册" />
</form>
</body>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.jmu.beans.Student; /**
* Servlet implementation class RegisterServlte
*/
public class RegisterServlte extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String name=request.getParameter("name");
String ageStr=request.getParameter("age");
Integer age=Integer.valueOf(ageStr);
Student student=new Student(name,age); request.getRequestDispatcher("/welcome.jsp").forward(request, response);
} }

三、测试环境搭建

 public class Student {
private Integer id;
private String name;
private int age; public Student() {
super();
} public Student( String name, int age) {
super();
this.name = name;
this.age = age;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
} }

Student

 //Dao增删改查
public interface IStudentDao {
void insertStudent(Student student);
void deleteById(int id);
void updateStudent(Student student); List<Student> selectAllStudents();
Student selectStudentById(int id);
}

IStudentDao

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jmu.dao.IStudentDao">
<insert id="insertStudent">
insert into student(name,age) values(#{name},#{age})
</insert> <delete id="deleteById">
delete from student where id=#{XXX}
</delete> <update id="updateStudent">
update student set name=#{name},age=#{age} where id=#{id}
</update> <select id="selectAllStudents" resultType="student">
select id,name,age from student
</select> <select id="selectStudentById" resultType="student">
select id,name,age from student where id=#{XXX}
</select>
</mapper>

IStudentDao.xml

IStudentService
 public class StudentServiceImpl implements IStudentService {
private IStudentDao dao; public void setDao(IStudentDao dao) {
this.dao = dao;
} public void addStudent(Student student) {
// TODO Auto-generated method stub
dao.insertStudent(student); } public void removeById(int id) {
// TODO Auto-generated method stub
dao.deleteById(id);
} public void modifyStudent(Student student) {
// TODO Auto-generated method stub
dao.updateStudent(student);
} public List<String> findAllStudentsNames() {
// TODO Auto-generated method stub
List<String> names = new ArrayList<String>();
List<Student> sudents = this.findAllStudents();
for (Student student : sudents) {
names.add(student.getName());
}
return names;
} public String findStudentNameById(int id) {
// TODO Auto-generated method stub
Student student = this.findStudentById(id);
return student.getName();
} public List<Student> findAllStudents() {
// TODO Auto-generated method stub
return dao.selectAllStudents();
} public Student findStudentById(int id) {
// TODO Auto-generated method stub
return dao.selectStudentById(id);
} }

StudentServiceImpl

// 获取Spring容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从Spring容器中获取到service对象
IStudentService service = (IStudentService) ac.getBean("studentService");
// 调用Service的addStudent()完成插入
service.addStudent(student);

RegisterServlet

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--注册数据源:C3P0 -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean> <!-- 注册属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" /> <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="dataSource" ref="myDataSource"></property>
</bean> <!--生成Dao的代理对象
当前配置会被本包中所有的接口生成代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory" />
<property name="basePackage" value="com.jmu.dao" />
</bean> <!-- 注册Service -->
<bean id="studentService" class="com.jmu.service.StudentServiceImpl">
<!-- 这里的Dao的注入需要使用ref属性,且其作为接口的简单类名 -->
<property name="dao" ref="IStudentDao" />
</bean>
</beans>

applicationContext.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <!--配置别名 -->
<typeAliases>
<package name="com.jmu.beans" />
</typeAliases> <mappers>
<package name="com.jmu.dao" />
</mappers> </configuration>

mybatis.xml

四、当前程序存在问题

刷新会创建不同spring容器对象,而不同servlet创建不同容器。当一个应用只能有一个spring容器

五、注册ContextLoaderListener

复制之前web项目,需要修改web context root

ctrl+shift+t open Type
ctrl+o 查看结构
ctrl+t 查看继承关系

myeclipse快捷键

方法一:读源码ContextLoaderListener与ContextLoader获取key

注册ServletContext监听器,完成2件工作:

1、在Servletcontext被创建时,创建Spring容器对象;

2、将创建好的Spring容器对象放入到ServletContext的域属性空间

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

修改applicationContext.xml为spring.xml在web.xml中添加如下(Spring在web项目中必须有的2项配置):

 <context-param>
<param-name>contextConfigLocation </param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- 注册servletContext监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

修改servlet中

    // 获取Spring容器对象
String acKey = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
ApplicationContext ac = (ApplicationContext) this.getServletContext().getAttribute(acKey);
 public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String ageStr = request.getParameter("age");
Integer age = Integer.valueOf(ageStr);
Student student = new Student(name, age);
// 获取Spring容器对象
String acKey = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
ApplicationContext ac = (ApplicationContext) this.getServletContext().getAttribute(acKey);
// 从Spring容器中获取到service对象
IStudentService service = (IStudentService) ac.getBean("studentService");
// 调用Service的addStudent()完成插入
service.addStudent(student);
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
} }

RegisterServlet

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>17-spring-web</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <context-param>
<param-name>contextConfigLocation </param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- 注册servletContext监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<description></description>
<display-name>RegisterServlet</display-name>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.jmu.servlets.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.jmu.servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

web.xml

方法二:使用工具类获取Spring容器

修改servlet中

    // 获取Spring容器对象
WebApplicationContext ac= WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

Spring与Web的更多相关文章

  1. 转载:如何让spring mvc web应用启动时就执行

    转载:如何让spring mvc web应用启动时就执行特定处理 http://www.cnblogs.com/yjmyzz/p/4747251.html# Spring-MVC的应用中 一.Appl ...

  2. Spring的web应用启动加载数据字典方法

    在一个基于Spring的web项目中,当我们需要在应用启动时加载数据字典时,可写一个监听实现javax.servlet.ServletContextListener 实现其中的contextIniti ...

  3. Spring实战5:基于Spring构建Web应用

    主要内容 将web请求映射到Spring控制器 绑定form参数 验证表单提交的参数 对于很多Java程序员来说,他们的主要工作就是开发Web应用,如果你也在做这样的工作,那么你一定会了解到构建这类系 ...

  4. 使用XFire+Spring构建Web Service(一)——helloWorld篇

    转自:http://www.blogjava.net/amigoxie/archive/2007/09/26/148207.html原文出处:http://tech.it168.com/j/2007- ...

  5. 使用Maven创建一个Spring MVC Web 项目

    使用Maven创建java web 项目(Spring MVC)用到如下工具: 1.Maven 3.2 2.IntelliJ IDEA 13 3.JDK 1.7 4.Spring 4.1.1 rele ...

  6. 使用XFire+Spring构建Web Service

    XFire是与Axis 2并列的新一代Web Service框架,通过提供简单的API支持Web Service各项标准协议,帮助你方便快速地开发Web Service应用. 相 对于Axis来说,目 ...

  7. 基于Spring的Web缓存

    缓存的基本思想其实是以空间换时间.我们知道,IO的读写速度相对内存来说是非常比较慢的,通常一个web应用的瓶颈就出现在磁盘IO的读写上.那么,如果我们在内存中建立一个存储区,将数据缓存起来,当浏览器端 ...

  8. Spring Boot Web Executable Demo

    Spring Boot Web Executable Demo */--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre.sr ...

  9. Spring之WEB模块

    Spring的WEB模块用于整合Web框架,例如Struts 1.Struts 2.JSF等 整合Struts 1 继承方式 Spring框架提供了ActionSupport类支持Struts 1的A ...

  10. J2EE进阶(五)Spring在web.xml中的配置

     J2EE进阶(五)Spring在web.xml中的配置 前言 在实际项目中spring的配置文件applicationcontext.xml是通过spring提供的加载机制自动加载到容器中.在web ...

随机推荐

  1. 《快学Scala》第一章 基础

  2. android learning

    https://www.cnblogs.com/kangjianwei101/p/5621238.html https://blog.csdn.net/write6/article/details/7 ...

  3. 高性能缓存服务器Varnish

    一.Varnish概述 Varnish是一款高性能的.开源的反向代理服务器和缓存服务器,计算机系统的除了有内存外,还有CPU的L1.L2,甚至L3级别的缓存,Varnish的设计架构就是利用操作系统的 ...

  4. Nginx文件上传下载实现与文件管理

    1.Nginx 上传 Nginx 依赖包下载 # wget http://www.nginx.org/download/nginx-1.2.2.tar.gzinx # wget http://www. ...

  5. Java_锁Synchronized

    锁(synchronized):既然线程之间是并发执行,就必然会有资源冲突的时候,如果不加以限制,很可能会出现死锁现象,这时就需要锁来对线程获取资源的限制程序中,可以给类,方法,代码块加锁.1.方法锁 ...

  6. Python中的匿名函数lambda的用法

    一.lambda函数的简介  对lambda函数,它其实是一个类似于def的函数,只不过lambda是一个不需要定义函数名的匿名函数.当我们在有些时候,需要做一些简单的数学计算时,如果定义一个def函 ...

  7. linux中pipe和dup2详解

    1.什么是管道 管道是半双工的,数据只能向一个方向流动:需要双方通信时,需要建立起两个管道: 只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程): 单独构成一种独立的文件系统:管道对于管道两端的进 ...

  8. USACO The Lazy Cow

    题目描述 这是一个炎热的夏天,奶牛贝茜感觉到相当的疲倦而且她也特别懒惰.她要在她的领域中找到一个合适的位置吃草,让她能吃到尽可能多的美味草并且尽量只在很短的距离.奶牛贝茜居住的领域是一个 N×N 的矩 ...

  9. [性能测试]:ISO8583报文解析实例

    现在我们有ISO8583报文如下(十六进制表示法): 60 00 03 00 00 60 31 00 31 07 30 02 00 30 20 04 C0 20 C0 98 11 00 00 00 0 ...

  10. [转] Akka 使用系列之二: 测试

    [From] http://www.algorithmdog.com/akka-test 通过上一篇文章,我们已经大致了解怎么使用 Akka,期待细致用法.这篇文章将介绍如何用 Akka-testki ...