title: spring整合servlet
date: 2019-07-06 14:18:19
tags: spring整合servlet
categories: spring
不懂可以给我留言,虽然我也很菜
web整合servlet+spring
整合步骤:
- 导包,除了导入spring需要的包以外,还要新导入一个: spring-web.
我等会把包都放这里: 所有jar包,还有一个如何下载spring的jar包的博客也放在这里: 如何在官网下载jar包.
这个是要创建一个web项目了哈,web项目会创建把,idea创建的时候选择java enterprise那个选项就可以了,然后在web-inf下面新建一个lib文件夹,将jar包放在里面,然后将lib文件夹添加为库就好了.
- 创建servlet,service(dao层我就省了哈,做个演示)
--servlet代码
@WebServlet(name = "UserServlet", urlPatterns = "/user")
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码
response.setContentType("text/html;charset=utf-8");
//获取参数
String name = request.getParameter("username");
//使用web.xml监听spring容器,使得其不论点击多少次页面都只会有一个容器,然后通过spring容器管理对象
//获取容器对象
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
UserService userService = (UserService) context.getBean("userService");
System.out.println(userService);
userService.addUser(name);
//做出响应
response.getWriter().write("成功添加用户");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
---service代码
public class UserService {
public void addUser(String username) {
System.out.println("成功添加了用户:" + username);
}
}
- 写spring的配置文件applicatonContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="UserService"></bean>
</beans>
- 为了防止多次访问页面会生成多个容器对象,我们需要在web.xml中配置对spring的监听,让内存中仅存一个容器对象,这时就会用到spring-web这个spring和web整合的jar包了,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_4_0.xsd"
version="4.0">
<!--配置容器的属性,也就是spring文件的加载路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<!--监听器,监听容器加载-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
- 在servlet中调用即可