使用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>
可以对应不同的角色设置不同的路径访问权限。