今天用spring ,在web.xml配置时,写过滤器。参考师兄写的代码,过滤器extends OncePerRequestFilter类。发现师兄在过滤器的类里面写了这么一句:
private final static boolean responseSetCharacterEncodingAvailable = ClassUtils.hasMethod(HttpServletResponse.class, "setCharacterEncoding", new Class[] { String.class });
通过查看spring源码知道:该类是判断给定的类有没有给定的方法。
而源码判断是否有该方法时使用了assert,保证类名和方法名均不为空。附源码:
public static boolean hasMethod(Class clazz, String methodName, Class[] paramTypes) {
return (getMethodIfAvailable(clazz, methodName, paramTypes) != null);
}
public static Method getMethodIfAvailable(Class clazz, String methodName, Class[] paramTypes) {
Assert.notNull(clazz, "Class must not be null");
Assert.notNull(methodName, "Method name must not be null");
try {
return clazz.getMethod(methodName, paramTypes);
}
catch (NoSuchMethodException ex) {
return null;
}
}
一般,在Java里面的参数通过spring注入,在配置文件里面配置相应的bean,为bean赋予property,而property可以是基本元素或是其他bean。过滤器的参数在web.xml在配置filter时一并初始化了。
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>common.web.util.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<span style="white-space:pre"> </span><filter-name>encodingFilter</filter-name>
<span style="white-space:pre"> </span><url-pattern>*.htm</url-pattern>
</filter-mapping>
<servlet> <span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"> </span>
通过web.xml告诉服务器使用spring框架的实现是在web.xml进行如下配置:
<span style="white-space:pre"> </span><servlet>
<servlet-name>defaultDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
这样通过
spring-context.xml可以将程序需要的所有配置文件全部都加载进来。