Spring与Web

时间:2023-03-09 20:37:15
Spring与Web

一、定义页面及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);
} }

三、测试环境搭建

Spring与Web

 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与WebSpring与Web

四、当前程序存在问题

刷新会创建不同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());