Servlet
过滤器两种配置方法
方法一(注解)
/**
* 使用注解标注过滤器
* @WebFilter将一个实现了javax.servlet.Filte接口的类定义为过滤器
* 属性filterName声明过滤器的名称,可选
* 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
*/
@WebFilter(filterName="TestFilter",urlPatterns="*.action")
方法二(配置web.xml文件)
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>cn.edu.njit.filter.LoginFilter</filter-class>
<init-param>
<param-name>loginUI</param-name>
<param-value>/home/loginUI</param-value>
</init-param>
<init-param>
<param-name>loginProcess</param-name>
<param-value>home/login</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
例:Servlet3.0 以上注解式配置方法
package com.tunny.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 javax.servlet.annotation.WebFilter;
// Servlet3.0 以上注解式配置方法
@WebFilter(filterName="EncodingFilter",urlPatterns="*.action")
public class EncodingFilter implements Filter{
public void destroy() {
}
// 主要的业务逻辑都写在此方法中
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
System.out.println("过滤器帮你转换码完毕");
chain.doFilter(req, resp); // 放行或者向后继续执行
}
public void init(FilterConfig config) throws ServletException {
}
}
Listener监听器
// session="false" 关闭session
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" session="false" %>
网友评论