不同角色登录及菜单内容权限

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24192465/article/details/83307759

<%@ page language="java" pageEncoding="UTF-8"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!doctype html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title><spring:message code="label.app.title"/></title>
    <title>登录</title>
    <link href="assets/css/sign_in.css" rel="stylesheet" />
</head>



 <body class="signin_background">
        <header class="signin_header"><img src="assets/img/moofen_logo.png" /> 欢迎登录</header>
        <article class="signin_frame">
            <h1>后台登录</h1>
            <p class="error_p visibility_hidden">密码不正确</p>
            <form id="loginForm" >
            <ul>
                <li>
                    <div class="signin_flex_div">
                        <img src="assets/img/man_icon.png" />
                        <input type="text" placeholder="请输入用户名" id="loginName" name="loginName" required />
                    </div>                    
                </li>
                <li>
                    <div class="signin_flex_div">
                        <img src="assets/img/lock_icon.png" />
                        <input type="password" placeholder="请输入登录密码" id="password" name="password" required />
                    </div>                    
                </li>
                <li>
                    <div class="flex_between">
                    <label class="checkbox_label"><input type="checkbox" class="checkbox_style" />记住用户名</label>
                    <a href="${pageContext.request.contextPath}/cube_resetpw.html">忘记密码?</a>
                    </div>  
                </li>
            </ul>
            	<input id="loginButton" type="button" value="登录" class="model_btn mt5" />
                
            </form>    
        </article>
        <footer class="signin_footer">
            Copyright ©2014-2017 上海牧分信息科技有限公司<br/>( 沪ICP 备11022765号-9)
        </footer>
    </body>

</html>
<script src="assets/js/jquery.min.js"></script>
<script>
	$("#loginButton").click(function() {
	console.log(1);
	console.log($("#loginForm").serialize());
		$.ajax({
			method : "POST",
			url : "${pageContext.request.contextPath}/user/login",
			data : $("#loginForm").serialize(),
			success : function(data) {
			console.log(data.code);
				 if (data.code == 0) {
                    window.location.href = "${pageContext.request.contextPath}/sign_in2.html";
                    return;
                }else{	
                	alert("[" + data.code + "][" + data.message + "]");	
                }	
			}
		})
	});
	
	
	
	
</script>

Form表单要点:配置name属性

package com.moofen.cube.controller.ume.login;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.moofen.core.constant.AuthConstant;
import com.moofen.core.constant.SessionConstant;
import com.moofen.core.entity.sys.um.RoleBase;
import com.moofen.core.mvc.controller.BaseController;
import com.moofen.core.mvc.view.BaseResult;
import com.moofen.cube.service.ume.login.LoginService;

@Controller
@RequestMapping("/user")
public class LoginController extends BaseController {

	@Resource(name = "loginService")
	private LoginService loginService;

	@ResponseBody
	@PostMapping("/login")
	public JSONObject login(@RequestParam(name = "loginName", required = true) String loginName,
			@RequestParam(name = "password", required = true) String password) {
		JSONObject result = loginService.login(loginName, password);
		BaseResult baseResult = JSON.parseObject(result.toJSONString(), BaseResult.class);
		// session中存储账号
		if (baseResult.isSuccess()) {
			// 设定Session变量
			JSONObject data = result.getJSONObject("data");
			// 当前身份
			RoleBase roldBase = JSON.parseObject(data.getString(SessionConstant.CURR_USER_ROLE), RoleBase.class);
			if (roldBase != null) {
				// 当前用户
				getRequest().getSession().setAttribute(SessionConstant.USER_CODE, data.get(SessionConstant.USER_CODE));
				// 当前角色
				getRequest().getSession().setAttribute(SessionConstant.CURR_USER_ROLE,
						data.get(SessionConstant.CURR_USER_ROLE));
				// 当前系统
				getRequest().getSession().setAttribute(AuthConstant.SYS_CODE_CUBE, AuthConstant.SYS_CODE_CUBE);

			}
		}
		return result;
	}

