javaweb设计中filter粗粒度权限控制代码示例

 更新时间:2017年10月14日 14:10:42   作者:bluzelee2011  
这篇文章主要介绍了javaweb设计中filter粗粒度权限控制代码示例,小编觉得还是挺不错的,需要的朋友可以参考。

1 说明

我们给出三个页面:index.jsp、user.jsp、admin.jsp。

index.jsp:谁都可以访问,没有限制;

user.jsp:只有登录用户才能访问;

admin.jsp:只有管理员才能访问。

2 分析

设计User类:username、password、grade,其中grade表示用户等级,1表示普通用户,2表示管理员用户。

当用户登录成功后,把user保存到session中。

创建LoginFilter,它有两种过滤方式:

如果访问的是user.jsp,查看session中是否存在user;
如果访问的是admin.jsp,查看session中是否存在user,并且user的grade等于2。

3 代码

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" 
 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_2_5.xsd"> 
<servlet> 
 <servlet-name>LoginServlet</servlet-name> 
 <servlet-class>com.cug.web.servlet.LoginServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
 <servlet-name>LoginServlet</servlet-name> 
 <url-pattern>/LoginServlet</url-pattern> 
</servlet-mapping> 
<welcome-file-list> 
 <welcome-file>index.jsp</welcome-file> 
</welcome-file-list> 
<filter> 
 <filter-name>UserFilter</filter-name> 
 <filter-class>com.cug.filter.UserFilter</filter-class> 
