servlet中注入Spring的bean
2013-03-06 14:28:40| 分类: java | 标签:servlet spring bean |举报 |字号 订阅
1、新增servlet类UploadMapServlet.java,并注入spring的bean
package com.cn.lzm.servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class UploadMapServlet extends HttpServlet {
private ServletConfig config = null;
@Autowired(required=true)
private EnterpriseService enterpriseService; //声明spring的bean
public void init(ServletConfig config) throws ServletException {
this.config = config;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doGet(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
//通过setter注入spring的bean
public void setEnterpriseService(EnterpriseService enterpriseService) {
this.enterpriseService = enterpriseService;
}
}
2、在spring配置文件中加入servlet的配置,如下配置
<bean id="uploadMapServlet" class="com.cn.lzm.servlet.UploadMapServlet"></bean>
3、新增代理类HttpServletProxy.java
package com.cn.lzm.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class HttpServletProxy extends HttpServlet {
Log logger = LogFactory.getLog(HttpServletProxy.class);
private String targetBean;
private HttpServlet proxy;
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
proxy.service(req, res);
}
public void init() throws ServletException {
this.targetBean = getServletName();
getServletBean();
proxy.init(getServletConfig());
logger.info(targetBean + "初始化成功................");
}
private void getServletBean() {
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
this.proxy = (HttpServlet) wac.getBean(targetBean);
}
}
4、在web.xml中配置代理类及servlet的路径
<servlet>
<servlet-name>uploadMapServlet</servlet-name>
<servlet-class>wsn.wscmp.web.servlet.HttpServletProxy</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadMapServlet</servlet-name>
<url-pattern>/uploadMap</url-pattern>
</servlet-mapping>
5、页面通过访问 ×××/uploadMap 就可以了。