当前位置:网站首页>Day 4 of SSM practice_ Get user name_ User exit_ User CRUD_ Password encryption_ Roles_ jurisdiction
Day 4 of SSM practice_ Get user name_ User exit_ User CRUD_ Password encryption_ Roles_ jurisdiction
2022-07-26 18:16:00 【Miracles are created by persistent people】
List of articles
- One 、 Chapter one : The user authentication function is perfect
- Chapter two : User module
- The third chapter : Role module
- Chapter four : Authority module
One 、 Chapter one : The user authentication function is perfect
Section 1 : Display user name function
Use SpringSecurity When the frame operates ,SpringSecurity A context object will be generated SecurityContext, The context object will be automatically stored in session domain , At the same time, the context object will be bound to the current thread , adopt SecurityContext You can obtain the authentication object Authentication, And the authentication object Authentication It's encapsulated inside principal( Lead ) attribute , The principal Is the current user object User, and User Objects naturally contain information such as user names .
Acquisition process :SecurityContext—>Authentication—>User—>username
1、 How to get user name 1 :
The server side can be programmed API The way to get
@RequestMapping("/showUsername")
public void showUsername(HttpServletRequest request){
// obtain session object
HttpSession session = request.getSession();
// from session Get... In domain username [ The frame helps you put session key How much is? ?]
// The method is what people think Try getting all the attribute names first
Enumeration attributeNames = session.getAttributeNames();
// Traversing enumeration types Just like traversing the result set
while(attributeNames.hasMoreElements()){
System.out.println(attributeNames.nextElement());
}
// only one :SPRING_SECURITY_CONTEXT
// seeing the name of a thing one thinks of its function The context object of the security framework It is not a simple key value pair Instead, it encapsulates a class object into session in
//System.out.println(session.getAttribute("SPRING_SECURITY_CONTEXT"));
SecurityContext securityContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
// Get authentication information from the context object
Authentication authentication = securityContext.getAuthentication();
//Principal: primary ( Is the user object )-- User details (UserDetails)
Object principal = authentication.getPrincipal();
User user= (User) principal;
// Get username
String username = user.getUsername();
System.out.println(username);
// Method 2 So important context It's impossible for you to arrive every time session Take in You have to provide a static method to get it Sure enough
SecurityContext context = SecurityContextHolder.getContext();
System.out.println(context==securityContext);// Get the same object The address is the same ( There can only be one context object )
User user1= (User) context.getAuthentication().getPrincipal();
System.out.println(user1.getUsername());
}
The simple way to get it is :
SecurityContext context = SecurityContextHolder.getContext();
User user= (User) context.getAuthentication().getPrincipal();
System.out.println(user.getUsername());
2、 Method 2 of obtaining user name :
Pass in page el Expression from session Get... In the domain el expression
according to demo session In order to get username Methods It is not difficult to understand this front-end acquisition username Writing
${sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.username}
3、 Get the user name in three ways :
Pass in page SpringSecurity Get the label directly
spring_SECURITY A set of label library provided
Since it is a label library, the waist line must be introduced :
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<security:authentication property="principal.username" />
4、 Display the user name effect

In the second quarter : User exit function
stay header.jsp Write hyperlinks in your page
The path is written as /logout The absolute path is enough logout and /login equally xml The path configured in
<a href="${pageContext.request.contextPath}/logout"
class="btn btn-default btn-flat"> Cancellation </a>
Note that the absolute path must be written 
It's too easy to use when configuring
Chapter two : User module
Section 1 : User list query function
1、 Page entrance

2、 To write Controller
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/findAll")
public ModelAndView findAll(){
List<SysUser> users = userService.findAll();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("users",users);
modelAndView.setViewName("user-list");
return modelAndView;
}
}
3、 To write Service
Interface
public interface UserService extends UserDetailsService{
/** * Query all * @return */
List<SysUser> findAll();
}
Realization
@Override
public List<SysUser> findAll() {
return userdao.findAll();
}
4、 To write Dao
@Select("select * from sys_user")
List<SysUser> findAll();
In the second quarter : Add user functions
1、 Page entrance

When writing the security framework, tables and javaBean Have it all.
2、 To write Controller
@RequestMapping("/save")
public String save(SysUser user){
userService.save(user);
return "redirect:/user/findAll";
}
3、 To write Service
Interface
void save(SysUser user);
Realization
@Override
public void save(SysUser user) {
//user.setPassword(MD5Utils.md5(user.getPassword()));//md5 Encryption exhaustive method can be cracked
userdao.save(user);
}
4、 To write Dao
@Insert("insert into sys_user values(user_seq.nextval,#{username},#{email},#{password},#{phoneNum},#{status})")
void save(SysUser user);
In the third quarter : Determine the unique user name
1、 Page entrance