</filter> 
<filter-mapping> 
 <filter-name>UserFilter</filter-name> 
 <url-pattern>/user/*</url-pattern> 
</filter-mapping> 
<filter> 
 <filter-name>AdminFilter</filter-name> 
 <filter-class>com.cug.filter.AdminFilter</filter-class> 
</filter> 
<filter-mapping> 
 <filter-name>AdminFilter</filter-name> 
 <url-pattern>/admin/*</url-pattern> 
</filter-mapping> 
</web-app> 

LoginServlet.java

package com.cug.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cug.domain.User;
import com.cug.web.service.UserService;
public class LoginServlet extends HttpServlet{
	@Override 
	 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
	   throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		User user = UserService.login(username, password);
		if(user == null){
			req.setAttribute("msg", "用户名或者密码错误");
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		} else{
			req.getSession().setAttribute("user", user);
			req.getRequestDispatcher("index.jsp").forward(req,resp);
		}
	}
}

UserService

package com.cug.web.service;
import java.util.HashMap;
import java.util.Map;
import com.cug.domain.User;
public class UserService {
	private static Map<String, User> users = new HashMap<String, User>();
	static{
		users.put("zhu", new User("zhu", "123", 2));
		users.put("xiao", new User("xiao", "123", 1));
	}
	public static User login(String username, String password){
		User user = users.get(username);
		if(user == null) 
		   return null;
		if(!user.getPassword().equals(password)) 
		   return null;
		return user;
	}
}

AdminFilter

package com.cug.filter;
import java.io.IOException;
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 com.cug.domain.User;
public class AdminFilter implements Filter{
	@Override 
	 public void destroy() {
	}
	@Override 
	 public void doFilter(ServletRequest req, ServletResponse resp, 
	   FilterChain chain) throws IOException, ServletException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		HttpServletRequest request = (HttpServletRequest)req;
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			resp.getWriter().print("用户还没有登陆");
			request.getRequestDispatcher("/login.jsp").forward(req, resp);
		}
		if(user.getGrade() < 2){
			resp.getWriter().print("您的等级不够");
			return;
		}
		chain.doFilter(req, resp);
	}
	@Override 
	 public void init(FilterConfig arg0) throws ServletException {
	}
}

UserFilter

package com.cug.filter;
import java.io.IOException;
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 com.cug.domain.User;
public class UserFilter implements Filter{
	@Override 
	 public void destroy() {
	}
	@Override 
	 public void doFilter(ServletRequest request, ServletResponse response, 
	   FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		HttpServletRequest httpReq = (HttpServletRequest)request;
		User user = (User)httpReq.getSession().getAttribute("user");
		if(user == null){
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
		chain.doFilter(request, response);
	}
	@Override 
	 public void init(FilterConfig filterConfig) throws ServletException {
	}
}

User

package com.cug.domain;
public class User {
	private String username;
	private String password;
	private int grade;
	public User() {
		super();
	}
	public User(String username, String password, int grade) {
		super();
		this.username = username;
		this.password = password;
		this.grade = grade;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	@Override 
	 public String toString() {
		return "User [username=" + username + ", password=" + password 
		    + ", grade=" + grade + "]";
	}
}

html

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
 <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 
 <title>My JSP 'admin.jsp' starting page</title> 
 <meta http-equiv="pragma" content="no-cache"> 
 <meta http-equiv="cache-control" content="no-cache"> 
 <meta http-equiv="expires" content="0">  
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
 <meta http-equiv="description" content="This is my page"> 
 <!-- 
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 
 --> 
 </head> 
 <body> 
 <h1>admin.jsp</h1> 
 <h3>${user.username }</h3> 
 <a href="<c:url value='/index.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</a><br/> 
 <a href="<c:url value='/user/user.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >用户页</a><br/> 
 <a href="<c:url value='/admin/admin.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >系统管理员</a><br/> 
 </body> 
</html> 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
 <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 
 <title>My JSP 'user.jsp' starting page</title> 
 <meta http-equiv="pragma" content="no-cache"> 
 <meta http-equiv="cache-control" content="no-cache"> 
 <meta http-equiv="expires" content="0">  
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
 <meta http-equiv="description" content="This is my page"> 
 <!-- 
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 
 --> 
 </head> 
 <body> 
 <h1>user.jsp</h1> 
 <h3>${user.username }</h3> 
 <a href="<c:url value='/index.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</a><br> 
 <a href="<c:url value='/user/user.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >用户登陆界面</a><br> 
 <a href="<c:url value='/admin/admin.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >管理员登陆界面</a><br> 
 </body> 
</html> 

用户登录

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
 <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 
 <title>My JSP 'login.jsp' starting page</title> 
 <meta http-equiv="pragma" content="no-cache"> 
 <meta http-equiv="cache-control" content="no-cache"> 
 <meta http-equiv="expires" content="0">  
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
 <meta http-equiv="description" content="This is my page"> 
 <!-- 
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 
 --> 
 </head> 
 <body> 
 ${msg } 
 <form action="<c:url value='/LoginServlet'/>" method="post"> 
  用户名:<input type="text" name="username"/><br/> 
  密码:<input type="password" name="password"/><br/> 
  <input type="submit" value="登陆"/> 
 </form> 
 </body> 
</html> 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
 <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 
 <title>My JSP 'index.jsp' starting page</title> 
 <meta http-equiv="pragma" content="no-cache"> 
 <meta http-equiv="cache-control" content="no-cache"> 
 <meta http-equiv="expires" content="0">  
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
 <meta http-equiv="description" content="This is my page"> 
 <!-- 
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 
 --> 
 </head> 
 <body> 
 <h1>index.jsp</h1> 
 <h3>${user.username }</h3> 
 <a href="<c:url value='/index.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</a><br> 
 <a href="<c:url value='/user/user.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >用户登陆界面</a><br> 
 <a href="<c:url value='/admin/admin.jsp'/>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >管理员登陆界面</a><br> 
 </body> 
</html> 

总结

以上就是本文关于javaweb设计中filter粗粒度权限控制代码示例的全部内容,感兴趣的朋友可以继续参阅:JavaWeb项目中dll文件动态加载方法解析(详细步骤)Javaweb使用cors完成跨域ajax数据交互Javaweb项目session超时解决方案等。

希望对大家有所帮助,如有不足之处,欢迎留言指正。感谢大家对本站的支持!

相关文章

  • Nebula Graph介绍和SpringBoot环境连接和查询操作

    Nebula Graph介绍和SpringBoot环境连接和查询操作

    Nebula Graph 是一款开源的、分布式的、易扩展的原生图数据库,能够承载包含数千亿个点和数万亿条边的超大规模数据集,并且提供毫秒级查询,这篇文章主要介绍了Nebula Graph介绍和SpringBoot环境连接和查询,需要的朋友可以参考下
    2022-10-10
  • SpringBoot整合Quartz方法详解

    SpringBoot整合Quartz方法详解

    这篇文章详解介绍了SpringBoot整合Quartz的方法,Quartz是一个比较成熟了的定时任务框架,本文实例代码给大家详细讲解,需要的朋友可以参考下
    2023-04-04
  • centos7如何通过systemctl启动springboot服务代替java -jar方式启动

    centos7如何通过systemctl启动springboot服务代替java -jar方式启动

    这篇文章主要介绍了centos7如何通过systemctl启动springboot服务代替java -jar方式启动,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2024-01-01
  • 深入解析Java的设计模式编程中的模板方法模式

    深入解析Java的设计模式编程中的模板方法模式

    这篇文章主要介绍了深入解析Java的设计模式编程中的模板方法模式, 模版方法模式由一个抽象类和一个(或一组)实现类通过继承结构组成,需要的朋友可以参考下
    2016-02-02
  • Springboot下RedisTemplate的两种序列化方式实例详解

    Springboot下RedisTemplate的两种序列化方式实例详解

    这篇文章主要介绍了Springboot下RedisTemplate的两种序列化方式,通过定义一个配置类,自定义RedisTemplate的序列化方式,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-09-09
  • Java创建并运行线程的方法

    Java创建并运行线程的方法

    这篇文章主要介绍了Java创建并运行线程的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • Spring Framework远程代码执行漏洞分析(最新漏洞)

    Spring Framework远程代码执行漏洞分析(最新漏洞)

    Spring Framework 是一个开源应用框架,旨在降低应用程序开发的复杂度,它具有分层体系结构,允许用户选择组件,同时还为 J2EE 应用程序开发提供了一个有凝聚力的框架,对Spring远程代码执行漏洞相关知识感兴趣的朋友一起看看吧
    2022-04-04
  • XML操作类库XStream使用详解

    XML操作类库XStream使用详解

    这篇文章主要给大家介绍了关于XML操作类库XStream使用的相关资料,需要的朋友可以参考下
    2023-11-11
  • Java Hibernate使用SessionFactory创建Session案例详解

    Java Hibernate使用SessionFactory创建Session案例详解

    这篇文章主要介绍了Java Hibernate使用SessionFactory创建Session案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • Java FTPClient实现文件上传下载

    Java FTPClient实现文件上传下载

    这篇文章主要为大家详细介绍了Java FTPClient实现文件上传下载的相关资料,需要的朋友可以参考下
    2016-04-04

最新评论