asp.net中,如果开发人员想自己处理http请求响应,可以利用HttpHandler来满足这一要求;类似的,如果要拦截所有http请求,可以使用HttpMoudle。java的web开发中,也有类似的处理机制,与HttpHandler应对的是HttpServlet,与HttpModule对应的则是Filter。
一、HttpServlet
先看一个简单的示例:
package com.cnblogs.yjmyzz.servlet; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class SampleServlet extends HttpServlet { private static final long serialVersionUID = 7065409287377444221L; public SampleServlet(){
System.out.println("SampleServlet is initialized!");
} protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("<h1>SampleServlet.doGet() is called!</h1>"); } protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { response.getWriter()
.append("<h1>SampleServlet.doPost() is called!</h1>"); } }
在HttpServlet中,程序员得自己控制所有要在页面上输出的内容,类似ASP.NET HttpHandler中Response.Write(...)一样。
自定义的Servlet必须在web.xml中注册才能使用,参考下面的配置片段:
<servlet>
<servlet-name>Sample</servlet-name>
<servlet-class>com.cnblogs.yjmyzz.servlet.SampleServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Sample</servlet-name>
<url-pattern>/A/*</url-pattern>
</servlet-mapping>
第2行与第7行的servlet-name要一致;url-pattern表示该Servlet要拦截的url,如果写成"/*",则表示拦截所有url请求;load-on-startup是可选节点,如果该节点值>0时,webapp一启动就会自动实例化该Servlet,否则将延时到第一次访问被拦截的url时,才会被实例化。
如果web.xml中同时注册了多个Servlet,且都指定了load-on-startup,将按照load-on-startup节点值从小到大的优先级顺序,依次实例化所有注册的Servlet。
如果多个Servlet同时拦截了相同的url,则根据它们出现在web.xml中的顺序,仅最后出现的Servlet具有拦截处理权。
二、Filter
还是先来一个最基本的示例
package com.cnblogs.yjmyzz.filter; import java.io.IOException; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; public class AnotherFilter implements Filter { @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public void doFilter(ServletRequest reqeust, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
response.getWriter().append("<h1>AnotherFilter.doFilter is called!</h1>");
chain.doFilter(reqeust, response);
} @Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub } }
注意下24行,开发人员自定义的处理完成后,最后记得调用chain.doFilter(reqeust, response),因为每一次http请求的完整处理通常会有很多个Filter按顺序协作完成,这些Filter形成一个”链式结构“,这一行的作用,就是当自己的处理完成后,继续交给Filter链中的下一个Filter去处理。
同样,Filter也必须在web.xml中注册方能使用:
<filter>
<filter-name>Filter2</filter-name>
<filter-class>com.cnblogs.yjmyzz.filter.AnotherFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
第2行与第6行的filter-name要保持一致;url-pattern为要拦截的url;如果一个web.xml中同时注册多个Filter,所有这些Filter都将起作用,处理的顺序按照在web.xml中出现的顺序,先出现的Filter先处理。
如果web.xml中同时注册了Servlet、Filter,且拦截的url相同时,Filter先处理,之后才轮到Servlet处理。
三、参数注入
通常在写Servlet、Filter时,有时候需要从外界获取一些参数,先来看下Filter的参数处理:
a) Filter基本String参数注入
package com.cnblogs.yjmyzz.filter; import java.io.IOException; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; public class AnotherFilter implements Filter {
// 定义参数变量
private String someParamter; @Override
public void destroy() { } @Override
public void doFilter(ServletRequest reqeust, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
response.getWriter().append(
"<h1>AnotherFilter.doFilter is called!" + someParamter
+ "</h1>");
chain.doFilter(reqeust, response);
} @Override
public void init(FilterConfig cfg) throws ServletException {
// 取得传入的参数
someParamter = cfg.getInitParameter("someParameter"); } }
代码很简单,在init方法中接收参数即可,这个参数是从哪里传进来的呢?看下面的web.xml配置
<filter>
<filter-name>Filter2</filter-name>
<filter-class>com.cnblogs.yjmyzz.filter.AnotherFilter</filter-class>
<init-param>
<param-name>someParameter</param-name>
<param-value>HelloWorld</param-value>
</init-param>
</filter>
init-param节点就是答案
b) Filter复杂对象的参数注入
如果要传的参数是一个复杂对象,上面的方法就不太适合(当然:你可以把对象序列化成json字符串,然后到init中接收,再反序列,理论上也可行,但是比较感觉比较怪。)
先定义一个参数对象:
package com.cnblogs.yjmyzz.filter; public class SampleData { private String someField; public String getSomeField() {
return someField;
} public void setSomeField(String someField) {
this.someField = someField;
} }
为了对比,再来一个Filter
package com.cnblogs.yjmyzz.filter; import java.io.IOException; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import org.springframework.beans.factory.annotation.Autowired; public class SampleFilter implements Filter { @Autowired
SampleData someData; @Override
public void destroy() { } @Override
public void doFilter(ServletRequest reqeust, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
response.getWriter().append(
"<h1>SampleFilter.doFilter is called!"
+ someData.getSomeField() + "</h1>");
chain.doFilter(reqeust, response);
} @Override
public void init(FilterConfig filterConfig) throws ServletException { } public SampleData getSomeData() {
return someData;
} public void setSomeData(SampleData someData) {
this.someData = someData;
} }
这里,我们希望SomeFilter在运行时,能动态注入一个SomeData实例。下面是配置部分:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="someData" class="com.cnblogs.yjmyzz.filter.SampleData">
<property name="someField" value="abc"></property>
</bean> <bean id="sampleFilter" class="com.cnblogs.yjmyzz.filter.SampleFilter">
<property name="someData" ref="someData"></property>
</bean> </beans>
spring的xml配置中,先定义好SomeFilter的bean,然后是web.xml的Filter配置:
<filter>
<description>Filter1</description>
<display-name>Filter1</display-name>
<filter-name>Filter1</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>sampleFilter</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
对比下刚才的Filter配置,有几个变化:
filter-class 换成了 org.springframework.web.filter.DelegatingFilterProxy
init-param 节点通过targetBeanName 这个参数名,将sampleFilter bean动态注入
再来看看Servlet的参数注入,spring并没有提供类似DelegatingServletProxy的代理类,所以只能自己动手了,下面是二种常见做法:
a) 通过init方法,实现Servlet的Spring bean注入
package com.cnblogs.yjmyzz.servlet; import java.io.IOException; import javax.servlet.*;
import javax.servlet.http.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import com.cnblogs.yjmyzz.filter.SampleData; public class SampleServlet extends HttpServlet { private static final long serialVersionUID = 7065409287377444221L; SampleData someData; public SampleServlet() {
System.out.println("SampleServlet is initialized!");
} protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { response.getWriter().append(
"<h1>SampleServlet.doGet() is called!"
+ someData.getSomeField() + "</h1>"); } protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { response.getWriter().append(
"<h1>SampleServlet.doPost() is called!</h1>"); } public void init() throws ServletException {
super.init();
ServletContext servletContext = this.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
someData = ctx.getBean("someData", SampleData.class);
}
}
关键在于init方法,通过Spring的WebApplicationContext拿到上下文,然后手动去获取bean实例
b) 自己实现ServletProxy,实现注入
先定义ServletProxy代理类:
package com.cnblogs.yjmyzz.servlet; import java.io.IOException; import javax.servlet.*;
import javax.servlet.http.HttpServlet; import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; public class HttpServletProxy extends HttpServlet { private static final long serialVersionUID = 4358391761577767574L; 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());
} private void getServletBean() {
WebApplicationContext wac = WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());
this.proxy = (HttpServlet) wac.getBean(targetBean);
} }
本质上ServletProxy也是一个Servlet,在init方法中,通过动态获取servletName,利用Spring的WebApplicationContextt得到真正需要的Servlet Bean实例并保存在proxy变量中,最终对http执行处理的(即:调用service方法的),是proxy变量所指向的Servlet Bean实例。
定义真正需要使用的Servlet
package com.cnblogs.yjmyzz.servlet; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cnblogs.yjmyzz.filter.SampleData; public class AnotherServlet extends HttpServlet { private static final long serialVersionUID = -3797187540470927379L; // 需要注入的Bean
SampleData someData; public AnotherServlet() {
System.out.println("AnotherServlet is initialized!");
} protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { response.getWriter().append(
"<h1>AnotherServlet.doGet() is called!"
+ someData.getSomeField() + "</h1>"); } protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { response.getWriter().append(
"<h1>AnotherServlet.doPost() is called!</h1>"); } public void setSomeData(SampleData someData) {
this.someData = someData;
} }
在spring的beans配置文件中,配置该Servlet Bean
<bean id="someData" class="com.cnblogs.yjmyzz.filter.SampleData">
<property name="someField" value="abc"></property>
</bean> <bean id="anotherServlet" class="com.cnblogs.yjmyzz.servlet.AnotherServlet">
<property name="someData" ref="someData"></property>
</bean>
最后是web.xml配置
<servlet>
<servlet-name>anotherServlet</servlet-name>
<servlet-class>com.cnblogs.yjmyzz.servlet.HttpServletProxy</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>anotherServlet</servlet-name>
<url-pattern>/A/*</url-pattern>
</servlet-mapping>
注:web.xml中的servlet-name节点值,必须于spring beans配置文件中的bean id一致,因为ServletProxy是根据ServletName来查找Bean实例的。