写一个代理类DelegatingServletProxy
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class DelegatingServletProxy extends GenericServlet{
private static final long serialVersionUID = 1L;
private String targetBean;
private Servlet proxy;
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
proxy.service(req, res);
}
@Override
public void init() throws ServletException {
this.targetBean = getServletName();
getServletBean();
proxy.init(getServletConfig());
}
private void getServletBean() {
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
this.proxy = (Servlet) wac.getBean(targetBean);
}
}
web.xml添加URL映射
<servlet>
<servlet-name>userController</servlet-name>
<servlet-class>proxy.DelegatingServletProxy</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>userController</servlet-name>
<url-pattern>/UserController</url-pattern>
</servlet-mapping>
被代理的sevlet不需要加@WebServlet("")
Tips:被代理的servlet bean id 要和web.xml的servlet-name相同
网友评论