鸿 网 互 联 www.68idc.cn

当前位置 : 服务器租用 > 网站制作教程 > JSP > >

Filter Servlet 应用

来源:互联网 作者:佚名 时间:2015-08-19 07:35
利用Filter Servlet 做权限控制。 import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.FilterCh
    利用Filter Servlet 做权限控制。
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;

public class RightFilter
implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
织梦CMS

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;

HttpSession session = req.getSession(true);

//从session里取的用户名信息
String username = (String) session.getAttribute("username");

//判断如果没有取到用户信息,就跳转到登陆页面
if (username == null || "".equals(username)) {
//跳转到登陆页面
res.sendRedirect("http://" req.getHeader("Host") "/login.jsp");
}
else {
//已经登陆,继续此次请求
chain.doFilter(request,response);
}
}

public void destroy() {
}
}



然后在web.xml里配置那些JSP文件需要登陆权限验证:

1.如果是某个具体的JSP文件(如a.jsp)需要登陆验证
<web-app>
...
<filter>
<filter-name>right</filter-name>
<filter-class>com.taihuatalk.taihua.common.common.RightFilter</filter-class>
www.dedecms.com

</filter>

<filter-mapping>
<filter-name>right</filter-name>
<url-pattern>/a.jsp</url-pattern>
</filter-mapping>
...
</web-app>

2.如果是某一个目录(如a/目录)整个目录下的文件都需要登陆验证:
<web-app>
...
<filter>
<filter-name>right</filter-name>
<filter-class>com.taihuatalk.taihua.common.common.RightFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>right</filter-name>
<url-pattern>/a/*</url-pattern>
</filter-mapping>
...
</web-app>import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;

public class RightFilter
implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
织梦CMS

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;

HttpSession session = req.getSession(true);

//从session里取的用户名信息
String username = (String) session.getAttribute("username");

//判断如果没有取到用户信息,就跳转到登陆页面
if (username == null || "".equals(username)) {
//跳转到登陆页面
res.sendRedirect("http://" req.getHeader("Host") "/login.jsp");
}
else {
//已经登陆,继续此次请求
chain.doFilter(request,response);
}
}

public void destroy() {
}
}



然后在web.xml里配置那些JSP文件需要登陆权限验证:

1.如果是某个具体的JSP文件(如a.jsp)需要登陆验证
<web-app>
...
<filter>
<filter-name>right</filter-name>
<filter-class>com.taihuatalk.taihua.common.common.RightFilter</filter-class>
www.dedecms.com


</filter>

<filter-mapping>
<filter-name>right</filter-name>
<url-pattern>/a.jsp</url-pattern>
</filter-mapping>
...
</web-app>

2.如果是某一个目录(如a/目录)整个目录下的文件都需要登陆验证:
<web-app>
...
<filter>
<filter-name>right</filter-name>
<filter-class>com.taihuatalk.taihua.common.common.RightFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>right</filter-name>
<url-pattern>/a/*</url-pattern>
</filter-mapping>
...
</web-app>

==========================
字符集定义,多用与中文问题。
public class CharSetFilter implements  javax.servlet.Filter {

    protected String encoding = null;


    protected FilterConfig filterConfig = null;


    protected boolean ignore = true;


    /**
     * Take this filter out of service.
     */
    public void destroy() {

        this.encoding = null;
        this.filterConfig = null;

    }



    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException {


        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null)
                request.setCharacterEncoding(encoding);
        }

        // Pass control on to the next filter
        chain.doFilter(request, response);

    }


    /**
     * Place this filter into service.
     *
     * @param filterConfig The filter configuration object
     */
    public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");//取web.xml中配的参数
        String value = filterConfig.getInitParameter("ignore");
        if (value == null)
            this.ignore = true;
        else if (value.equalsIgnoreCase("true"))
            this.ignore = true;
        else if (value.equalsIgnoreCase("yes"))
            this.ignore = true;
        else
            this.ignore = false;

    }
    protected String selectEncoding(ServletRequest request) {

        return (this.encoding);

    }

}
web.xml中的配置:
<filter>
        <filter-name>SetEncoding</filter-name>
        <filter-class>com.xxxx.filter.CharSetFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name><!-- 指定编码 -->
            <param-value>GB2312</param-value>
        </init-param>
    </filter>
