1、有选择的被访问
描述:首先若用户没有在页面提交注册(直接访问list.jsp),就只能被允许访问a.jsp。其他页面均不被允许访问
在login.jsp提交信息之后,可以在b.jsp访问,
代码如下:
创建留个页面(login.jsp、list.jsp、a.jsp、b.jsp、c.jsp、d.jsp),这里就不写了,可以参考全部代码(在本文的最后面有链接)
创建Logservlet去处理登入后的逻辑处理
package com.gqx.login;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LogServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("user"); if (name!=null && name!="") { request.getSession().setAttribute("user", name); response.sendRedirect(request.getContextPath()+"/login/list.jsp"); }else { response.sendRedirect(request.getContextPath()+"/login/login.jsp"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}
然后是最重要的Filter过滤器了,这里对权限的设置实在web.xml里面配置实现的,如下
userSession USERSISSION rediretPage /login/login.jsp uncheckedUrl /login/a.jsp,/login/list.jsp,/login/login.jsp,/LogServlet LoginFilter com.gqx.login.LoginFilter LoginFilter /login/*
接着是根据xml里面的配置去做有选择性的去做过滤
package com.gqx.login;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import javax.jms.Session;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginFilter implements Filter { private String userSession; private String rediretPage; private String uncheckedUrl; @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub ServletContext servletContext=arg0.getServletContext(); userSession=servletContext.getInitParameter("userSession"); rediretPage=servletContext.getInitParameter("rediretPage"); uncheckedUrl=servletContext.getInitParameter("uncheckedUrl"); } @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request=(HttpServletRequest)arg0; HttpServletResponse response=(HttpServletResponse)arg1; //1、获取来的请求的URL String requestUrl=request.getRequestURL().toString(); // http://localhost:8080/FilterDemo/login/login.jsp String requestUri=request.getRequestURI().toString();// /FilterDemo/login/login.jsp String servletPath=request.getServletPath();// /login/login.jsp //2、检查1获取的servletPath是否为不需要检查的URL中的而一个 Listurls=Arrays.asList(uncheckedUrl.split(",")); if (urls.contains(servletPath)) { arg2.doFilter(request, response); return; } //3、从session中获取userSession,判断值是否存在 Object user=request.getSession().getAttribute("user"); if (user==null) { response.sendRedirect(request.getContextPath()+rediretPage); return; } //4、存在,就允许访问 arg2.doFilter(request, response); } }
根据以上的代码就可以实现那些功能了。
(2)、管理权限的去访问
问题描述:通过设置允许用户去访问某些页面,若设置某用户可以访问某些页面,提交之后,去登入,在列表页根据用户的权限去及时的反应。(由于没有存数据库,本地自己自己认为的加上了两个用户AAA和BBB)
权限修改之后,提交,再去login.jsp去访问,输入用户,便可以去访问相对应权限的文章
实现代码
(1)、首先两个javaBean。User(用于管理其对应的名字和所有的权限)和Authority类(每一个权限以及他的url,通过url去访问其文章)。
package com.gqx.demo1;import java.util.List;// 封装用户信息: Userpublic class User { private String username; private Listauthorities; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public List getAuthorities() { return authorities; } public void setAuthorities(List authorities) { this.authorities = authorities; } public User(String username, List authorities) { super(); this.username = username; this.authorities = authorities; } public User() { // TODO Auto-generated constructor stub }}
package com.gqx.demo1;public class Authority { //显示到页面上的权限的名字 private String displayName; //权限对应的 URL 地址: 已权限对应着一个 URL, 例如 Article-1 -> /article-1.jsp private String url; public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Authority(String displayName, String url) { super(); this.displayName = displayName; this.url = url; } public Authority() { // TODO Auto-generated constructor stub } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((url == null) ? 0 : url.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Authority other = (Authority) obj; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; } }
用户权限的管理(UserDao)
package com.gqx.demo1;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;//用户的权限管理,获取和修改操作public class UserDao { private static Mapusers; //用户所有的权限 private static List authorities =null; //权限的种类 static{ //在authorities中一共有多少种权限 authorities=new ArrayList (); authorities.add(new Authority("Article-1", "/article-1.jsp")); authorities.add(new Authority("Article-2", "/article-2.jsp")); authorities.add(new Authority("Article-3", "/article-3.jsp")); authorities.add(new Authority("Article-4", "/article-4.jsp")); users=new HashMap (); User user1=new User("AAA",authorities.subList(0, 2)); //sublist:左闭右关 users.put("AAA", user1); User user2=new User("BBB",authorities.subList(2,4)); //sublist:左闭右关 users.put("BBB", user2); } //获取用户的全部信息 User get(String username){ return users.get(username); } //修改用户的信息 void update(String name,List authorities){ users.get(name).setAuthorities(authorities); } //获取所有的Authorities(一共有多少种authority) public static List getAuthorities() { return authorities; } public List getAuthorities(String[] urls) { List authorities2 = new ArrayList<>(); for(Authority authority: authorities){ if(urls != null){ for(String url: urls){ if(url.equals(authority.getUrl())){ authorities2.add(authority); } } } } return authorities2; } }
还有两个servlet,第一个是处理用户权限的访问(显示登入者所有的权限)以及修改其对应的权限
package com.gqx.demo1;import java.io.IOException;import java.io.PrintWriter;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class AuthorityServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String methodName=request.getParameter("method"); //为了让一个servlet响应多个请求,这里可以使用反射 try { Method method=getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); method.invoke(this, request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } private UserDao userDao=new UserDao(); //获取用户所有的信息 public void getAuthorities(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName=request.getParameter("username"); User user =userDao.get(userName); request.setAttribute("user", user); request.setAttribute("authorities", userDao.getAuthorities()); request.getRequestDispatcher("/authority-manager.jsp").forward(request, response); } public void updateAuthority(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String [] authorities = request.getParameterValues("authority"); ListauthorityList = userDao.getAuthorities(authorities); userDao.update(username, authorityList); response.sendRedirect(request.getContextPath() + "/authority-manager.jsp"); } }
另一个是登入的servlet(主要是完成登入和注销的功能)
package com.gqx.demo1;import java.io.IOException;import java.io.PrintWriter;import java.lang.reflect.Method;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String methodName=request.getParameter("method"); //为了让一个servlet响应多个请求,这里可以使用反射 try { Method method=getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); method.invoke(this, request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } private UserDao userDao=new UserDao(); public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1、获取用户的username String name=request.getParameter("name"); //2、调用userDao获取信息,把用户信息放入到session中, User user=userDao.get(name); request.getSession().setAttribute("user", user); //3、重定向到article.jsp response.sendRedirect(request.getContextPath()+"/articles.jsp"); } public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 获取 HttpSession //2. 使 HttpSession 失效 request.getSession().invalidate(); //3. 重定向到 /loign.jsp response.sendRedirect(request.getContextPath() + "/login.jsp"); }}
最后是最重要的过滤器了,指定了哪些情况下是可以去访问哪些资源的,以及如何处理没有权限的访问。这里如果没有权限,则会统一去到一个页面(403.jsp)。
package com.gqx.demo1;import java.io.IOException;import java.util.Arrays;import java.util.List;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class AuthorityFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain filterChain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request=(HttpServletRequest)arg0; HttpServletResponse response=(HttpServletResponse)arg1;// - 获取 servletPath, 类似于 /app_3/article1.jsp String servletPath = request.getServletPath(); //不需要被拦截的 url 列表. ListuncheckedUrls = Arrays.asList("/403.jsp", "/articles.jsp", "/authority-manager.jsp", "/login.jsp", "/logout.jsp"); if(uncheckedUrls.contains(servletPath)){ filterChain.doFilter(request, response); return; } // - 在用户已经登录(可使用 用户是否登录 的过滤器)的情况下, 获取用户信息. session.getAttribute("user") User user = (User)request.getSession().getAttribute("user"); if(user == null){ response.sendRedirect(request.getContextPath() + "/login.jsp"); return; } // - 再获取用户所具有的权限的信息: List List authorities = user.getAuthorities(); // - 检验用户是否有请求 servletPath 的权限: 可以思考除了遍历以外, 有没有更好的实现方式 Authority authority = new Authority(null, servletPath); // - 若有权限则: 响应 if (authorities.contains(authority)) { filterChain.doFilter(request, response); return; } // - 若没有权限: 重定向到 403.jsp response.sendRedirect(request.getContextPath() + "/403.jsp"); return; } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub }}
其他的html代码,在文中最后部分有下载