国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

springSecurity02(mybatis+springmvc+spring) 01

FrancisSoung / 1480人閱讀

摘要:建立一個模塊繼承上一個模塊然后添加依賴解決打包時找不到文件建立數據源文件數據庫連接相關修改配置數據源和整合,以及事務管理自動掃描掃描時跳過注解的類控制器掃描配置文件這里指向的是

1.建立一個模塊繼承上一個模塊然后添加依賴

  

        
            junit
            junit
            4.11
            test
        
        
            org.springframework
            spring-test
            4.2.8.RELEASE
        
        
            org.mybatis
            mybatis
            3.4.4
        
        
            org.mybatis
            mybatis-spring
            1.3.0
        
        
            com.alibaba
            druid
            1.1.8
        
        
            mysql
            mysql-connector-java
            5.1.41
        
    
  
    
    
        
            
                src/main/java
                
                    **/*.xml
                
            
        
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.8
                    1.8
                
            
        
    

2.建立數據源文件application.properties

#數據庫連接相關
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/security-demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username = root
jdbc.password = 123456

3.修改applicationContext.xml,配置數據源,和mybatis整合,以及事務管理




    
    
        
        
        
    

    
    

    
    
          
             
           
           
              
               
              
          
    

    
    
        
        
        
        
    

    
    
        
    

   
    
        
    
    
    

目錄結構,我這里測試mybatis時放在同一包出問題,所以選擇了分別掃描xml和mapper接口

數據庫,總共建立了5張表,用戶表,角色表,用戶角色對應表,權限表,權限角色對應表,關系也很簡單,一個用戶有多個角色,一個角色也可以有多個用戶擁有,一個角色有多種權限,一個權限也可以由多個角色掌握,這個看自己怎么設計,其中用戶表最重要,這里面包含了用戶的基本信息

/*
Navicat MySQL Data Transfer

Source Server         : security
Source Server Version : 50719
Source Host           : localhost:3306
Source Database       : security-demo

Target Server Type    : MYSQL
Target Server Version : 50719
File Encoding         : 65001

Date: 2019-08-02 10:25:48
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for sys_authorization
-- ----------------------------
DROP TABLE IF EXISTS `sys_authorization`;
CREATE TABLE `sys_authorization` (
  `id` int(11) NOT NULL,
  `authorizationName` varchar(50) DEFAULT NULL,
  `authorizationMark` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_authorization
-- ----------------------------
INSERT INTO `sys_authorization` VALUES ("1", "產品查詢", "ROLE_LIST_PRODUCT");
INSERT INTO `sys_authorization` VALUES ("2", "產品添加", "ROLE_ADD_PRODUCT");
INSERT INTO `sys_authorization` VALUES ("3", "產品修改", "ROLE_UPDATE_PRODUCT");
INSERT INTO `sys_authorization` VALUES ("4", "產品刪除", "ROLE_DELETE_PRODUCT");

-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
  `id` int(11) NOT NULL,
  `roleName` varchar(50) DEFAULT NULL,
  `roleDescription` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ("1", "普通用戶", "普通用戶");
INSERT INTO `sys_role` VALUES ("2", "管理員", "管理員");

-- ----------------------------
-- Table structure for sys_role_authorization
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_authorization`;
CREATE TABLE `sys_role_authorization` (
  `roleId` int(11) NOT NULL,
  `authorizationId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_role_authorization
-- ----------------------------
INSERT INTO `sys_role_authorization` VALUES ("1", "1");
INSERT INTO `sys_role_authorization` VALUES ("1", "2");
INSERT INTO `sys_role_authorization` VALUES ("2", "1");
INSERT INTO `sys_role_authorization` VALUES ("2", "2");
INSERT INTO `sys_role_authorization` VALUES ("2", "3");
INSERT INTO `sys_role_authorization` VALUES ("2", "4");

-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  `realname` varchar(50) DEFAULT NULL,
  `createDate` date DEFAULT NULL,
  `lastLoginTime` date DEFAULT NULL,
  `enabled` int(11) DEFAULT NULL,
  `accountNonExpired` int(11) DEFAULT NULL,
  `accountNonLocked` int(11) DEFAULT NULL,
  `credentialsNonExpired` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ("1", "jojo", "$2a$10$VCvgzml/DNzBTkjsPlImDuZp38sNZB7cEmsNgFIWBm/Vtpn0Q3Bj.", "張三", "2019-06-26", "2019-08-01", "1", "1", "1", "1");
INSERT INTO `sys_user` VALUES ("2", "jack", "$2a$10$W1T2Z5dUMIgBfxvFdBOWuusq8Nwke/cQydxDFemsbTh0PjGeZCiMC", "李四", "2019-07-30", "2019-08-01", "1", "1", "1", "1");

-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
  `userId` int(11) NOT NULL,
  `roleId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ("1", "1");
INSERT INTO `sys_user_role` VALUES ("2", "2");

基本配置完成
在mapper文件夾下建立UserMapper接口

package com.ty.mapper;

import com.ty.pojo.Authorization;
import com.ty.pojo.User;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 11:34 2019/8/1
 * @Modificd By:
 */