Write page
<script type="text/javascript">
function isUniqueUsername(a) {
//alert(a.value);// You can get a Represents the whole input box dom Element type
//alert($("#username").val());//jquery The way is sure to get
var username=$("#username").val();
// request controller, Determine whether the user name is unique
// Cannot refresh the entire page Therefore must ajax Asynchronous requests
$.ajax({
url:"${pageContext.request.contextPath}/user/isUniqueUsername",
//data:"username="+username,// The back end can receive
data:{
"username":username},// Back end can also receive
success:function (data) {
//alert(data);
if(data == "false"){
// The return is false String turn json Stream returns
// Prompt that the user name has been occupied -- Set the text box to red , Width is 1, The style is solid line
$("#username").attr("style","border:red 2px solid");//.css Can not use Because there is already class Style
// The Save button is set to unavailable
$("#saveBtn").prop("disabled","disabled");
//attr("disabled","true");// Then write below false It's OK
}else{
// Cancel the pattern
$("#username").removeAttr("style");
$("#username").addClass("form-control")// If the style is gone You need to add the original style
// The Save button is set to available
$("#saveBtn").removeAttr("disabled");
}
},
//dataType:"text",// In general, you can omit
type:"GET"
});
}
</script>
notes :pl/sql development Modified query
select * from sys_user for update;

2、 To write Controller
springMVC The return value is 3 Kind of void string modelAndView No, bool Other types Only one of three
@ResponseBody: Turn the result set into json Return as a stream ( Otherwise, it will enter the view parser and jump 404 page )
//springMVC The return value is 3 Kind of void string modelAndView No, bool Other types Only one of three
//@ResponseBody: Turn the result set into json Return as a stream ( Otherwise, it will enter the view parser and jump 404 page )
@RequestMapping("/isUniqueUsername")
@ResponseBody
public String isUniqueUsername(String username){
LogUtils.print(username);
Boolean b=userService.isUniqueUsername(username);
return ""+b;// Convert to string and return
}
3、 To write service
Interface :
Boolean isUniqueUsername(String username);
Realization :
@Override
public Boolean isUniqueUsername(String username) {
SysUser user = userdao.findAllUserByUsername(username);
return user == null;
}
4、 To write Dao
Pay attention to the front findByUsername Method requires a condition : Closed users are not allowed to log in 
There is no state problem here , Must be judged seriously , Therefore, the previous method cannot be used
/** * Query a single user according to the user name Do not ignore users who are closed * @param username * @return */
@Select("select * from sys_user where username=#{abc}")
SysUser findAllUserByUsername(String username);
The fourth quarter, : Encryption of user password
For the security of customer accounts , The password cannot be displayed in clear text in the database , Therefore, it is necessary to encrypt the password submitted by the client and store it in the database . It can be used md5、 Salt encryption and other tools for password encryption , Currently we use SpringSecurity The framework itself provides encryption tools .
0、md5 encryption
It can be cracked by violence Not good
@Override
public void save(SysUser user) {
// Get clear text password
String password = user.getPassword();
// Encrypt the plaintext password
String md5Password = MD5Utils.md5(password);
// Store the encrypted password in user In the object
user.setPassword(md5Password);
userDao.save(user);
}
1、 stay spring-security.xml Configure encryption class in BCryptPasswordEncoder
<!-- Create encryption tool class object -->
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean>
2、 modify save Business methods
@Autowired
PasswordEncoder passwordEncoder;// above xml Has been created in It's already in the container
@Override
public void save(SysUser user) {
//user.setPassword(MD5Utils.md5(user.getPassword()));//md5 Cannot prevent brute force cracking
user.setPassword(passwordEncoder.encode(user.getPassword()));// The encryption of the security framework is very good
userdao.save(user);
}
3、 Encryption effect

4、 Modify login operation
<!-- Configure authentication information -->
<security:authentication-manager>
<!-- The provider of authentication information : Associate user service object - Provide account number and password -->
<security:authentication-provider user-service-ref="userServiceImpl"><!-- It uses ioc The default name in the container -->
<!-- Encrypt the password when logging in : Specify login encryption tool class -->
<security:password-encoder ref="passwordEncoder"></security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
<!-- Create encryption tool class object Below This configuration is 1 Step adds -->
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean>