<filter-mapping>
        <filter-name>SetEncoding</filter-name>
        <url-pattern>/*</url-pattern>//对所有的请求都指定字符集
    </filter-mapping>

权限控制(只判断session有没有值,可以扩展到更复杂)
public class CheckSessionFilter implements Filter {

    protected FilterConfig filterConfig = null;
    protected boolean checkit = true;
    protected String user_key="user_id";
    protected String sessionerror="/error.jsp";
    protected String sessionerror2="";
    protected String special=null;
    /**
     * destroy
     *
     * @todo Implement this javax.servlet.Filter method
     */
    public void destroy() {
        this.filterConfig =null;
        this.checkit =true;
        this.user_key ="user_id";
        this.sessionerror ="/error.jsp";
        this.sessionerror2 ="";
        this.special =null;
    }

    /**
     * doFilter
     *
     * @param servletRequest ServletRequest
     * @param servletResponse ServletResponse
     * @param filterChain FilterChain
     * @throws IOException
     * @throws ServletException
     * @todo Implement this javax.servlet.Filter method
     */
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException,
            ServletException {
        if(servletRequest instanceof HttpServletRequest){
            HttpServletRequest servlets = (HttpServletRequest) servletRequest;
            HttpSession session=servlets.getSession();
            Object user=session.getAttribute(this.user_key );
            //System.out.println(user);
            boolean find=false;
            int types=1;
            if(this.special !=null){
                String[] temp=TheStrings.split(special,",");
                String paths=servlets.getServletPath() ;
                if(paths.indexOf("league")>=0){
                    types=2;
                }
                if(temp.length >=0){
                    for(int i=0;i<temp.length ;i++){
                        if(paths.indexOf(temp[i])>=0) {
                            find=true;
                            break;
                        }
                    }

                }

                //String address=servlets.getr

            }

            if(!find&&(user==null||user.toString() .trim() .length() ==0)){

                if(types==2){
                servletRequest.getRequestDispatcher(this.sessionerror2).forward(servletRequest,servletResponse);
                }
                else{
                servletRequest.getRequestDispatcher(this.sessionerror).forward(servletRequest,servletResponse);
                }


            }else{
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    /**
     * init
     *
     * @param filterConfig FilterConfig
     * @throws ServletException
     * @todo Implement this javax.servlet.Filter method
     */
    public void init(FilterConfig filterConfig2) throws ServletException {
        this.filterConfig = filterConfig2;
        String check=filterConfig.getInitParameter("checkit");
        String user_keys=filterConfig.getInitParameter("user_key");
        String sessionerrors=filterConfig.getInitParameter("errorPath");
        String sessionerrors2=filterConfig.getInitParameter("errorPath_league");
        String specials=filterConfig.getInitParameter("special");
        if(check==null) this.checkit =true;
        else if(check.equals("true")) this.checkit =true;
        else this.checkit =false;
        if(user_keys!=null&&user_keys.trim().length() >0) this.user_key =user_keys;
        if(sessionerrors!=null&&sessionerrors.trim().length() >0) this.sessionerror =sessionerrors;
        if(sessionerrors2!=null&&sessionerrors2.trim().length() >0) this.sessionerror2 =sessionerrors2;
        if(specials!=null&&specials.trim().length() >0) this.special=specials;
    }
}
对应web.xml配置:
<filter>
        <filter-name>checkSession</filter-name>
        <filter-class>com.xxxx.filter.CheckSessionFilter</filter-class>
        <init-param>
            <param-name>checkit</param-name><!-- 是否检查权限 -->
            <param-value>true</param-value>
        </init-param>
                 <init-param>
            <param-name>user_key</param-name><!-- session中的关键key -->
            <param-value>username</param-value>
        </init-param>
                <init-param>
            <param-name>errorPath</param-name>
            <param-value>/error/sessionTimeout.jsp</param-value><!-- 错误页面(后台) -->
        </init-param>
                <init-param>
            <param-name>errorPath_league</param-name>
            <param-value>/error/sessionTimeout2.jsp</param-value><!-- 错误页面(前台)-->
        </init-param>
                <init-param>
                        <param-name>special</param-name>
                        <param-value>redirect.jsp,login.jsp,add</param-value><!-- 不需要权限控制的资源列表 -->
                </init-param>
    </filter>
<filter-mapping>
        <filter-name>checkSession</filter-name>
        <url-pattern>/*.jsp</url-pattern><!-- filter的作用域 -->
    </filter-mapping>

网友评论
<