spring-web:在web應用中即使用監聽器建立spring容器物件
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);
}
}