一、Spring 与Web 集成
核心内容:注册ContextLoaderListener
添加依赖:
<!-- 提供和web环境集成的支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
在web.xml文件中添加配置:
<!-- 监听项目的启动,负责启动spring工厂,并把工厂对象存储于ServletContext作用域中
细节:需要知道 spring的配置文件的位置。会从 一个名为"contextConfigLocation"的context-param中获取
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 定义了spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
Servlet集成工厂:
import com.vince.pojo.User;
import com.vince.service.UserService;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "UserServlet",value = "/user")
public class UserServlet extends HttpServlet {
// 获取setvice
private UserService userService= (UserService) ContextLoader.getCurrentWebApplicationContext().getBean("us");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
项目示例:
一、servlet :
@WebServlet(name = "UserServlet",value = "/user")
public class UserServlet extends HttpServlet {
private UserService userService= (UserService) ContextLoader.getCurrentWebApplicationContext().getBean("us");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取数据
String id = request.getParameter("id");
// 调用业务
User user = userService.queryByID(Integer.parseInt(id));
System.out.println(user);
if (user!=null){
response.getWriter().write("恭喜你 登录成功~");
//存入域中
request.setAttribute("user", user);
//转发
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- 监听项目的启动,负责启动spring工厂,并把工厂对象存储于ServletContext作用域中
细节:需要知道 spring的配置文件的位置。会从 一个名为"contextConfigLocation"的context-param中获取
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 定义了spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-annotation.xml</param-value>
</context-param>
</web-app>