Java过滤器页面访问权限控制

(..•˘_˘•..) 版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创! (..•˘_˘•..)某些网站的小编真的是眼瞎! 转载注明出处!求求你了!

用户:游客(未登录),学生,老师

权限:游客只能访问login.html,学生登录成功只能访问student.html,老师登录成功只能访问teacher.html

testFilter.java过滤器

import java.io.IOException;
import java.util.ArrayList;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class testFilter
 */
@WebFilter("/*")
public class testFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public testFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * 公共放行页面和servlet
	 */
	private static List<String> common = new ArrayList<>();
	static {
		common.add("/login");
		common.add("/login.html");
	}
	/**
	 * 学生放行页面和servlet
	 */
	private static List<String> student = new ArrayList<>();
	static {
		student.add("/student.html");
	}
	/**
	 * 老师放行页面和servlet
	 */
	private static List<String> teacher = new ArrayList<>();
	static {
		teacher.add("/teacher.html");
	}
	
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		//设置编码
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String urlPattern = req.getServletPath();
		String session = (String) req.getSession().getAttribute("type");
		
		//访问权控制
		if (session == null||session.equals("other")) {
			session = "other";
			common.removeAll(student);
			common.removeAll(teacher);
		} 
		if (session.equals("学生")) {
			common.addAll(student);
			common.removeAll(teacher);
		}
		if (session.equals("老师")) {
			common.addAll(teacher);
			common.removeAll(student);
		}
		for (String url : common) {
			if (url.equals(urlPattern)) {
				chain.doFilter(request, response);
				return;
			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}

登录servlet

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class login
 */
@WebServlet("/login")
public class login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String action=request.getParameter("action");
		if(action.equals("login")) {
			login(request,response);
		}
	}
	
	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		String type=request.getParameter("type");
		if(name.equals("daobin")&&pwd.equals("123456")&&type!=null) {
			request.getSession().setAttribute("type", type); //存入用户类型
			response.getWriter().print("登录成功");
		}
		else {
			request.getSession().setAttribute("type", "other");
			response.getWriter().print("登录失败");
		}
	}
}

登录login.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<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">
<script type="text/javascript"
	src="https://www.idaobin.com/js/jquery-3.2.1.js"></script>
</head>

<body>
	This is Login JSP page.
	<br>
	<input type="text" id="username" placeholder="用户名">
	<input type="text" id="pwd" placeholder="密码">
	<input type="button" id="btn" value="登录">
	<input type="radio" name="type" checked value="学生">学生
	<input type="radio" name="type" value="老师">老师
</body>
<script type="text/javascript">
	$(document).ready(function() {
		$("#btn").click(function() {
			var name=$("#username").val();
			var pwd=$("#pwd").val();
			var type=$("input[name='type']:checked").val();
			$.ajax({
				type : 'Post',
				url : '/testweb/login', //请求地址
				data : {
					name:name,
					pwd:pwd,
					type:type,
					action:"login"
				},
				dataType : 'text', //返回类型

				success : function(data) { //请求成功
					alert(data);
					if(data=="登录成功"&&type=="学生"){
						window.location.href="student.html";
					}
					if(data=="登录成功"&&type=="老师"){
						window.location.href="teacher.html";
					}
				},
				error : function(XMLHttpRequest, textStatus) { //请求失败
					if (textStatus == 'timeout') {
						var xmlhttp = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHttp");
						xmlhttp.abort();
						alert("请求超时");
					} else if (textStatus == "error") {
						alert("服务器内部错误");
					} else if (textStatus == "parsererror") {
						alert("返回类型错误");
					}
				}
			});
		});
	});
</script>
</html>

student.html和teacher.html随便写个html就行了

原文链接:https://www.idaobin.com/archives/2076.html

既然都复制粘贴转载了,就不能打赏一点…ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中

发表评论

电子邮件地址不会被公开。 必填项已用*标注

58 − 50 =