spring-web2:在web应用中,使用spring。spring管理Service,Dao对象,而servlet、JSP、监听器对象是由Tomcat生成的
web项目中使用spring的问题:
1.容器对象创建多次了, 应该是创建一次 (在应用启动的时候创建一次)
2.容器对象需要在多个Servlet中使用,需要把容器对象放入到全局作用域ServletContext
解决问题使用监听器(自定义),框架提供了ContextLoaderLister监听器
private WebApplicationContext context;
public interface WebApplicationContext extends ApplicationContext
public interface ConfigurableWebApplicationContext extends WebApplicationContext
把创建好的spring容器对象,放入到ServletContext中
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
key : WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
this.context: 是WebApplicationContext
步骤:
1.新建 web应用
加入jar:spring-web.jar
2.拷贝14-spring-mybatis-dbcp项目中的lib, src项目的源码和配置文件
3.新建jsp,定义form,有参数name,age
4.新建Servlet,接收请求参数, 在Servlet中创建Spring的容器, 获取Service对象,调用Service的业务方法。
5.新建显示处理结果的jsp
6.修改web.xml:
1)注册Servlet
2)注册监听器
/****web.xml配置/
监听器启动的时候,找/WEB-INF/applicationContext.xml ,
这个文件是在监听器中创建spring容器时,默认加载的配置文件路径和名称。
使用自动的配置文件路径和名称
contextConfigLocation
classpath:spring.xml
org.springframework.web.context.ContextLoaderListener
/*** registerServlet***/
package com.bjpowernode.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.bjpowernode.beans.Student;
import com.bjpowernode.service.StudentService;
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求参数 name ,age
String strName = request.getParameter("name");
String strAge = request.getParameter("age");
//创建spring容器对象
String configLocation="applicationContext.xml";
//ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);
//从ServletContext中获取容器对象
//String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
//WebApplicationContext ctx = (WebApplicationContext) this.getServletContext().getAttribute(key);
//框架提供一方法,获取容器对象
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
System.out.println("容器对象:"+ctx);
//从容器中获取对象
StudentService service = (StudentService) ctx.getBean("studentService");
//调用Service的方法
Student student = new Student();
student.setAge(Integer.parseInt(strAge));
student.setName(strName);
service.addStudent(student);
//指定显示处理结果的页面
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}