1) 建一个Login Servlet: Login.java

package com.my;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*; public class Login extends HttpServlet {
public Login() {} public void doGet(HttpServletRequest req, HttpServletResponse resp) { try {
String strPath = req.getParameter("path");
if(strPath == null || strPath == "") {
strPath = req.getServletContext().getContextPath();
}
resp.setContentType("text/html;charset=\"UTF-8\"");
PrintWriter pw = resp.getWriter();
pw.println("<html>");
pw.println("<header>");
pw.println("</header>");
pw.println("<body>");
pw.println("<form action=\"login?path=" + java.net.URLEncoder.encode(strPath, "UTF-8") + "\" method=\"POST\">");
pw.println("UserName:<input type=\"text\" id=\"txtUserName\" name=\"txtUserName\" /><br/>");
pw.println("Password:<input type=\"password\" id=\"txtPassword\" name=\"txtPassword\" /><br/>");
pw.println("<input type=\"submit\" value=\"Submit\" />");
pw.println("</form>");
pw.println("</body>");
pw.println("</html>");
}
catch(IOException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
} public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String strUserName = req.getParameter("txtUserName");
String strPassword = req.getParameter("txtPassword");
String strPath = req.getParameter("path");
if(strPath == null || strPath == "") {
strPath = req.getServletContext().getContextPath();
}
if(strUserName.equals("admin") && strPassword.equals("admin")) {
HttpSession session = req.getSession(true);
session.setAttribute("USER", strUserName);
session.setAttribute("ROLE", "admin");
resp.sendRedirect(strPath);
}
else {
resp.sendRedirect("login?path=" + java.net.URLEncoder.encode(strPath, "UTF-8"));
}
}
}

2) 建一个LoginFilter类:LoginFilter.java

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;
import java.util.Map;
import java.util.HashMap;
import java.util.Enumeration; public class LoginFilter implements Filter {
private Map<String, String> _pathMap = new HashMap<String, String>(); public LoginFilter() {} public void init(FilterConfig config) throws ServletException {
System.out.println("login filter init...");
Enumeration enumeration = config.getInitParameterNames();
while(enumeration.hasMoreElements()){
String name = (String)enumeration.nextElement();
String value = config.getInitParameter(name);
_pathMap.put(name, value);
}
} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
System.out.println("login filter doFilter...");
// web-app path, e.x.: /mytest
String strContextPath = req.getServletContext().getContextPath(); HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp; // user request Full URL path, e.x.: /mytest/hello/test
String uri = request.getRequestURI();
// user request file URL path, e.x.: /hello/test
uri = uri.substring(strContextPath.length());
String authPath = null;
String authRole = null; for(String name : _pathMap.keySet()) {
if(uri.startsWith(name)) {
authRole = _pathMap.get(name);
authPath = name;
}
} if( authPath == null ) {
chain.doFilter(req, resp);
return;
}
else {
HttpSession session = request.getSession(false);
if(authRole.equals("admin") && session != null) {
String role = (String)session.getAttribute("ROLE");
if( role != null && role.equals(authRole) ) {
chain.doFilter(req, resp);
}
else {
String strQueryString = (String)request.getQueryString() != null ? "?" + request.getQueryString() : "";
response.sendRedirect(strContextPath + "/login" + "?path=" + java.net.URLEncoder.encode(request.getRequestURI() + strQueryString, "UTF-8"));
}
}
else {
String strQueryString = (String)request.getQueryString() != null ? "?" + request.getQueryString() : "";
response.sendRedirect(strContextPath + "/login" + "?path=" + java.net.URLEncoder.encode(request.getRequestURI() + strQueryString, "UTF-8"));
}
return;
}
} public void destroy() {
System.out.println("login filter destroy");
}
}

web.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true"> <description>
My Test WebSite
</description>
<display-name>My Test WebSite</display-name> <servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.my.Hello</servlet-class>
</servlet>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.my.Login</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping> <filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.my.filter.LoginFilter</filter-class>
<init-param>
<param-name>/admin</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>/hello</param-name>
<param-value>admin</param-value>
</init-param>
</filter>
<filter>
<filter-name>helloFilter</filter-name>
<filter-class>com.my.filter.HelloFilter</filter-class>
</filter> <filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>helloFilter</filter-name>
<url-pattern>/hello</url-pattern>
</filter-mapping> <listener>
<listener-class>com.my.ServletListener</listener-class>
</listener> </web-app>

