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. toLocaleString

  2. 从Wordpress迁移到Jekyll

    http://pinkyjie.com/2013/10/24/migrate-from-wordpress-to-jekyll/ 上周末闲着没事干突然想把博客从Wordpress迁移到Github p ...

  3. UI学习笔记---第十三天可视化设计 XIB, StoryBoard

    一.XIB Xib是一种苹果提供的快速构建界面的编程方式,主要是为了简化MVC中的V的构建 Xib提供可视化的编辑界面,能大大提升页面布局效率 Xib常用操作 为控件关联事件 为空间指定delegat ...

  4. php 函数ignore_user_abort()

    ignore_user_abort()  设置与客户机断开是否会终止脚本的执行. 工作中看到这样一个类似的方法,查资料理解了一下: 一个的ignore_user_abort()的例子,配合set_ti ...

  5. 将String类型的XML解析并设置到实体类中

    package com.mooc.string; import java.util.ArrayList; import java.util.List; import org.dom4j.Documen ...

  6. Python学习(2)——编码

    今天写了个程序但是在DOS窗口和IDEL窗口调试的结果不一样,有些郁闷~ #!/usr/bin/env python #coding=utf-8 #python version:2.7.3 #syst ...

  7. kuangbin_UnionFind B (POJ 1611)

    过程是模板 merge完后扫一下几个跟0同祖先节点就是答案了 #include <iostream> #include <string> #include <cstdio ...

  8. display:none,overflow:hidden,visibility:hidden之间的区别

    一,display:none; 隐藏元素,不占网页中的任何空间,让这个元素彻底消失(看不见也摸不着) 二,overflow:hidden; 让超出的元素隐藏,就是在设置该属性的时候他会根据你设置的宽高 ...

  9. bufferedReader 乱码问题

    public static void main(String arsg[]) throws Exception{ BufferedReader bufferedReader = new Buffere ...

  10. Unity资源管理与更新

    当你在 工程目录下的 Asset 文件夹中放置一个文件时(电脑上的文件夹,不是 Unity 界面中的文件夹),Unity会自动检测到一个新的文件被添加(Unity会不停地检查Assets文件夹中的内容 ...