整合Servlet到Spring容器
有时在Spring(3.2.5)项目中,如果使用到Servlet,可能希望Servlet实例作为bean受Spring容器管理,这样也能自动注入其他需要的bean,查了下,发现只针对过滤器提供了代理类org.springframework.web.filter.DelegatingFilterProxy,并没有提供针对Servlet的代理类,于是模仿着写了下面的代理类:
package org.springframework.web.servlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* Servlet代理类,将Servlet托管于Spring容器,以便直接在Servlet内部自动注入其他bean<br>
* 参考 {@code org.springframework.web.filter.DelegatingFilterProxy}<br>
*/
@SuppressWarnings("serial")
public class DelegatingServletProxy extends HttpServletBean {
private String contextAttribute;
private WebApplicationContext webApplicationContext;
private String targetBeanName;
private boolean targetServletLifecycle = true;
private volatile Servlet delegate;
private final Object delegateMonitor = new Object();
public DelegatingServletProxy() {
}
public DelegatingServletProxy(Servlet delegate) {
Assert.notNull(delegate, "delegate Servlet object must not be null");
this.delegate = delegate;
}
public DelegatingServletProxy(String targetBeanName) {
this(targetBeanName, null);
}
public DelegatingServletProxy(String targetBeanName, WebApplicationContext wac) {
Assert.hasText(targetBeanName, "target Servlet bean name must not be null or empty");
this.setTargetBeanName(targetBeanName);
this.webApplicationContext = wac;
if (wac != null) {
this.setEnvironment(wac.getEnvironment());
}
}
public void setContextAttribute(String contextAttribute) {
this.contextAttribute = contextAttribute;
}
public String getContextAttribute() {
return this.contextAttribute;
}
public void setTargetBeanName(String targetBeanName) {
this.targetBeanName = targetBeanName;
}
protected String getTargetBeanName() {
return this.targetBeanName;
}
public void setTargetServletLifecycle(boolean targetServletLifecycle) {
this.targetServletLifecycle = targetServletLifecycle;
}
protected boolean isTargetServletLifecycle() {
return this.targetServletLifecycle;
}
@Override
protected void initServletBean() throws ServletException {
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
if (this.targetBeanName == null) {
this.targetBeanName = this.getServletName();
}
WebApplicationContext wac = this.findWebApplicationContext();
if (wac != null) {
this.delegate = this.initDelegate(wac);
}
}
}
}
@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
Servlet delegateToUse = this.delegate;
if (delegateToUse == null) {
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
WebApplicationContext wac = this.findWebApplicationContext();
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
}
this.delegate = this.initDelegate(wac);
}
delegateToUse = this.delegate;
}
}
this.invokeDelegate(delegateToUse, req, resp);
}
@Override
public void destroy() {
Servlet delegateToUse = this.delegate;
if (delegateToUse != null) {
this.destroyDelegate(delegateToUse);
}
}
protected WebApplicationContext findWebApplicationContext() {
if (this.webApplicationContext != null) {
if (this.webApplicationContext instanceof ConfigurableApplicationContext) {
if (!((ConfigurableApplicationContext) this.webApplicationContext).isActive()) {
((ConfigurableApplicationContext) this.webApplicationContext).refresh();
}
}
return this.webApplicationContext;
}
String attrName = this.getContextAttribute();
if (attrName != null) {
return WebApplicationContextUtils.getWebApplicationContext(super.getServletContext(), attrName);
}
else {
return WebApplicationContextUtils.getWebApplicationContext(super.getServletContext());
}
}
protected Servlet initDelegate(WebApplicationContext wac) throws ServletException {
Servlet delegate = wac.getBean(this.getTargetBeanName(), Servlet.class);
if (this.isTargetServletLifecycle()) {
delegate.init(super.getServletConfig());
}
return delegate;
}
protected void invokeDelegate(Servlet delegate, ServletRequest req, ServletResponse resp) throws ServletException, IOException {
delegate.service(req, resp);
}
protected void destroyDelegate(Servlet delegate) {
if (this.isTargetServletLifecycle()) {
delegate.destroy();
}
}
}
//======================================================//
用法:
1、比如存在test.TestServlet,配置到spring对应xml中:
<bean id="testServlet" class="test.TestServlet" />
2、在web.xml配置如下:
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DelegatingServletProxy</servlet-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>testServlet</param-value>
</init-param>
<load-on-startup>10</load-on-startup>
</servlet>
然后在TestServlet中可自动注入需要的bean。
整合Servlet到Spring容器的更多相关文章
- spring boot整合servlet、filter、Listener等组件方式
创建一个maven项目,然后此项目继承一个父项目:org.springframework.boot 1.创建一个maven项目: 2.点击next后配置父项目及版本号 3.点击finish后就可查看p ...
- spring boot 2.x 系列 —— spring boot 整合 servlet 3.0
文章目录 一.说明 1.1 项目结构说明 1.2 项目依赖 二.采用spring 注册方式整合 servlet 2.1 新建过滤器.监听器和servlet 2.2 注册过滤器.监听器和servlet ...
- spring 整合 servlet
目的:记录spring整合 servlet过程demo.(企业实际开发中可能很少用到),融会贯通. 前言:在学习spring 过程(核心 ioc,aop,插一句 学了spring 才对这个有深刻概念, ...
- Servlet自动注入Spring容器中的Bean解决方法
很多情况在进行Web开发的时候需要自己手写Servlet来完成某些功能,而servlet有需要注入Spring容器中的某些bean,这是每次都要手动获取比较麻烦,这里有一个解决方案,只需要写一个ser ...
- 如何在servlet的监听器中使用spring容器的bean
另外补充下:在web Server容器中,无论是Servlet,Filter,还是Listener都不是Spring容器管理的,因此我们都无法在这些类中直接使用Spring注解的方式来注入我们需要的对 ...
- Spring管理Filter和Servlet(在servlet中注入spring容器中的bean)
在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建.如果要在servlet中使用spring容器管理业务对 ...
- servlet容器,web容器,spring容器,springmvc容器的区别(转)
web容器中有servlet容器,spring项目部署后存在spring容器和springmvc容器.其中spring控制service层和dao层的bean对象.springmvc容器控制contr ...
- Web容器、Servlet容器、Spring容器、SpringMVC容器之间的关系
以下内容为个人理解,如有误还请留言指出,不胜感激! Web容器 web容器(web服务器)主要有:Apache.IIS.Tomcat.Jetty.JBoss.webLogic等,而Tomcat.Jet ...
- Spring Boot整合Servlet,Filter,Listener,访问静态资源
目录 Spring Boot整合Servlet(两种方式) 第一种方式(通过注解扫描方式完成Servlet组件的注册): 第二种方式(通过方法完成Servlet组件的注册) Springboot整合F ...
随机推荐
- JAVA_HOME环境变量失效的解决办法
晚上把oracle自带的weblogic给卸载了,然后打开eclipse,发现报错了:Error: could not open `C:\Java\jre7\lib\amd64\jvm.cfg' JA ...
- 安卓开发:效果图中标注的像素尺寸如何转换为安卓的dp尺寸?
我们的UI基于1920x1080分辨率给的尺寸标注,但是在安卓开发中大家一般都使用dp.sp来标注界面尺寸,所以需要一个dp与sp的转换公式. 一开始参考的的这篇文章:关于Android开发中px.d ...
- WPF中的数据验证
数据验证 WPF的Binding使得数据能够在数据源和目标之间流通,在数据流通的中间,便能够对数据做一些处理. 数据转换和数据验证便是在数据从源到目标 or 从目标到源 的时候对数据的验证和转换. V ...
- jQuery操作单选按钮(radio)用法
1.获取选中值,四种方法都可以: $('input:radio:checked').val():$("input[type='radio']:checked").val(); $( ...
- jquery图片轮播效果(unslider)
今天做网站(住建局网站)需要用到图片轮播,刚开始想借鉴DTCMS上的,查看CSS与页面代码,呵呵,不复杂,直接复制过来,结果调整半天,页面还是各种乱,没办法,网上找一个吧,于是找到了今天要说的这货un ...
- KM模板
var n,m,i,j:longint; ans:int64; sel,lx,ly,slack:..] of int64; a:..,..] of int64; visx,visy:..] of bo ...
- Android开发之ViewPager做新手引导界面
先看一下我们要开发的界面(三张图片,滑到最后一个会出现开始体验的Button,下面的小红点会跟着一起滑动): 首先看一下布局文件: <?xml version="1.0" e ...
- Oracle数据库下sde用户系统表开放权限sql语句
--sde用户登陆执行以下语句 grant insert, update, delete on sde.table_registry to PUBLIC; grant insert, update, ...
- Activiti 学习笔记(2016-8-30)
前言 不管学习什么,都必须对知识体系中专有的名词或者特定的语言组织方式 有所了解. 本文仅记录学习过程中的笔记,参考意义因人而定,不保证所言全部正确. 学习方式,百度传课的视频<权威Activi ...
- editplus-查找替换的正则表达式应用
editplus查找替换的正则表达式应用 表达式 说明 \t 制表符. \n 新行. . 匹配任意字符. | 匹配表达式左边和右边的字符. 例如, "ab|bc" 匹配 " ...