使用Servlet Filter做Login checking
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的更多相关文章
- Servlet Filter 2
10.Filter常见应用 )统一全站字符编码的过滤器 通过配置参数encoding指明使用何种字符编码,以处理Html Form请求参数的中文问题 案例:编写jsp 输入用户名,在Servlet中获 ...
- Java Servlet Filter(转)
做web开发的人对于Filter应该不会陌生,一直在很简单的使用,但是一直没有系统的总结一下,随着年纪的慢慢长大,喜欢总结一些事情,下面说说我对Filter的理解,官方给出的Filter的定义是在请求 ...
- Servlet/Filter发布后与其他页面的相对路径
1.Servlet 3个文件 E:\web.workspace\mldndemo\WebContent\ch14\regist.html E:\web.workspace\mldndemo\WebCo ...
- Java Servlet Filter
做web开发的人对于Filter应该不会陌生,一直在很简单的使用,但是一直没有系统的总结一下,随着年纪的慢慢长大,喜欢总结一些事情,下面说说我对Filter的理解,官方给出的Filter的定义是在请求 ...
- servlet/filter/listener/interceptor区别与联系
转自:http://www.cnblogs.com/doit8791/p/4209442.html servlet.filter.listener是配置到web.xml中(web.xml 的加载顺序是 ...
- java Servlet Filter 拦截Ajax请求
/** * 版权:Copyright 2016-2016 AudaqueTech. Co. Ltd. All Rights Reserved. * 描述: * 创建人:赵巍 * 创建时间:2016年1 ...
- 【转】servlet/filter/listener/interceptor区别与联系
原文:https://www.cnblogs.com/doit8791/p/4209442.html 一.概念: 1.servlet:servlet是一种运行服务器端的java应用程序,具有独立于平台 ...
- java Servlet Filter 拦截Ajax请求,统一处理session超时的问题
后台增加filter,注意不要把druid也屏蔽了 import java.io.IOException; import javax.servlet.Filter; import javax.serv ...
- Spring boot中使用servlet filter
Spring boot中使用servlet filter liuyuhang原创,未经允许请勿转载! 在web项目中经常需要一些场景,如参数过滤防止sql注入,防止页面攻击,空参数矫正等, 也可以做成 ...
随机推荐
- 解决Eclipse Pydev中import时报错:Unresolved import
在安装 图像处理工具包 mahotas 后,在eclipse中尝试import mahotas时,出现Unresolved import错误,按快捷无法自动生成代码提示 但是,程序运行时可以通过,在命 ...
- leetcode 94 Binary Tree Inorder Traversal ----- java
Given a binary tree, return the inorder traversal of its nodes' values. For example:Given binary tre ...
- IOS请求H5页面、要求自定义agent判断是电脑、安卓还是iPhone登录
//自定制的userAgent- (void)createMyAgent{ NSString *userAgent = [[[UIWebView alloc]init]stringByE ...
- strlen() 函数
strlen() 函数通常用来计算字符串的长度,但是今天突然发现个奇怪的现象. 如下所示: #include <stdio.h> #include <stdlib.h> #in ...
- 黑马程序员——JAVA基础之包,权限
------- android培训.java培训.期待与您交流! ---------- 包(package) 对类文件进行分类管理. 给类提供多层命名空间. 写在程序文件的第一行. 类名的全称的是:包 ...
- Java Web学习(1): 客户端请求、服务器响应及其HTTP状态码
一JSP客户端请求 当浏览器请求一个网页时,它会向网络服务器发送一系列不能被直接读取的信息,因为这些信息是作为HTTP信 息头的一部分来传送的.我们可以查阅HTTP协议来获得更多的信息. 下表列出了浏 ...
- 磁盘检验[转自vbird]
磁盘检验 由于系统在运行时谁也说不准啥时硬件或者是电源会有问题,所以『死机』可能是难免的情况(不管是硬件还是软件). 现在我们知道文件系统运行时会有硬盘与内存数据异步的状况发生,因此莫名其妙的死机非常 ...
- (转)word2vec前世今生
word2vec 前世今生 2013年,Google开源了一款用于词向量计算的工具——word2vec,引起了工业界和学术界的关注.首先,word2vec可以在百万数量级的词典和上亿的数据集上进行高效 ...
- php特殊语法--模板引擎中比较常见
<?php $a=array(1,2,0); foreach ($a as $v): if($v>1): ?> 5 <?php endif; endforeach; ?> ...
- PostgreSQL and bloat
The bucardo project has released its nagios plugins for PostgreSQL and we can extract from them this ...