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. I.MX6 mfgtool2-android-mx6q-sabresd-emmc.vbs hacking

    /******************************************************************** * I.MX6 mfgtool2-android-mx6q- ...

  2. MyBatis对应的xml的数据类型

    MyBatis对应的xml的数据类型 JDBC Type Java TypeCHAR StringVARCHAR StringLONGVARCHAR StringNUMERIC java.math.B ...

  3. php中将文中关键词高亮显示,快捷方式可以用正则

    php将文中关键词高亮显示,可以用正则表达式 $text = "Sample sentence from AnsonCheung.tk, regular expression has bec ...

  4. php中能够获取到某一网站内容的方法

    方法一:file_get_contents 函数 example: <?php $url = "http://www.cnblogs.com"; $contents = fi ...

  5. word文档快速取消图片的链接

    快捷键Ctrl+Shift+F9 首先,Ctrl+A全选文章或者用鼠标拖动的方法选中部分文中: 批量删除word文档中的超级链接然后,同时按下键盘上的Ctrl+Shift+F9. 效果就出现了! 宏方 ...

  6. Java--接口和类集框架

    一.接口 接口是静态常量和抽象方法的集合.也就是说,接口中只能有静态常量和抽象方法. public interface Pet { public static final int A = 10; pu ...

  7. java的getClass()函数

    Java反射学习 所谓反射,可以理解为在运行时期获取对象类型信息的操作.传统的编程方法要求程序员在编译阶段决定使用的类型,但是在反射的帮助下,编程人员可以动态获取这些信息,从而编写更加具有可移植性的代 ...

  8. bootstrap-3

    段落: 1.全局文本字号为14px(font-size); 2.行高为1.42857143(line-height),大约是20px(一串数字是由less编译器计算出来的,当然sass也有这样的功能) ...

  9. bootStrap-2

    全局样式: 1.移除Body的margin声明: 2.设置Body的背景色为白色: 3.为排版设置了基本的字体,字号和行高: 4.设置全局连接颜色,且当连接处于悬浮:hover状态时,才会显示下划线样 ...

  10. Linux内核编译和运行(转-段玉磊)

    内核获取网站:https://www.kernel.org/pub/linux/kernel/ 步骤如下: 1.打开终端,更改用户权限为root.具体做法是在终端输入sudo su,然后按提示输入密码 ...