1、编码过滤
大家都知道在web开发中,中文在很多时候是乱码,这就需要我们使用统一的编码方式,传统的每个jsp或者servlet中都添加转码代码有很多不便,这时候我们就可以使用过滤器统一进行编码。
public class EncodeingFilter implements Filter {
public String charset;//设置字符编码
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
charset=fConfig.getInitParameter("charset");//初始化字符编码
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// place your code here
request.setCharacterEncoding(charset);//设置统一编码
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#destroy()
*/
public void destroy() {
}
}
web.xml
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.sky.learn.servletfilter.EncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、登录验证
登录验证是web开发中不可缺少的部分,最早的做法是通过验证session的方式完成的,但是如果每个页面都这样做的话,会造成大量的代码重复,也不利于统一维护,通过过滤器可以统一的管理登录验证。
session本身是属于http协议的,但是dofilter方法中定义的是servletrequest类型的对象,要取得session对象,就必须进行向下转型,将servletrequest转换为httpservletrequest对象,才能通过getsession的方法获取session对象。
public class LoginFilter implements Filter {
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// place your code here
HttpServletRequest req=(HttpServletRequest)request;//向下转型
HttpSession session=req.getSession();//获取session
if(session.getAttribute("userid")!=null){
chain.doFilter(request, response);
}
else{
request.getRequestDispatcher("login.jsp").forward(request, response);//跳转到登录页
}
}
/**
* @see Filter#destroy()
*/
public void destroy() {
}
}