modify userServiceImpl The authentication method of loadUserByUsername
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//System.out.println(username);
SysUser sysUser = userdao.findByUsername(username);
if(sysUser==null) return null;
// There is no specified role in the configuration file You need to create your own character object
// Create a character's collection object
Collection<GrantedAuthority> authorities=new ArrayList<>();
// Create a temporary role object Under normal circumstances, it should be checked in the database role table
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
// Objects are added to the collection
authorities.add(grantedAuthority);
//User It is implemented within the security framework UserDetails A class of interface
// The third parameter is : Role list object ( Here the role name ROLE_USER Define your own xml I need this name in )
//{noop} Prefix means no encryption It's time to get rid of non encryption
UserDetails user = new User(sysUser.getUsername(),sysUser.getPassword(),authorities);
return user;
}

notes : It's better to put it below 
The third chapter : Role module
Section 1 : Role table and entity creation
1、 Role TABLE statement and field meaning
create sequence role_seq;
CREATE TABLE sys_role(
id number PRIMARY KEY,
roleName VARCHAR2(50) ,
roleDesc VARCHAR2(50)
)
insert into sys_role values(role_seq.nextval, 'ADMIN',' Administrators ');
select * from sys_role;
Field meaning :
| Serial number | Field name | Field type | Field description |
|---|---|---|---|
| 1 | id | bigint | meaningless , Primary key auto growth |
| 2 | roleName | varchar | The role of |
| 3 | roleDesc | varchar | Role description |
2、Role Entity creation
@Data
public class Role {
private Integer id;
private String roleName;
private String roleDesc;
}
In the second quarter : Role list query function
1、 Page entrance

2、 To write Controller
@Controller
@RequestMapping("/role")
public class RoleController {
@Autowired
RoleService roleService;
@RequestMapping("/findAll")
public ModelAndView findAll(){
List<Role> roles = roleService.findAll();
LogUtils.print(roles);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("roles",roles);
modelAndView.setViewName("role-list");
return modelAndView;
}
}
3、 To write Service
Interface
List<Role> findAll();
Realization
@Override
public List<Role> findAll() {
return roleDao.findAll();
}
4、 To write Dao
@Select("select * from sys_role")
List<Role> findAll();
In the third quarter : Add character features
1、 Page entrance

2、 To write Controller
@RequestMapping("/save")
public String save(Role role){
LogUtils.print(role);
roleService.save(role);
return "redirect:findAll";
}
3、 To write Service
Interface
void save(Role role);
Realization
@Override
public void save(Role role) {
roleDao.save(role);
}
4、 To write Dao
@Insert("insert into sys_role values(role_seq.nextval,#{roleName},#{roleDesc})")
void save(Role role);
Chapter four : Authority module
Section 1 : Permission table and entity creation
1、 Meaning of permission table statement and field
-- Rights management
create sequence permission_seq;
-- pid Associate your own table id It is called superior authority id There is no superior pid by 0
CREATE TABLE sys_permission(
id number PRIMARY KEY,
permissionName VARCHAR2(50) ,
url VARCHAR2(50),
pid number
)
select * from sys_permission for update;
select permission_seq.nextval from dual;
select * from sys_permission;
Add data manually :
Then brush the sequence to 5 Prevent the next insert from always having primary key conflicts
select permission_seq.nextval from dual;

Field meaning :
| Serial number | Field name | Field type | Field description |
|---|---|---|---|
| 1 | id | bigint | meaningless |
| 2 | permissionName | varchar | Authority Name |
| 3 | url | varchar | Resource path |
| 4 | pid | bigint | Parent menu id |
notes : Set up pl/sql development perform sql Auto commit transaction

2、Permission Entity creation
@Data
public class Permission {
private Integer id;
private String permissionName;
private String url;
private Integer pid;// Write simple pid Can't write Permission object Just thinking about it is also a dead cycle
}
In the second quarter : Permission list query function
1、 Page entrance

2、 To write Controller
@RequestMapping("/findAll")
public ModelAndView findAll(){
List<Permission> permissions= permissionService.findAll();
LogUtils.print(permissions);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("permissions",permissions);
modelAndView.setViewName("permission-list");
return modelAndView;
}
3、 To write Service
Interface
List<Permission> findAll();
Realization
@Override
public List<Permission> findAll() {
return permissionDao.findAll();
}
4、 To write Dao
@Select("select * from sys_permission")
List<Permission> findAll();
The front end hasn't been changed much ordinary c:foreach loop
In the third quarter : Add permission function - Echo parent menu
1、 Page entrance

