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. 八 JDBC

    一 JDBC 简介 1. 作用:规避数据库的不同,为程序开发人员访问数据库提供统一的编程接口. 2. 具体作用:和数据库建立连接,发送 sql 语句,处理数据库返回的结果集. 3. 框架模式: 4. ...

  2. hdu 4248 A Famous Stone Collector

    首先发现一个很头痛的问题,下面是2个求排列组合的代码 memset(C,,sizeof(C)); ;i<;i++) { C[i][]=; ;j<=;j++) C[i][j]=(C[i-][ ...

  3. 安装Python+Pywin32(version 3.3)

    1.下载python3.3,默认设置,安装. 2.完成后,在开始-程序中运行python IDLE.我在运行时出现了应用程序运行异常,原因是与其他软件内存发生冲突,如.net framework等. ...

  4. ZOJ 1068 P,MTHBGWB

    原题链接 题目大意:给定一个字符串,先用Morse Code编码,把编码倒序,再解码成字符串.现给定处理后的字符串,求原始信息. 解法:用C++String类的函数.每次读入一个字符,就在string ...

  5. ZOJ 1216 Deck

    原题链接 题目大意:1/2+1/4+1/6+…1/n 解法:直接累加即可. 参考代码: #include<stdio.h> int main(){ printf("# Cards ...

  6. Matlab GUI设计中的一些常用函数

    Matlab GUI常用函数总结 % — 文件的打开.读取和关闭% — 文件的保存% — 创建一个进度条% — 在名为display的axes显示图像,然后关闭% — 把数字转化为时间格式% — ch ...

  7. rsync+inotify实现服务器数据同步

    一.什么是rsync rsync,remote synchronize是一款实现远程同步功能的软件,它在同步文件的同时,可以保持原来文件的权限.时间.软硬链接等附加信息.rsync是用 “rsync算 ...

  8. 正确答案 全国信息学奥林匹克联赛( ( NOIP2014) 复 赛 模拟题 Day1 长乐一中

    [题目描述]小 H 与小 Y 刚刚参加完 UOIP 外卡组的初赛,就迫不及待的跑出考场对答案."吔,我的答案和你都不一样!",小 Y 说道,"我们去找神犇们问答案吧&qu ...

  9. poj2367 拓扑序

    题意:有一些人他们关系非常复杂,一个人可能有很多后代,现在要制定一种顺序,按照前辈在后代前排列就行 拓扑序裸题,直接建边拓扑排序一下就行了. #include<stdio.h> #incl ...

  10. 使用CURL下载远程文件保存到服务器

    比如微信公众平台开发,下载用户的头像到服务器上: /** * 使用CURL获取远程文件保存到服务器 *@param $image=$oJSON->headimgurl; 获取到的微信返回的头像U ...