换成spring-web后的servlet类:
package com.web.servlet;
import com.service.UserService;
import com.web.listener.WebApplicationContextUtils;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.ServletContext;
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("/UserServlet")
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
ServletContext sc = this.getServletContext();
//ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(sc);
WebApplicationContext app = (WebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);
UserService userService = app.getBean(UserService.class);
userService.save();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
this.doPost(req, res);
}
}
spring-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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
tomcat能连接成功,虚拟目录没有设置,
如果使用自定义的监听器,就没有访问不到servlet的问题