public interface UserMapper {

    @Select("select * from sys_user")
    List findAll();
    /**
     * 查詢當前用戶對象
     */

    public User findByUserName(String username);


    /**
     * 查詢當前用戶的權限
     */
    List findAuthorizationByUserName(String username);

    /**
     * 修改密碼
     */

    @Update("update sys_user set password=#{password} where username=#{username}")
    public void updatePassword(User user);


}

UserMapper.xml:







    


    

想要測試就這樣


在MainController里面添加一個驗證碼接口(生成驗證碼網上都有,這里就不列出了)

    @RequestMapping("/imageCode")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws Exception {

//        ImageCodeProcessor.send(new ServletWebRequest(request,response),new ImageCodeGenerator().generate(new ServletWebRequest(request)));
        ImageCode generate = new ImageCodeGenerator().generate(new ServletWebRequest(request));
        HttpSession session = request.getSession();
        System.out.println("生成的驗證碼為:"+generate.getCode());
        session.setAttribute("key",generate.getCode());
        response.setContentType("image/jpeg");
        // 將圖像輸出到Servlet輸出流中。
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(generate.getImage(), "jpeg", sos);
        sos.close();
    }

pojo包中的User對象,里面添加了一個權限的字段,是user表中沒有的,并且User對象實現了UserDetails接口,實現了其中的方法,方便后面security使用

package com.ty.pojo;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class User implements UserDetails{

  private Integer id;
  private String username;
  private String password;
  private String realname;
  private java.util.Date createDate;
  private java.util.Date lastLoginTime;
  private boolean enabled;
  private boolean accountNonExpired;
  private boolean accountNonLocked;
  private boolean credentialsNonExpired;

  //用戶擁有的所有權限
  List  authorities=new ArrayList<>();

  @Override
  public String toString() {
    return "User{" +
            "username="" + username + """ +
            ", realname="" + realname + """ +
            ", authorities=" + authorities +
            "}";
  }

  @Override
  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public List getAuthorities() {
    return authorities;
  }



  public void setAuthorities(List authorities) {
    this.authorities = authorities;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getRealname() {
    return realname;
  }

  public void setRealname(String realname) {
    this.realname = realname;
  }

  public Date getCreateDate() {
    return createDate;
  }

  public void setCreateDate(Date createDate) {
    this.createDate = createDate;
  }

  public Date getLastLoginTime() {
    return lastLoginTime;
  }

  public void setLastLoginTime(Date lastLoginTime) {
    this.lastLoginTime = lastLoginTime;
  }

  public boolean isEnabled() {
    return enabled;
  }

  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }

  public boolean isAccountNonExpired() {
    return accountNonExpired;
  }

  public void setAccountNonExpired(boolean accountNonExpired) {
    this.accountNonExpired = accountNonExpired;
  }

  public boolean isAccountNonLocked() {
    return accountNonLocked;
  }

  public void setAccountNonLocked(boolean accountNonLocked) {
    this.accountNonLocked = accountNonLocked;
  }

  public boolean isCredentialsNonExpired() {
    return credentialsNonExpired;
  }

  public void setCredentialsNonExpired(boolean credentialsNonExpired) {
    this.credentialsNonExpired = credentialsNonExpired;
  }
}