可以对应不同的角色设置不同的路径访问权限。

使用Servlet Filter做Login checking的更多相关文章

  1. Servlet Filter 2

    10.Filter常见应用 )统一全站字符编码的过滤器 通过配置参数encoding指明使用何种字符编码,以处理Html Form请求参数的中文问题 案例:编写jsp 输入用户名,在Servlet中获 ...

  2. Java Servlet Filter(转)

    做web开发的人对于Filter应该不会陌生,一直在很简单的使用,但是一直没有系统的总结一下,随着年纪的慢慢长大,喜欢总结一些事情,下面说说我对Filter的理解,官方给出的Filter的定义是在请求 ...

  3. Servlet/Filter发布后与其他页面的相对路径

    1.Servlet 3个文件 E:\web.workspace\mldndemo\WebContent\ch14\regist.html E:\web.workspace\mldndemo\WebCo ...

  4. Java Servlet Filter

    做web开发的人对于Filter应该不会陌生,一直在很简单的使用,但是一直没有系统的总结一下,随着年纪的慢慢长大,喜欢总结一些事情,下面说说我对Filter的理解,官方给出的Filter的定义是在请求 ...

  5. servlet/filter/listener/interceptor区别与联系

    转自:http://www.cnblogs.com/doit8791/p/4209442.html servlet.filter.listener是配置到web.xml中(web.xml 的加载顺序是 ...

  6. java Servlet Filter 拦截Ajax请求

    /** * 版权:Copyright 2016-2016 AudaqueTech. Co. Ltd. All Rights Reserved. * 描述: * 创建人:赵巍 * 创建时间:2016年1 ...

  7. 【转】servlet/filter/listener/interceptor区别与联系

    原文:https://www.cnblogs.com/doit8791/p/4209442.html 一.概念: 1.servlet:servlet是一种运行服务器端的java应用程序,具有独立于平台 ...

  8. java Servlet Filter 拦截Ajax请求,统一处理session超时的问题

    后台增加filter,注意不要把druid也屏蔽了 import java.io.IOException; import javax.servlet.Filter; import javax.serv ...

  9. Spring boot中使用servlet filter

    Spring boot中使用servlet filter liuyuhang原创,未经允许请勿转载! 在web项目中经常需要一些场景,如参数过滤防止sql注入,防止页面攻击,空参数矫正等, 也可以做成 ...

随机推荐

  1. Spring AOP配置文件

    在<aop:config>...</aop:config>报错: Multiple annotations found at this line: - cvc-complex- ...

  2. python 中 sorted() 和 list.sort() 的用法

    今天用python自带的sorted对一个列表进行排序, 在这里总结一下 只要是可迭代对象都可以用sorted . sorted(itrearble, cmp=None, key=None, reve ...

  3. spring学习笔记---Jackson的使用和定制

      前言: JAVA总是把实体对象(数据库/Nosql等)转换为POJO对象再处理, 虽然有各类框架予以强力支持. 但实体对象和POJO, 由于"饮食习惯", "民族特色 ...

  4. Integer to Roman

    Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 t ...

  5. CentOS搭建LNMP环境

    安装开发工具包: yum groupinstall -y "Development Tools*" 50多个,安装了好久…… 下载Nginx: http://nginx.org/e ...

  6. Linux 安装rar解压工具

    下载RAR安装包: http://www.rarsoft.com/download.htm 我的是CentOS 64位: wget http://www.rarsoft.com/rar/rarlinu ...

  7. hdu3639 强连通

    题意:有 n 个人,m 组支持关系,已知支持关系可以传递,比如 A 支持 B,则所有支持 A 的人也同时支持 B,问哪些人获得的支持数最多,最多获得多少支持(自己不能获得自己的支持). 首先,如果一些 ...

  8. poj2762 强连通+拓扑序

    题意:有 n 个房间,不同房间之间有单向通道,问是否任意两个房间 A .B 都可以从 A 到 B 或从 B 到 A(有一条有就可以). 在这题中,如果一些点是在同一个强连通分量中,那么这些点肯定能够相 ...

  9. 论文笔记之: Recurrent Models of Visual Attention

    Recurrent Models of Visual Attention Google DeepMind 模拟人类看东西的方式,我们并非将目光放在整张图像上,尽管有时候会从总体上对目标进行把握,但是也 ...

  10. log tree(merge)

    http://www-users.cs.umn.edu/~he/diff/p256-severance.pdf http://www.eecs.harvard.edu/~margo/cs165/pap ...