<div class="col-md-2 title"> Parent permissions </div>
<div class="col-md-4 data">
<select class="form-control select2" style="width: 100%"
name="pid">
<c:forEach items="${permissions}" var="p">
<option value="${p.id}" selected="selected">${
p.permissionName}</option>
</c:forEach>
</select>
</div>
2、 To write Controller
/** * Add data echo * It mainly queries all parent permissions in the database Then select and display in the drop-down */
@RequestMapping("/saveUI")
public ModelAndView saveUI(){
List<Permission> permissions=permissionService.findAllParentPermission();
LogUtils.print(permissions);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("permissions",permissions);
modelAndView.setViewName("permission-add");
return modelAndView;
}
3、 To write Service
Interface
/** * Query all parent permissions * @return */
List<Permission> findAllParentPermission();
Realization
@Override
public List<Permission> findAllParentPermission() {
return permissionDao.findAllParentPermission();
}
4、 To write Dao
/** * Query all parent permissions * @return */
@Select("select * from sys_permission where pid=0")
List<Permission> findAllParentPermission();
The fourth quarter, : Add permission function - Save to database
1、 Page entrance

2、 To write Controller
@RequestMapping("/save")
public String save(Permission permission){
LogUtils.print(permission);
permissionService.save(permission);
return "redirect:/permission/findAll";
}
3、 To write Service
Interface
void save(Permission permission);
Realization
@Override
public void save(Permission permission) {
permissionDao.save(permission);
}
4、 To write Dao
/** * Save permission * @param permission */
@Select("insert into sys_permission values(permission_seq.nextval,#{permissionName},#{url},#{pid})")
void save(Permission permission);
Turn the blog see statueStr The meaning of
边栏推荐
- Sign up now | oar hacker marathon phase III midsummer debut, waiting for you to challenge
- openssl
- PMP考试详解,新考纲有什么变化?
- Vector CANoe Menu Plugin拓展入门
- Is it safe for me to open the securities account of CITIC and find the channel manager?
- [day3] reconstruction of roads
- AI zhetianchuan ml unsupervised learning
- 百度飞桨EasyDL X 韦士肯:看轴承质检如何装上“AI之眼”
- ICML 2022 (Part 4) | | graph hierarchical alignment graph kernel to realize graph matching
- Leetcode 0139. word splitting
猜你喜欢

CentOS installs docker and MySQL and redis environments

Kindergarten system based on SSM

Become a test / development programmer, Xiao Zhang: reality is coming

Vector CANoe Menu Plugin拓展入门

Oracle第二天(视图、索引、plsql、游标、存储过程和存储函数、触发器、jdbc访问存储过程和存储函数)

Redisdesktopmanager removes the upgrade prompt

LeetCode50天刷题计划(Day 4—— 最长回文子串 14.00-16:20)

Deep learning experiment: softmax realizes handwritten digit recognition

【静态代码质量分析工具】上海道宁为您带来SonarSource/SonarQube下载、试用、教程

【Unity3D】摇杆
随机推荐
我要开中信的证券账户找渠道的经理开安全吗?
1、 C language program structure, compilation and operation, data type related
The database uses PSQL and JDBC to connect remotely and disconnect automatically from time to time
The second set of 2020 American Asian individual match
Leetcode 50 day question brushing plan (day 2 - the longest substring without repeated characters 10.00-12.00)
ssm练习第四天_获取用户名_用户退出_用户crud_密码加密_角色_权限
Leetcode 50 day question brushing plan (day 4 - longest palindrome substring 14.00-16:20)
Leetcode 50 day question brushing plan (day 1 - add two numbers 11.00-12.30)
有一说一,阿里P7的薪资待遇是真的香
It is said that the salary of Alibaba P7 is really fragrant
2、 Topic communication principle, code implementation
数据仓库:详解维度建模之事实表
[Digital IC] understand Axi Lite protocol in simple terms
跟我学 UML 系统建模
Machine learning by Li Hongyi 2. Regression
7月30号PMP考试延期后我们应该做什么?
LeetCode50天刷题计划(Day 3—— 串联所有单词的子串 10.00-13.20)
推荐效果不如意,不如试试飞桨图学习
Leetcode 0137. number II that appears only once
CentOS installs docker and MySQL and redis environments