其它表就直接用idea自帶的工具:數據庫生成pojo類執行就行了

連接數據庫點擊

springSecurity.xml:里面都有注釋,而且也不難,一看就會系列



    
    
        
        
        
        
        
        

        

        
        



        
        

        


        
        
        

        
        
        
    

    
        
            
            
        
    


    
        
    

    
    

    
    

    


    
    
        
        
        
    

MyUserDetailService :這里就動態在數據庫里面動態查詢了用戶的權限,然后因為之前我們的User類實現了UserDetails接口,所以當返回我們自己從數據庫查詢的用戶然后返回的時候,springSecurity會自己拿著用戶輸入的信息和我們數據庫中的做一個比對,對比上了則認證成功

package com.ty.security;

import com.ty.mapper.UserMapper;
import com.ty.pojo.Authorization;
import com.ty.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 17:09 2019/8/1
 * @Modificd By:
 */
public class MyUserDetailService implements UserDetailsService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=null;
        System.out.println(username);
        if(username!=null&&!username.equals(""))
        {
              user = userMapper.findByUserName(username);
            if (user!=null)
            {
                //獲取用戶權限
                List  permList = userMapper.findAuthorizationByUserName(username);
                List authorizations=new ArrayList<>();
                for (Authorization perm:permList)
                {
                     GrantedAuthority authority=new SimpleGrantedAuthority(perm.getAuthorizationMark());
                     authorizations.add(authority);
                }
                user.setAuthorities(authorizations);
            }
            return user;
        }

        return user;
    }

}

然后我們自定義成功后的處理器MySuccessAthenticationHandler

package com.ty.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 19:43 2019/8/1
 * @Modificd By:
 */
public class MySuccessAthenticationHandler implements AuthenticationSuccessHandler {
    private static final ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Map map=new HashMap();
        map.put("success",true);
        String result = objectMapper.writeValueAsString(map);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(result);
    }
}

失敗處理器:

package com.ty.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 21:23 2019/7/31
 * @Modificd By:
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler{
    private    ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Map map=new HashMap();
        map.put("success",false);
        map.put("errorMsg",e.getMessage());
        String result = objectMapper.writeValueAsString(map);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(result);
    }
}

登錄的時候是先驗證驗證碼,驗證碼通過在驗證用戶名和密碼
驗證碼的攔截器

package com.ty.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author:TY
 * @Descroption:,他能夠確保在一次請求只通過一次filter,而不需要重復執行
 *
 * @Date: Created in 21:22 2019/8/1
 * @Modificd By:
 */
public class ImageCodeAuthenticationFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler authenticationFailureHandler;


    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

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

        //判斷當前請求,是否為登錄請求,
        if (request.getRequestURI().contains("/login"))
        {
           try {
               //校驗驗證碼
               //表單填的驗證碼
               String imageCode = request.getParameter("imageCode");
               System.out.println("表單填的驗證碼為:"+imageCode);
               //系統生成的驗證碼
               HttpSession session = request.getSession();
               String  sesstionCode = (String) session.getAttribute("key");
               System.out.println("session里的驗證碼為:"+sesstionCode);
               if(imageCode==null||imageCode.equals(""))
               {
                   throw new ImageCodeException("驗證碼不能為空");
               }
               if(!imageCode.equals(sesstionCode))
               {
                   throw new ImageCodeException("驗證碼錯誤");
               }
           }catch (AuthenticationException e){
             //交給自定義的
               authenticationFailureHandler.onAuthenticationFailure(request,response,e);
               return;
           }
        }
        filterChain.doFilter(request,response);
    }
}

驗證碼異常類

package com.ty.security;


import org.springframework.security.core.AuthenticationException;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 21:47 2019/8/1
 * @Modificd By:
 */
