用Filter解决乱码和jsp缓存问题

1) 乱码Filter:

新建一个:CharSetFilter

package com.my.filter;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;

public class CharSetFilter implements Filter {
    public CharSetFilter() {}
    
    public void init(FilterConfig config) throws ServletException {
    }
    
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpServletRequest request = (HttpServletRequest)req;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=\"utf-8\"");
        chain.doFilter(request,response);
    }
    
    public void destroy() {
    }
}

 

修改web.xml

    <filter>
        <filter-name>charsetFilter</filter-name>
        <filter-class>com.my.filter.CharSetFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>charsetFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

2) JSP缓存问题:

新建一个:CacheFilter

package com.my.filter;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;

public class CacheFilter implements Filter {
    public CacheFilter() {}
    
    public void init(FilterConfig config) throws ServletException {
    }
    
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpServletRequest request = (HttpServletRequest)req;
        response.setDateHeader("Expires",-1);
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Pragma","no-cache");
        chain.doFilter(request, response);
    }
    
    public void destroy() {
    }
}

 

修改web.xml

    <filter>
        <filter-name>cahceFilter</filter-name>
        <filter-class>com.my.filter.CacheFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cahceFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>

 

posted @ 2014-03-31 12:02  横渡  阅读(905)  评论(0编辑  收藏  举报