编写一个servlet代理,如下:
- public class DelegatingServletProxy extends GenericServlet{
- private static final long serialVersionUID = 1L;
- private String targetBean;//目标bean
- 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中配置Spring自动加载的监听,用以启动Spring容器,配置需要的servlet,并将servlet的类指向刚才的代理。
三、编写一个bean,继承自HttpServlet,它将是响应请求的servlet。然后在applicationContext.xml中为其注入,要注意注入bean的名字需和web.xml中写的servlet的servlet-name一致。然后可以随便为这个bean注入什么样的值。