public class ImageCodeException extends AuthenticationException {

    public ImageCodeException(String msg, Throwable t) {
        super(msg, t);
    }

    public ImageCodeException(String msg) {
        super(msg);
    }
}

注意:我們是把驗證碼過濾器加在UserNamePasswordAuthenticationFilter前面的,當我們的驗證碼拋出異常,驗證碼沒通過時會拋一個ImageCodeException,這個類繼承了AuthenticationException ,所以當拋出異常之后會到我們自定義的MyAuthenticationFailureHandler,這樣就可以向前端返回異常的數據

login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: TY
  Date: 2019/7/31
  Time: 19:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登錄頁面



    用戶名或密碼錯誤

用戶名:
密 碼:
驗證碼:
記住我

如果要根據權限顯示前端內容,就在pom.xml引入

    
      org.springframework.security
      spring-security-taglibs
      4.2.3.RELEASE
    

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: TY
  Date: 2019/7/31
  Time: 16:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="security" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    首頁



    歡迎${username}登陸

以下是網站的功能

    商品添加


    商品修改


    商品查詢



    商品刪除


**最后如果想要獲取認證通過后的用戶的信息,任何地方都能獲取
可以使用SecurityContextHolder.getContext().getAuthentication().getPrincipal()

    /**
     * 首頁  SecurityContextHolder.getContext().getAuthentication().getPrincipal()可以在任何地方獲取當前用戶的信息
     */
    @RequestMapping("index")
    public String index(Model model)
    {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal!=null)
        {
            if(principal instanceof UserDetails)
            {
               UserDetails userDetails= (UserDetails)principal;
               model.addAttribute("username",userDetails.getUsername());
            }
        }
        return "index";
    }

**

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/75767.html

相關文章

  • SpringSecurity系列01】初識SpringSecurity

    摘要:什么是是一個能夠為基于的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。它來自于,那么它與整合開發有著天然的優勢,目前與對應的開源框架還有。通常大家在做一個后臺管理的系統的時候,應該采用判斷用戶是否登錄。 ? 什么是SpringSecurity ? ? Spring Security是一個能夠為基于Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全...

    elva 評論0 收藏0
  • 兩年了,我寫了這些干貨!

    摘要:開公眾號差不多兩年了,有不少原創教程,當原創越來越多時,大家搜索起來就很不方便,因此做了一個索引幫助大家快速找到需要的文章系列處理登錄請求前后端分離一使用完美處理權限問題前后端分離二使用完美處理權限問題前后端分離三中密碼加鹽與中異常統一處理 開公眾號差不多兩年了,有不少原創教程,當原創越來越多時,大家搜索起來就很不方便,因此做了一個索引幫助大家快速找到需要的文章! Spring Boo...

    huayeluoliuhen 評論0 收藏0
  • SpringSecurity01(使用傳統的xml方式開發,且不連接數據庫)

    摘要:創建一個工程在里面添加依賴,依賴不要隨便改我改了出錯了好幾次都找不到原因可以輕松的將對象轉換成對象和文檔同樣也可以將轉換成對象和配置 1.創建一個web工程2.在pom里面添加依賴,依賴不要隨便改,我改了出錯了好幾次都找不到原因 UTF-8 1.7 1.7 2.5.0 1.2 3.0-alpha-1 ...

    Gilbertat 評論0 收藏0
  • Spring4和SpringSecurity4的整合(二)連接mybatis和mysql

    摘要:在上一篇基本配置了一些文件中,基本可以在文件中指定用戶名和密碼來進行實現的驗證,這次和一起來配合使用加入的配置文件別名在的中配置數據源查找配置事物然后建立層,和層以及對應這里省略實 在上一篇基本配置了一些文件中,基本可以在文件中指定用戶名和密碼來進行實現SpringSecurity的驗證,這次和mynatis一起來配合使用 加入mybatis的配置文件: mybatis-config....

    NoraXie 評論0 收藏0

發表評論

0條評論

FrancisSoung

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<