1.需要用到两个实体类:
User {
private String username;
private List<Authority> authorities;
}
Authority {
//权限名字
private String displayName;
//权限的地址
private String url;
//hashCode()是用于用户查询时候返回一个url可以根据用户得到权限可以进入网站的作用
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
//用于//当前用户权限和系统所有权限进行对比,如果有相符合的权限
//如何进行判断就在Authority类中 加入equals()与contains进行配合判断.不然没有执行判断
//contains是用于遍历数组判断的 而上面新建了Authority authority =new Authority(null,servletPath);
//并没有进行遍历数组,所以可以直接写到Authority类中
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;
}
}
需要get() and set()
!!!分别给他们造一个无参与有参数的构造器!!!
2 进行实体类的实现
UserDAO{
// 前台需要遍历一个权限的信息
private static List<Authority> authorities = null;
// 静态初始化
private static Map<String, User> users;
static {
// 遍历在首页输出
authorities = new ArrayList<>();
authorities.add(new Authority("Ariticle-1", "/Ariticle-1.jsp"));
authorities.add(new Authority("Ariticle-2", "/Ariticle-2.jsp"));
authorities.add(new Authority("Ariticle-3", "/Ariticle-3.jsp"));
authorities.add(new Authority("Ariticle-4", "/Ariticle-4.jsp"));
// 1 初始化一个用户 分别为用户分配初始值的权限
users = new HashMap<String, User>();
User u1 = new User("a", authorities.subList(0, 2));
users.put("a", u1);
u1 = new User("b", authorities.subList(2, 4));
users.put("b", u1);
}
//得到一个用户的信息
User get(String username) {
return users.get(username);
}
//更新
void update(String username, List<Authority> authorities) {
// 想要更新,先获取用户的信息,然后在保存它的权限.
users.get(username).setAuthorities(authorities);
}
//更新时候显示权限
首先
// 获取全部的Authority
public List<Authority> getAuthorities() {
return authorities;
}
// 更新时候产生的urls
public List<Authority> getAuthorities(String[] urls) {
// 更改后要显示的权限的信息
List<Authority> authorities2 = new ArrayList<>();
// 当前所有的authorities
for (Authority authority : authorities) {
// 如果更新时候的url不为空
if (urls != null) {
// 循环输出一个urls
for (String url : urls) {
//
if (url.equals(authority.getUrl())) {
// 信息比对成功存在这个要更新的urls就会将全部的url列表添加到要更新的列表数据中.
authorities2.add(authority);
}
}
}
}
// 注意返回值,
return authorities2;
}
3.AuthorityServlet 权限的实现servlet
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String methodName = request.getParameter("method");
try {
//反射机制,因为要查数据库返回, method是http中的类别区分.我们将多个dopost方法进行调用时候需要在连接上面区别
//例如AuthorityServlet?method=updateAuthorities
Method method = getClass().getMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
//提供一个userdao的调用
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 updateAuthorities(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//获取页面中需要更改的页面的名字和权限
String username = request.getParameter("username");
//权限是一个数组
String[] authorities =request.getParameterValues("authority");
List<Authority> authoritList=userDAO.getAuthorities(authorities);
userDAO.update(username, authoritList);
response.sendRedirect(request.getContextPath()+"/authority-manager.jsp");
}
}
页面显示是这样的
<body>
<center>
<form action="AuthorityServlet?method=getAuthorities" method="post">
name:<input type="text" name="username" /> <input type="submit"
value="submit" />
</form>
<c:if test="${requestScope.user != null }">
<br>
${requestScope.user.username } 的权限是:
<br>
<form action="AuthorityServlet?method=updateAuthorities"
method="post">
<input type="hidden" name="username"
value="${requestScope.user.username }" />
<!-- 双循环输出 -->
//此处为现在显示的权限用户默认
<c:forEach items="${authorities }" var="auth">
<c:set var="flag" value="false"></c:set>
//此处为用户现在有得权限也是更新后的
<c:forEach items="${user.authorities }" var="ua">
<c:if test="${ua.url == auth.url }">
<c:set var="flag" value="true"></c:set>
</c:if>
</c:forEach>
<c:if test="${flag == true }">
<input type="checkbox" name="authority" value="${auth.url }"
checked="checked" />${auth.displayName }
</c:if>
<c:if test="${flag == false }">
<input type="checkbox" name="authority" value="${auth.url }" />${auth.displayName }
</c:if>
<br>
</c:forEach>
<input type="submit" value="update" />
</form>
</c:if>
</center>
</body>
以上步骤是赋予权限的所有步骤
5制作一个登陆的步骤
页面是这样
<body>
<form action="LoginServlet?method=login" method="post">
name:<input type="text" name="name"/>
<input type="submit" value="submit">
</form>
</body>
6 LoginServlet
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get post都可以相互调用
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String methodName = request.getParameter("method");
try {
// 反射机制
Method method = getClass().getMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
private UserDAO userDAO = new UserDAO();
public void login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
//此处将用户session化
User user =userDAO.get(name);
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath()+"/Ariticle.jsp");
}
public void logout(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取session 注销session
request.getSession().invalidate();
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
}
7制作一个HttpFilter 取代原生的filter 这样就不在权限拦截中做强转
public abstract class HttpFilter implements Filter {
public void destroy() {
}
// 原生的dofilter方法 , 方法内部将ServletRequest ServletResponse 强转为HttpServletRequest
// HttpServletResponse 然后进行调用
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 强转
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 放行
doFilter(request, response, chain);
}
public abstract void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain filterchain)
throws IOException, ServletException;
// 成员变量 保存FilterConfig
private FilterConfig filterConfig;
// 子类覆盖的方法,不建议使用,有可能FilterConfig 成员初始化失败
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
init();
}
// 子类可以使用的初始化方法,可以通过getFilterConfig()获取getFilterConfig对象.
protected void init() {
}
// 直接返回init(servletconfig)对象.
public FilterConfig getFilterConfig() {
return filterConfig;
}
}
8AuthorityFilter编写 直接继承上面的httpservlet
public class AuthorityFilter extends HttpFilter {
@Override
public void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain filterchain)
throws IOException, ServletException {
// 获取拦截的页面的路径 ps:如果使用原生的那么就需要强转HttpServletRequest
String servletPath = request.getServletPath();
// 直接将不需要拦截的页面进行写死
List<String> uncheckUrls = Arrays.asList("/Ariticle.jsp",
"/authority-manager.jsp", "/login.jsp", "/403.jsp","/logout.jsp");
// 请求的地址和不需要拦截的地址一致,那么就可以直接放行
if(uncheckUrls.contains(servletPath)){
filterchain.doFilter(request, response);
return;
}
// 如果用户登陆,获取用户信息,
User user =(User)request.getSession().getAttribute("user");
if(user==null){
response.sendRedirect(request.getContextPath()+"/login.jsp");
return;
}
//获取用户全部的权限信息
List<Authority> authorities =user.getAuthorities();
//检查用户是否有servletPath的请求/初始化参数
Authority authority =new Authority(null,servletPath);
//当前用户权限和系统所有权限进行对比,如果有相符合的权限
//如何进行判断就在Authority类中 加入equals()与contains进行配合判断.不然没有执行判断
//contains是用于遍历数组判断的 而上面新建了Authority authority =new Authority(null,servletPath);
//并没有进行遍历数组,所以可以直接写到Authority类中
if(authorities.contains(authority)){
filterchain.doFilter(request, response);
return;
}
//如果没有权限
response.sendRedirect(request.getContextPath()+"/403.jsp");
return;
}
}