Springboot Study Notes: 11. springboot + shiro + mysql + mybatis (General mapper) + freemarker + ztree + layui implement a general java Background Management System (permission management + User Management + menu management ),

Source: Internet
Author: User

Springboot Study Notes: 11. springboot + shiro + mysql + mybatis (General mapper) + freemarker + ztree + layui implement a general java Background Management System (permission management + User Management + menu management ),
I. Preface

After the first 10 articles, we can quickly build a springboot web project;

Today, on the basis of the previous section, we continue to integrate the shiro framework to implement a general background management system, which includes three common management modules: user management, role management, and menu management;

2. database table preparation:

To implement user management, role management, and menu management, we usually use the following five tables ):

3. Integrate shiro and Configuration

1. Add the pom dependency.

<dependency>            <groupId>org.apache.shiro</groupId>            <artifactId>shiro-core</artifactId>            <version>1.4.0</version>        </dependency>        <dependency>            <groupId>org.apache.shiro</groupId>            <artifactId>shiro-spring</artifactId>            <version>1.4.0</version>        </dependency>

 

2. Edit shiro configuration class: ShiroConfig. java

Package com. zjt. config; import com. zjt. realm. myRealm; import org. apache. shiro. mgt. securityManager; import org. apache. shiro. spring. lifecycleBeanPostProcessor; import org. apache. shiro. spring. security. interceptor. authorizationAttributeSourceAdvisor; import org. apache. shiro. spring. web. shiroFilterFactoryBean; import org. apache. shiro. web. mgt. cookieRememberMeManager; import org. apache. shiro. web. mgt. defaultWebSec UrityManager; import org. apache. shiro. web. servlet. simpleCookie; import org. springframework. context. annotation. bean; import org. springframework. context. annotation. configuration; import java. util. linkedHashMap; import java. util. map;/*** @ Author: Zhaojiatao * @ Description: Shiro configuration class * @ Date: created in * @ param */@ Configurationpublic class ShiroConfig {/*** ShiroFilterFactoryBean handles the interception of resource files. * Note: if a single ShiroFilterFactoryBean is configured or an error is reported, it indicates that injection is required when * ShiroFilterFactoryBean is initialized: SecurityManager ** Filter Chain definition description 1. Multiple filters can be configured for one URL, use commas (,) to separate two filters. If multiple filters are set and all the filters pass the verification, they are considered to pass * 3. Some filters can specify parameters, such as perms, roles **/@ Bean public ShiroFilterFactoryBean shirFilter (SecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean (); // you must set SecurityManager shiroFilterFacto RyBean. setSecurityManager (securityManager); // if this parameter is not set, the system automatically searches for "/login. jsp "Page // shiroFilterFactoryBean. setLoginUrl ("/login. ftl "); // configure the exit filter. The specific exit code Shiro has implemented shiroFilterFactoryBean for us. setLoginUrl ("/tologin"); shiroFilterFactoryBean. setUnauthorizedUrl ("/tologin"); // interceptor. map <String, String> filterChainDefinitionMap = new LinkedHashMap <String, String> (); // configure to remember me or the address that can be accessed through authentication (configure the order of links that will not be blocked to determine) FilterChainDefinitionMap. put ("/static/**", "anon"); filterChainDefinitionMap. put ("/user/login", "anon"); filterChainDefinitionMap. put ("/drawImage", "anon"); // configure the exit filter. The specific exit code Shiro has implemented filterChainDefinitionMap for us. put ("/admin/user/logout", "logout"); // <! -- Filter chain definition, which is executed sequentially from top to bottom. Generally,/** is placed at the bottom -->: This is a pitfall. It is hard to make the code out of caution. // <! -- Authc: All URLs can be accessed only after authentication. anon: All URLs can be accessed anonymously --> filterChainDefinitionMap. put ("/**", "authc"); shiroFilterFactoryBean. setFilterChainDefinitionMap (filterChainDefinitionMap); return shiroFilterFactoryBean;} @ Bean public SecurityManager securityManager () {defawebwebsecuritymanager securityManager = new defawebwebsecuritymanager (); // set realm. securityManager. setRealm (myRealm (); // inject my manager; security Manager. setRememberMeManager (rememberMeManager (); return securityManager;}/*** Identity Authentication realm; (this requires self-writing, account and password verification, and permission verification) ** @ return */@ Bean public MyRealm myRealm () {MyRealm myRealm = new MyRealm (); return myRealm ;} /*** Shiro Life Cycle processor * @ return */@ Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor () {return new LifecycleBeanPostProcessor ();} /*** enable Shiro annotations (for example, @ RequiresRoles and @ Require) SPermissions), you need to use SpringAOP to scan the classes that use the Shiro annotation, and perform security logic verification when necessary * configure the following two beans (DefaultAdvisorAutoProxyCreator (optional) and AuthorizationAttributeSourceAdvisor) you can implement this function * do not use DefaultAdvisorAutoProxyCreator to issue secondary proxy issues. Here we will not detail * @ return * // * @ Bean @ DependsOn ({"lifecycleBeanPostProcessor "}) public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator () {DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultA DvisorAutoProxyCreator (); advisorAutoProxyCreator. setProxyTargetClass (true); return advisorAutoProxyCreator;} */@ Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor () {AuthorizationAttributeSourceAdvisor principal = new principal (); principal. setSecurityManager (securityManager (); return AuthorizationAttributeSourceAdvisor;}/*** cookie object; * It is relatively simple to remember the implementation of the password, mainly to see how it is implemented. * @ Return */@ Bean public SimpleCookie rememberMeCookie () {System. out. println ("ShiroConfiguration. rememberMeCookie () "); // this parameter is the cookie name, corresponding to the front-end checkbox name = rememberMe SimpleCookie simpleCookie = new SimpleCookie (" rememberMe "); // <! -- Remember that the cookie takes effect for 30 days, in seconds. --> simpleCookie. setMaxAge (259200); return simpleCookie;}/*** cookie management object; * @ return */@ Bean public CookieRememberMeManager rememberMeManager () {System. out. println ("ShiroConfiguration. rememberMeManager () "); CookieRememberMeManager cookierembermemanager = new cookieRememberMeManager (); cookierembermemanager. setCookie (rememberMeCookie (); return cookieRememberMeManager ;}}

 

3. Implement custom MyRealm. java

Package com. zjt. realm; import com. zjt. entity. tmenu; import com. zjt. entity. trole; import com. zjt. entity. tuser; import com. zjt. mapper. tmenuMapper; import com. zjt. mapper. troleMapper; import com. zjt. mapper. tuserMapper; import com. zjt. mapper. tuserroleMapper; import org. apache. shiro. securityUtils; import org. apache. shiro. authc. authenticationException; import org. apache. shiro. authc. authenticationInfo; import org. apa Che. shiro. authc. authenticationToken; import org. apache. shiro. authc. simpleAuthenticationInfo; import org. apache. shiro. authz. authorizationInfo; import org. apache. shiro. authz. simpleAuthorizationInfo; import org. apache. shiro. realm. authorizingRealm; import org. apache. shiro. subject. principalCollection; import tk. mybatis. mapper. entity. example; import javax. annotation. resource; import java. util. hashSet; import jav A. util. list; import java. util. set;/*** custom Realm * @ author zjt **/public class MyRealm extends AuthorizingRealm {@ Resource private TuserMapper tuserMapper; @ Resource private TroleMapper troleMapper; @ Resource private TuserroleMapper tuserroleMapper er extends; @ Resource private TmenuMapper tmenuMapper;/*** authorize */@ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals ){ String userName = (String) SecurityUtils. getSubject (). getPrincipal (); // User user = userRepository. findByUserName (userName); // query the user record Example tuserExample = new Example (Tuser. class); tuserExample. or (). andEqualTo ("userName", userName); Tuser user = tuserMapper. selectByExample (tuserExample ). get (0); SimpleAuthorizationInfo = new SimpleAuthorizationInfo (); // List <Role> roleList = roleRepository. findByUs ErId (user. getId (); List <Trole> roleList = troleMapper. selectRolesByUserId (user. getId (); Set <String> roles = new HashSet <String> (); if (roleList. size ()> 0) {for (Trole role: roleList) {roles. add (role. getName (); // List <Tmenu> menuList = menuRepository. findByRoleId (role. getId (); // query all resource lists by role id <Tmenu> menuList = tmenuMapper. selectMenusByRoleId (role. getId (); for (Tmenu menu: menuList) {info. addStringPerm Ission (menu. getName (); // Add permission }}info. setRoles (roles); return info;}/*** permission authentication */@ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {String userName = (String) token. getPrincipal (); // User user = userRepository. findByUserName (userName); Example tuserExample = new Example (Tuser. class); tuserExample. or (). andEqualTo ("userName", us ErName); Tuser user = tuserMapper. selectByExample (tuserExample). get (0); if (user! = Null) {AuthenticationInfo authcInfo = new SimpleAuthenticationInfo (user. getUserName (), user. getPassword (), "xxx"); return authcInfo;} else {return null ;}}}

 

 

4. logon, logout, and permission restrictions

Logon: subject. login (token );

Exit: SecurityUtils. getSubject (). logout ();

Perform permission verification using the shiro annotation before the method. For example, @ RequiresPermissions (value = {"user management"}) indicates that the current user must have the permissions managed by the user;

Iv. Front-end implementation and result display

1. log on

Source code: src \ main \ resources \ templates \ login. ftl

Username: admin

Password: 1

 

2. System Management-menu management

Source code of the menu management page: src \ main \ resources \ templates \ power \ menu. ftl

Use ztree to create, edit, and delete menus;

Background interface of menu management: com. zjt. web. MenuController. java

Note that the level-1 menu is displayed on the top, and the level-1 menu name cannot be a pure number;

Level-2 and level-3 menus are displayed on the left and can only be level-3 menus at most;

 

3. System Management-role management

Src \ main \ resources \ templates \ power \ role. ftl

Com. zjt. web. RoleAdminController. java

The jqgrid table plug-in is used on the page;

You can also set the menu permissions for each role:

4. System Management-user management

Src \ main \ resources \ templates \ power \ user. ftl

Com. zjt. web. UserAdminController. java

 

After selecting a row, you can set the role:

 

V. Postscript

This background management system can be used as a general background management system, which is simple and pure. It has built-in menu management, role management, and user management;

Technologies involved:

Springboot + springmvc + mysql + mybatis + general mapper + paging plug-in + shiro + freemarker + layui + ztree

The layui template uses layuicms2.0.

 

Source code of this project:

Https://github.com/zhaojiatao/springboot-zjt-chapter10-springboot-mysql-mybatis-shiro-freemarker-layui.git

SQL scripts are included in the Project SQL folder.

 

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.