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);
}
}
web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>15-spring-web</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RegServlet</servlet-name>
<servlet-class>com.bjpowernode.action.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegServlet</servlet-name>
<url-pattern>/regservlet</url-pattern>
</servlet-mapping>
<!-- 注册监听器:1.创建spring的容器对象;2.把创建好的容器对象放入到ServletContext中 -->
<!--
监听器启动的时候,找/WEB-INF/applicationContext.xml ,
这个文件是在监听器中创建spring容器时,默认加载的配置文件路径和名称。
-->
<!-- 使用自动的配置文件路径和名称 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<listener>
<!-- spring-web.jar -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>