filter过滤器 的初步使用,以及他的基本应用

来源:互联网 发布:java报表开发工具 编辑:程序博客网 时间:2024/06/12 01:13

一,设置项目的字符
myfilter.java

public class myfilter implements Filter {    private String ecodingString="";    public void destroy() {        // TODO Auto-generated method stub    }    public void doFilter(ServletRequest req, ServletResponse resp,            FilterChain chain) throws IOException, ServletException {            req.setCharacterEncoding(ecodingString);            resp.setCharacterEncoding(ecodingString);            resp.setContentType("text/html");            chain.doFilter(req, resp);    }    public void init(FilterConfig arg0) throws ServletException {        this.ecodingString=arg0.getInitParameter("ecoding");    }}

web.xml

<filter>    <filter-name>myfilter</filter-name>    <filter-class>com.bright.filter.myfilter</filter-class>        <init-param>            <param-name>ecoding</param-name>            <param-value>utf-8</param-value>        </init-param>     </filter>  <filter-mapping>    <filter-name>myfilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>

(2)拦截非法登录
isLoginfilter.java

public class isloginFilter implements Filter {    public void destroy() {        // TODO Auto-generated method stub    }    public void doFilter(ServletRequest req, ServletResponse resp,            FilterChain chain) throws IOException, ServletException {        HttpSession session=((HttpServletRequest)req).getSession();        String islogin=(String)session.getAttribute("uname");        if("ok".equals(islogin)){            chain.doFilter(req, resp);        }else{            //在filter中一定要用绝对路径!一定,一定,一定!以‘/’开头的就是绝对路径            ((HttpServletResponse)resp).sendRedirect("/day08/please");        }    }    public void init(FilterConfig arg0) throws ServletException {        // TODO Auto-generated method stub    }}

web.xml

<filter>    <filter-name>isf</filter-name>    <filter-class>com.bright.filter.isloginFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>isf</filter-name>    <url-pattern>/show</url-pattern>  </filter-mapping>

三,转载的用法说明

http://www.cnblogs.com/xdp-gacl/p/3948422.html

0 0
原创粉丝点击