Java web-Filter coarse-grained permission Control

Source: Internet
Author: User

Java web-Filter coarse-grained permission Control

1 Description

We provide three pages: index. jsp, user. jsp, and admin. jsp.

Index. jsp: no one can access the system. user. jsp: only the logged-on user can access the system. admin. jsp: only the administrator can access the system.

2 Analysis

Design User class: username, password, and grade. grade indicates the User level, 1 indicates the common User, and 2 indicates the administrator User.

After the user successfully logs on, save the user to the session.

Create a LoginFilter. There are two filtering methods:

If user. jsp is accessed, check whether there is a user in the session. If admin. jsp is accessed, check whether there is a user in the session, and the grade of the user is 2.

3 code

 
 
  
   
    LoginServlet
   
   
    com.cug.web.servlet.LoginServlet
   
  
  
   
    LoginServlet
   
   
    /LoginServlet
   
  
      
   
    index.jsp
   
  
  
   
    UserFilter
   
   
    com.cug.filter.UserFilter
   
  
  
   
    UserFilter
   
   
    /user/*
   
  
  
   
    AdminFilter
   
   
    com.cug.filter.AdminFilter
   
  
  
   
    AdminFilter
   
   
    /admin/*
   
  
 

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 {@ Overrideprotected 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 User = UserService. login (username, password); if (user = null) {req. setAttribute ("msg", "incorrect user name or password"); 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
 
   users = new HashMap
  
   ();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 {@ Overridepublic void destroy () {}@ Overridepublic 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 ("the user has not logged on"); request. getRequestDispatcher ("/login. jsp "). forward (req, resp);} if (user. getGrade () <2) {resp. getWriter (). print ("your level is not enough"); return;} chain. doFilter (req, resp) ;}@ Overridepublic 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{@Overridepublic void destroy() {}@Overridepublic 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);}@Overridepublic 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;}@Overridepublic 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 + "/"; %>              My JSP 'admin. jsp 'starting page    
 
 
     
 
 
       Admin. jsp $ {user. username} "> Homepage
"> User page
"> System Administrator

<% @ 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 + "/"; %>              My JSP 'user. jsp 'starting page    
 
 
     
 
 
       User. jsp $ {user. username} "> Homepage
"> User Logon Interface
"> Administrator Logon Interface

<%@ 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+"/";%>              My JSP 'login.jsp' starting page    
 
 
     
 
 
         ${msg }      

<% @ 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 + "/"; %>              My JSP 'index. jsp 'starting page
 
 
     
 
 
       Index. jsp $ {user. username} "> Homepage
"> User Logon Interface
"> Administrator Logon Interface


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.