Java web----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>
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);
		}
	}
}
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;
	}
}
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 {

	}

}
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 {

	}

}
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 + "]";
	}
}
<%@ 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%>">

    <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">
	-->

  </head>

  <body>
    <h1>admin.jsp</h1>
    <h3>${user.username }</h3>
    <a href="<c:url value='/index.jsp'/>">首页</a><br/>
    <a href="<c:url value='/user/user.jsp'/>">用户页</a><br/>
    <a href="<c:url value='/admin/admin.jsp'/>">系统管理员</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%>">

    <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">
	-->

  </head>

  <body>
    <h1>user.jsp</h1>
    <h3>${user.username }</h3>
    <a href="<c:url value='/index.jsp'/>">首页</a><br>
    <a href="<c:url value='/user/user.jsp'/>">用户登陆界面</a><br>
    <a href="<c:url value='/admin/admin.jsp'/>">管理员登陆界面</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%>">

    <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">
	-->

  </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%>">

    <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">
	-->
  </head>

  <body>
    <h1>index.jsp</h1>
    <h3>${user.username }</h3>
    <a href="<c:url value='/index.jsp'/>">首页</a><br>
    <a href="<c:url value='/user/user.jsp'/>">用户登陆界面</a><br>
    <a href="<c:url value='/admin/admin.jsp'/>">管理员登陆界面</a><br>
  </body>
</html>
时间: 2024-10-10 10:23:23

Java web----Filter之粗粒度权限控制的相关文章

web day21 web过滤器Filter,应用案例统计IP,解决全站乱码,粗粒度权限控制,页面静态化

JavaWeb三大组件 1. 都需要在web.xml中进行配置 Servlet Listener(2个感知监听器不需要配置) Filter 过滤器 它会在一组资源(jsp.servlet..css..html等等)的前面执行! 它可以让请求得到目标资源,也可以不让请求达到! * 过滤器有拦截请求的能力! 登录: 允许它访问AServlet.BServlet.CServlet ------------------------------- 过滤器如何编写 1. 写一个类实现Filter接口 2.

Asp.net下使用HttpModule模拟Filter,实现权限控制

在asp.net中,我们为了防止用户直接从Url中访问指定的页面而绕过登录验证,需要给每个页面加上验证,或者是在模板页中加上验证.如果说项目比较大的话,添加验证是一件令人抓狂的事情,本次,我就跟大家分享一个利用HttpModule实现权限验证的方法. 第一步: 在项目中新建一个类.cs文件,本例为Filter,应用一下命名空间,主要是为了访问Session. using System.Web.SessionState; 第二步:让这个类继承IHttpModel和IRequiresSessionS

java web filter 学习(2)

本文主要对filter的基本使用进行了讲解,其中涉及到了 filter是什么 一个filter处理一个jsp 多个filter处理一个jsp filter是什么 Filter 是java下的一种过滤器 ,能实现对java web程序 客户端和服务器端消息的过滤,也就是在服务器段接受request之前,可以预先对request进行处理,或在客户端接受response之前,对response进行处理. Filter的使用非常灵活,是在"链"到客户端和服务器之间的,在需要时可以配置到客户端与

学习笔记_过滤器应用(粗粒度权限控制(拦截是否登录、拦截用户名admin权限))

RBAC ->基于角色的权限控制 l  tb_user l  tb_role l  tb_userrole l  tb_menu(增.删.改.查) l  tb_rolemenu 1 说明 我们给出三个页面:index.jsp.user.jsp.admin.jsp. l  index.jsp:谁都可以访问,没有限制: l  user.jsp:只有登录用户才能访问: l  admin.jsp:只有管理员才能访问. 2 分析 设计User类:username.password.grade,其中grad

java web filter 基础

本文主要对Filter的使用进行讲解. 1.Filter是什么? Filter 技术是servlet 2.3 新增加的功能.Filter翻译过来的意思就是过滤器,能对客户端的消息进行预处理,然后将请求转发给其它的web组件,可以对ServletHttpRequest和ServletHttpResponse进行修改和检查.例如:在Filter中可以检查用户是否登录,对未登录的用户跳转到登陆界面. 2.过滤器快速入门 要定义一个过滤器,则需要实现javax.servlet.Filter接口,一个过滤

Java Web Filter登录验证

初做网站需要登录验证,转自 :http://blog.csdn.net/daguanjia11/article/details/48995789 Filter: Filter是服务器端的组件,用来过滤web请求.当发生一个web请求时,web容器会先检查请求的URL是否设置了Filter,如果设置了,则执行该Filter的doFilter方法.所有Filter都实现了javax.servlet.Filter接口,doFilter是定义在该接口中的最重要的方法. 最常见的使用过滤器的例子有:登录访

通过Java Web Filter实现一个最简单的UrlRewrite过滤器

工具:支持JavaEE的Eclipse IDE Web 过滤器可以通过动态Web项目来直接添加:或者直接创建Java项目通过添加类来完成,参看如下过滤器代码: package me.ereach.urlfilter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.se

重读java编程思想之访问权限控制二

private:私有权限 即除了包含该成员的类之外,其他任何类都无法访问这个成员: class Sun{ private Sun(){} static Sun doSun(){ return new Sun(); } } public class IceCream{ public static void main(String[] args){ // Sun s = new Sun(); 这是错误的 Sun s = Sun.doSun(); } } //上面的例子简单的描述了private的一个

java web Filter过滤器解决乱码

package com.kt.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.Serv