	/**
	 * 退出系统
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value = "/logout")
	public String logout(HttpSession session) throws Exception {
		// 清除Session
		session.invalidate();
		return "redirect:../login.html";
	}
}

要点:在session里放登录用户信息

package com.moofen.cube.controller.ume.login;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.moofen.core.constant.SessionConstant;

public class SessionFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		// 不过滤的uri
		String[] notFilter = new String[] { "login", "sign_in1", "cube_resetpw", "frameworks", "assets" };

		// 请求的uri
		String uri = request.getRequestURI();

		// 是否过滤
		boolean doFilter = true;
		for (String s : notFilter) {
			if (uri.indexOf(s) != -1) {
				// 如果uri中包含不过滤的uri,则不进行过滤
				doFilter = false;
				break;
			}
		}
		if (doFilter) {
			// 执行过滤
			// 从session中获取登录者实体
			Object obj = request.getSession().getAttribute(SessionConstant.USER_CODE);
			if (null == obj) {
				String loginUrl = request.getContextPath() + "/sign_in1.html";
				response.sendRedirect(loginUrl);
			} else {
				// 如果session中存在登录者实体,则继续
				filterChain.doFilter(request, response);
			}
		} else {
			// 如果不执行过滤,则继续
			filterChain.doFilter(request, response);
		}
	}

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>Moofen Cube Web</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/spring/applicationContext*.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
	</listener>

	<filter>
		<filter-name>log4jServletFilter</filter-name>
		<filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>log4jServletFilter</filter-name>
		<url-pattern>/</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
		<dispatcher>ERROR</dispatcher>
	</filter-mapping>

	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>sessionFilter</filter-name>
		<filter-class>com.moofen.cube.controller.ume.login.SessionFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>sessionFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value></param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>sign_in1.html</welcome-file>
	</welcome-file-list>

	<error-page>
		<location>/error</location>
	</error-page>

</web-app>

 配置登录过滤,除了个别页面,其它所有页面需要登录成功后才有权限访问

 角色列表页面

<%@ page language="java" pageEncoding="UTF-8"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!doctype html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>登录</title>
    <link href="assets/css/sign_in.css" rel="stylesheet" />
</head>

<body>
    <article class="resetpw_article">
        <div class="signin_div">
        <h2>选择登录者身份</h2>
            <ul class="select_ul">
                
            </ul>
    </div>
    </article>
    <footer class="resetpw_footer">
            Copyright ©2014-2017 上海牧分信息科技有限公司( 沪ICP 备11022765号-9)
    </footer>    
</body>

</html>
<script src="assets/js/jquery.min.js"></script>
<script>
    var signin2={
        //身份数据
       // body_data:[{"id":"1","name":"管理员"},{"id":"2","name":"某校校长"},{"id":"3","name":"某校教务主任"},{"id":"4","name":"语文老师"},{"id":"5","name":"数学老师"},{"id":"6","name":"5年级年级组长"}],
        //ul绑定相应的身份
        bind_select_ul: function(){
        
        	var body_data;
			$.ajax({
				type : "get",
				async:false,
				url : "${pageContext.request.contextPath}/ume/sys/um/roles/list",
				dataType: 'json',
				success : function(s) {
					body_data = s.data;
				},
				error : function(XMLHttpRequest, textStatus, errorThrown){
					datas = XMLHttpRequest.data;
					console.error("XMLHttpRequest:",XMLHttpRequest);
					console.error("textStatus:",textStatus);
					console.error("errorThrown:",errorThrown);
				}
			});
            var html="";
            $.each(body_data, function(index,value){
                //html +=`<li><a href="sign_in3.html?${value.id}" data-id="${value.id}">${value.name}</a></li>`;
                html +="<li><a href=pages/cube.html?roleCode="+value.roleCode+">"+value.showName+"</a></li>";
            });
            $(".select_ul").html(html);   
        },
        //自动运行
        init: function(){
            this.bind_select_ul();
        }
    };
    signin2.init();
</script>
package com.moofen.cube.controller.ume.sys.um;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.moofen.core.constant.SessionConstant;
import com.moofen.core.entity.sys.um.RoleBase;
import com.moofen.core.mvc.controller.BaseController;
import com.moofen.cube.service.ume.sys.um.RoleBaseService;

@Controller
@RequestMapping("/ume/sys/um/roles")
public class RoleController extends BaseController{
	
	@Resource(name = "roleBaseService")
	private RoleBaseService roleBaseService;
	
	@ResponseBody
	@GetMapping("/list")
	public JSONObject listRoles(HttpServletRequest request) {
		String userCode = (String)request.getSession().getAttribute(SessionConstant.USER_CODE);
		return roleBaseService.listRoles(userCode);
	}

	@ResponseBody
	@GetMapping("/select")
	public JSONObject select(HttpServletRequest request) {
		String roleId=request.getParameter("roleCode");
		JSONObject obj = roleBaseService.getRole(roleId);
		JSONObject result = obj.getJSONObject("data");
		RoleBase roleBase = JSON.parseObject(result.toJSONString(),RoleBase.class);
		request.getSession().setAttribute(SessionConstant.CURR_USER_ROLE, roleBase);
		return obj;
	}
	
}
<%@ page language="java" pageEncoding="UTF-8"%>
<!doctype html>
<html>

<head>
<meta charset="utf-8" />
<meta name="viewport"
	content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=0">
<meta name="format-detection" content="telephone=no" />
<meta name="format-detection" content="email=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="description" content="多分科技">
<meta name="keywords" content="多分科技">
<title>cube首页</title>
<!--[if lt IE 9]>
            <script src="http://cdn.static.runoob.com/libs/html5shiv/3.7/html5shiv.min.js"></script>
            <script src="../js/ie9.js"></script> 
        <![endif]-->
<script src="../assets/js/jquery.min.js"></script>
<link rel="shortcut icon" href="../assets/img/cube-icon.png" />
<link href="../assets/css/style.css" rel="stylesheet">
<link href="../assets/css/sign_in.css" rel="stylesheet">
</head>

<body>
	<div class="wrapper">
		<header class="cube_header">
			<div>
				<a href="javascript:void(0)" class="header_logo" id="toggle_nav_btn"
					title="点击隐藏/显示左边栏"></a>
				<nav>
					<ul class="header_nav_ul">
					</ul>
				</nav>
			</div>
			<nav>
				<!--  切换身份-->
				<div id="link_content">
					<div id="identity_div">
						<ul>
						</ul>
						<button id="turn_identity_btn">开始切换</button>
					</div>
					<div class="top">切换身份</div>
				</div>
				<button id="turn_identity_btn" onclick="sign_in3.open_window()">打开切换窗口</button>
				<script type="text/html" id="window_tmpl">
        <div class="window_identity_background">
            <div class="bt_close"></div>
            <div class="window_identity_div">
                <h2>切换身份</h2>
                <ul>                   
                </ul>
                <div class="tec_div">
                    <button id="click_identity_btn">开始切换</button>
                </div>                
            </div>
        </div>
    </script>
				<!--  切换身份END-->
				<a href="javascript:void(0)" title="消息"><i
					class="iconfont icon-xiaoxi"></i></a> <a href="javascript:void(0)"
					title="设置"><i class="iconfont icon-shezhi"></i></a> <a
					href="javascript:void(0)" title="退出"><i
					class="iconfont icon-tuichu"></i></a>
			</nav>
		</header>
		<article class="cube_article">
			<article></article>
			<article></article>
			<article></article>
			<article></article>
			<article></article>
			<article></article>
			<article></article>
		</article>
		<footer class="cube_footer"> </footer>
		<form></form>
	</div>
</body>

</html>
<script>var menus_Items=[];
var school_data;
var menus_data;
    var sign_in3 = {
        //身份数据
        //body_data:[{"id":"1","name":"管理员"},{"id":"2","name":"某校校长"},{"id":"3","name":"某校教务主任"},{"id":"4","name":"语文老师"},{"id":"5","name":"数学老师"},{"id":"6","name":"5年级年级组长"}],
        //身份绑定到切换内容
        
	         getQueryString: function(name){
	     		var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	     		var r = window.location.search.substr(1).match(reg);
	     		if(r!=null)return  unescape(r[2]); return null;
			},

		get_data : function(url, data) {
			//Tomd.wait('加载中...');
			var datas;
			$.ajax({
				type : "get",
				async : false,
				url : url,
				data : data,
				success : function(s) {
					//Tomd.waitok();
					datas = s.data;
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					datas = XMLHttpRequest.data;
					console.error("XMLHttpRequest:", XMLHttpRequest);
					console.error("textStatus:", textStatus);
					console.error("errorThrown:", errorThrown);
				}
			});
			return datas;
		},

		bind_identity: function() {

				var data1 = {};
				var body_data = this.get_data("${pageContext.request.contextPath}/ume/sys/um/roles/list", data1);

			// 调用方法
			var roleCode = this.getQueryString("roleCode");

			//当前角色
			var data2 = {"roleCode": roleCode};
			var role_data = this.get_data("${pageContext.request.contextPath}/ume/sys/um/roles/select", data2);
			
			//菜单列表
			var data3 = {"roleCode": roleCode};
			menus_data = this.get_data("${pageContext.request.contextPath}/ume/sys/um/userAuthorization/listMenus", data3);
			
			//学校列表
			var data4 = {"roleCode": roleCode};
			school_data = this.get_data("${pageContext.request.contextPath}/ume/sys/um/userAuthorization/listSchools", data4);

			var html = "";
            $.each(body_data, function(index,value){
                if(roleCode == value.roleCode)
                   html +="<li><label><input type='radio' name='radio_identity' value='"+value.roleCode+"' checked />"+value.showName+"</label></li>";
                else
                    html +="<li><label><input type='radio' name='radio_identity' value='"+value.roleCode+"' />"+value.user.showName+"</label></li>";
            });
            $("#identity_div ul").html(html);
			$("#turn_identity_btn").on("click", function() {
				roleCode = $("input[name='radio_identity']:checked").val();

				//当前角色
				var data2 = {
					"roleCode" : roleCode
				};
				var role_data = sign_in3.get_data("${pageContext.request.contextPath}/ume/sys/um/roles/select", data2);

				//菜单列表
				var data3 = {
					"roleCode" : roleCode
				};
				menus_data = sign_in3.get_data("${pageContext.request.contextPath}/ume/sys/um/userAuthorization/listMenus", data3);

				//学校列表
				var data4 = {
					"roleCode" : roleCode
				};
				school_data = sign_in3.get_data("${pageContext.request.contextPath}/ume/sys/um/userAuthorization/listSchools", data4);
				location=location.href.split("?")[0]+"?roleCode="+roleCode;
			})
		},
        //弹出选项窗口
        open_window: function(){
            var html=$("#window_tmpl").html();
            $(document.body).append(html);
            this.bind_window_identity();
            this.close_window();
        },
        //身份绑定到窗口中的切换内容
        bind_window_identity: function() {

			var data1 = {};
			var body_data = this.get_data("${pageContext.request.contextPath}/ume/sys/um/roles/list", data1);
			
			// 调用方法
			var roleCode = this.getQueryString("roleCode");
			var html="";
            $.each(body_data, function(index,value){
                if(roleCode == value.roleCode)
                   html +="<li><label><input type='radio' name='window_radio_identity' value='"+value.roleCode+"' checked />"+value.showName+"</label></li>";
                else
                     html +="<li><label><input type='radio' name='window_radio_identity' value='"+value.roleCode+"' />"+value.showName+"</label></li>";
            });
            $(".window_identity_div ul").html(html);
			$("#click_identity_btn").on("click", function(){
                roleCode = $("input[name='window_radio_identity']:checked").val();
                $(".window_identity_background").remove();
                
                //当前角色
				var data2 = {
					"roleCode" : roleCode
				};
				var role_data = sign_in3.get_data("${pageContext.request.contextPath}/ume/sys/um/roles/select", data2);

				//菜单列表
				var data3 = {
					"roleCode" : roleCode
				};
				menus_data = sign_in3.get_data("${pageContext.request.contextPath}/ume/sys/um/userAuthorization/listMenus", data3);
				//学校列表
				var data4 = {
					"roleCode" : roleCode
				};
				school_data = sign_in3.get_data("${pageContext.request.contextPath}/ume/sys/um/userAuthorization/listSchools", data4);
				location=location.href.split("?")[0]+"?roleCode="+roleCode;
			})
        },
        //点击关闭符号关闭窗口
        close_window: function(){
            $(".bt_close").on("click", function(){
                $(".window_identity_background").remove();
            });
        },
        //自动运行
        init: function(){
            this.bind_identity();
        },
    };
    sign_in3.init();
</script>

<script src="../assets/js/bootstrap.min.js"></script><script src="../assets/js/model.js"></script>
<script type="text/javascript" src="../assets/js/cube.js"></script><script src="../assets/js/jquery.treegrid.extension.js"></script>

 

package com.moofen.cube.controller.ume.sys.um;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.moofen.core.constant.AuthConstant;
import com.moofen.core.mvc.controller.BaseController;
import com.moofen.cube.service.ume.sys.um.UserAuthorizationService;

@Controller
@RequestMapping("/ume/sys/um/userAuthorization")
public class UserAuthorizationController extends BaseController{
	
	@Resource(name = "userAuthorizationService")
	private UserAuthorizationService userAuthorizationService;
	
	@ResponseBody
	@GetMapping("/listMenus")
	public JSONObject listMenus(HttpServletRequest request) {
		Map<String, Object> params = new HashMap<String, Object>();
		String sysCode = (String)request.getSession().getAttribute(AuthConstant.SYS_CODE_CUBE);
		params.put("roleId", request.getParameter("roleCode"));
		params.put("sysCode", sysCode);
		JSONObject json = userAuthorizationService.listMenus(params);
		return json;
	}

	@ResponseBody
	@GetMapping("/listSchools")
	public JSONObject listSchools(HttpServletRequest request) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("roleId", request.getParameter("roleCode"));
		return userAuthorizationService.listSchools(params);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_24192465/article/details/83307759
今日推荐