In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to modify springboot user data". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to modify springboot user data" can help you solve the problem.
Modify password 1 user-change password-persistence layer 1.1 Plan the SQL statements to be executed
The SQL statements that a user needs to execute when changing a password are roughly:
UPDATE t_user SET password=?, modified_user=?, modified_time=? WHERE uid=?
Before you change the password, you should also check the existence of the user data, check that the user data is marked as deleted, and check that the original password is correct, all of which can be assisted by querying user data:
SELECT * FROM t_user WHERE uid=?1.2 Interface and Abstract method
Add updatePasswordByUid (Integer uid,String password,String modifiedUser,Date modifiedTime) abstract methods to the UserMapper interface.
When using annotations to simplify xml configuration, the @ Param annotation is used to name the parameters. After naming the parameters, you can get the parameter values according to their names, and correctly pass the parameters into the sql statement. The parameter name in the @ Param ("parameter name") annotation needs to be consistent with the parameter name of # {parameter name} in the sql statement.
/ * update the user's password according to uid * @ param uid user's id * @ param password new password * @ param modifiedUser Last change executor * @ param modifiedTime Last modification time * @ return number of rows affected * / Integer updatePasswordByUid (@ Param ("uid") Integer uid, @ Param ("password") String password, @ Param ("modifiedUser") String modifiedUser @ Param ("modifiedTime") Date modifiedTime) / * * query user data based on user id * @ param uid user id * @ return matching user data. If no matching user data is found, null * / User findByUid (Integer uid) is returned. 1.3 configure SQL mapping
1. Configure the mapping of updatePasswordByUid () and findByUid () abstract methods in UserMapper.xml.
UPDATE t_user SET password = # {password}, modified_user = # {modifiedUser}, modified_time = # {modifiedTime} WHERE uid = # {uid} SELECT * FROM t_user WHERE uid = # {uid}
two。 Write and execute unit tests in UserMapperTests.
@ Testpublic void updatePasswordByUid () {Integer uid = 7; String password = "123456"; String modifiedUser = "Super Admin"; Date modifiedTime = new Date (); Integer rows= userMapper.updatePasswordByUid (uid, password, modifiedUser, modifiedTime); System.out.println ("rows=" + rows);} @ Testpublic void findByUid () {Integer uid = 7; User result = userMapper.findByUid (uid) System.out.println (result);} 2 user-change password-Business Tier 2.1 Planning exception
1. Before changing the password, the user needs to check whether the user data exists and is marked as deleted. If the check fails, a UserNotFoundException exception should be thrown.
two。 When a user changes a password, the modification may fail due to the error of the original password entered, then a PasswordNotMatchException exception should be thrown.
3. When performing a password change, a UpdateException exception should be thrown if the number of affected rows returned is different from the expected value.
4. Create a com.cy.store.service.ex.UpdateException exception class that inherits from the ServiceException class.
/ * * exception to update data * / public class UpdateException extends ServiceException {/ / Override Methods...} 2.2 Interface and Abstract method
Add changePassword (Integer uid, String username, String oldPassword, String newPassword) abstract methods to IUserService.
/ * change password * @ param uid current logged-in user id * @ param username user name * @ param oldPassword original password * @ param newPassword new password * / public void changePassword (Integer uid, String username, String oldPassword, String newPassword)
1. Implement the changePassword () abstract method in the UserServiceImpl class.
Public void changePassword (Integer uid, String username, String oldPassword, String newPassword) {/ / calls the findByUid () method of userMapper Query user data according to parameter uid / / check whether the query result is null / Yes: throw a UserNotFoundException exception / / check whether the isDelete in the query result is 1 / Yes: throw UserNotFoundException exception / / extract salt value from the query result / / encrypt the parameter oldPassword combined with salt value Get oldMd5Password / / determine whether the password and oldMd5Password in the query result are inconsistent / / Yes: throw a PasswordNotMatchException exception / / encrypt the parameter newPassword with salt value to get the newMd5Password / / create the current time object / / call the updatePasswordByUid () update password of userMapper And get the return value / / to determine whether the number of affected rows returned above is not 1 / / Yes: UpdateException exception is thrown}
The specific code for the 2.changePassword () method.
Both the equals and contentEquals methods in String can be used to compare whether the contents of the String object are the same.
@ Overridepublic void changePassword (Integer uid, String username, String oldPassword, String newPassword) {/ / call the findByUid () method of userMapper, query the user data User result = userMapper.findByUid (uid) according to the parameter uid; / / check whether the query result is null if (result = = null) {/ / Yes: throw UserNotFoundException exception throw new UserNotFoundException ("user data does not exist") } / / check whether the isDelete in the query result is 1 if (result.getIsDelete (). Equals (1)) {/ / Yes: throw a UserNotFoundException exception throw new UserNotFoundException ("user data does not exist");} / / extract the salt value String salt = result.getSalt () from the query result / / encrypt the parameter oldPassword with salt value to get oldMd5Password String oldMd5Password = getMd5Password (oldPassword, salt); / / determine whether the password and oldMd5Password in the query result are inconsistent if (! result.getPassword (). ContentEquals (oldMd5Password)) {/ / Yes: throw PasswordNotMatchException exception throw new PasswordNotMatchException ("original password error") } / / encrypt the parameter newPassword with salt value to get newMd5Password String newMd5Password = getMd5Password (newPassword, salt); / / create the current time object Date now = new Date (); / / call the updatePasswordByUid () of userMapper to update the password and get the return value Integer rows = userMapper.updatePasswordByUid (uid, newMd5Password, username, now) / / determine whether the number of affected rows returned above is not 1 if (rows! = 1) {/ / Yes: throw a UpdateException exception throw new UpdateException ("an unknown error occurred while updating user data, please contact the system administrator");}}
3. Write and execute unit tests in UserServiceTests.
@ Testpublic void changePassword () {try {Integer uid = 5; String username = "lower"; String oldPassword = "123456"; String newPassword = "888888"; userService.changePassword (uid, username, oldPassword, newPassword); System.out.println ("password changed successfully!") ;} catch (ServiceException e) {System.out.println ("password modification failed!" + e.getClass () .getSimpleName (); System.out.println (e.getMessage ());}} 3 user-modify password-Controller 3.1 handle exception
A new UpdateException exception is thrown in the business where the user changes the password, which needs to be handled in the BaseController class.
@ ExceptionHandler (ServiceException.class) public JsonResult handleException (Throwable e) {JsonResult result = new JsonResult (e); if (e instanceof UsernameDuplicateException) {result.setState (4000);} else if (e instanceof UserNotFoundException) {result.setState (4001);} else if (e instanceof PasswordNotMatchException) {result.setState (4002) } else if (e instanceof InsertException) {result.setState (5000);} else if (e instanceof UpdateException) {result.setState (5001);} return result;} 3.2 Design request
Design the request submitted by the user and design the way to respond.
Request path: / users/change_password
Request parameters: String oldPassword, String newPassword, HttpSession session
Request type: POST
Response result: JsonResult
3.3 processing requests
1. Add a changePassword (String oldPassword, String newPassword, HttpSession session) method to handle the request in the UserController class.
@ RequestMapping ("change_password") public JsonResult changePassword (String oldPassword, String newPassword, HttpSession session) {/ / call session.getAttribute ("") to get uid and username / / call business object to change password / / return successful return null;}
two。 The code that implements the password modification method in the UserController controller.
@ RequestMapping ("change_password") public JsonResult changePassword (String oldPassword, String newPassword, HttpSession session) {/ / call session.getAttribute (") to get uid and username Integer uid = getUidFromSession (session); String username = getUsernameFromSession (session); / / call the business object to change the password iUserService.changePassword (uid, username, oldPassword, newPassword); / / return success return new JsonResult (OK);}
3. Log in to start the project, and then visit http://localhost:8080/users/change_password?oldPassword=xx&newPassword=xx for testing.
4 user-change password-frontend page
1. At the end of the password.html page inside the body tag, add the script tag to write the JavaScript program.
$("# btn-change-password") .click (function () {$.ajax ({url: "/ users/change_password", type: "POST", data: $("# form-change-password") .serialize (), dataType: "json" Success: function (json) {if (json.state = = 200) {alert ("modified successfully!") ;} else {alert ("modification failed!" + json.message);})
two。 Log in to start the project, then visit the http://localhost:8080/web/password.html page and change the password.
Problem: if you can not transfer the data to the background normally, restart the system and IDEA development tools, and you can change the password after logging in.
3. Problem: when operating the front-end page, the user enters the password change page and stays on the current page for a long time without doing anything, which will cause the login information to expire. When the modify button is clicked, the request will still be sent to / users/change_password and will be redirected to the login page by the interceptor. Because the whole process is handled asynchronously by the $.ajax () function, the redirection is also done by the asynchronous task, and there will be "no response when the user clicks the button after the login information times out" without any performance on the page.
Solution: you can supplement the configuration of the error property in the $.ajax () of the password.html page, whose value is a callback function. This function will be called when the server does not normally respond to status codes, such as 302, 400, 404, 405, 500, and so on.
Error: function (xhr) {alert ("your login information has expired, please log in again! HTTP response code:" + xhr.status "); location.href =" login.html ";} profile 1 user-profile-persistence layer 1.1 Planning the SQL statements to be executed
1. The SQL statement that executes to modify the user's personal data is roughly as follows:
UPDATE t_user SET phone=?, email=?, gender=?, modified_user=?, modified_time=? WHERE uid=?
two。 Before modifying the user profile, the currently logged-in user information should be displayed on the page when the user opens the modified page. To display user information, you can use:
SELECT * FROM t_user WHERE uid=?
Description:
1. The query function has been implemented and does not need to be developed again
two。 Before modifying the user profile, you should also check whether the user data exists and marked as "deleted", which can also be achieved through the above query.
1.2 interfaces and abstract methods
Add the updateInfoByUid (User user) method to the UserMapper interface.
/ * Update user profile based on uid * @ param user encapsulates the number of rows affected by the user's id and new profile object * @ return * / Integer updateInfoByUid (User user); 1.3 configure SQL mapping
1. Configure the mapping of Integer updateInfoByUid (User user) abstract methods in UserMapper.xml.
UPDATE t_user SET phone = # {phone}, email = # {email}, gender = # {gender}, modified_user = # {modifiedUser}, modified_time = # {modifiedTime} WHERE uid = # {uid}
two。 Write and execute unit tests in UserMapperTests.
@ Testpublic void updateInfoByUid () {User user = new User (); user.setUid (20); user.setPhone ("17858802222"); user.setEmail ("admin@cy.com"); user.setGender (1); user.setModifiedUser ("system administrator"); user.setModifiedTime (new Date ()); Integer rows= userMapper.updateInfoByUid (user); System.out.println ("rows=" + rows) } 2 user-profile-Business layer 2.1 Planning exception
1. The modification of personal data by users consists of two functions.
Displays the information of the currently logged in user when the page is opened
Update the user's information when you click the modify button.
two。 A UserNotFoundException exception is thrown about the information that displays the currently logged in user when the page is opened, and the page may not be displayed correctly because the user data does not exist and the user is marked as deleted.
3. For updating the user's information when the modify button is clicked, you still need to check again whether the user data exists and the user is marked as "deleted" before performing the modification, then a UserNotFoundException exception may be thrown. It is also possible to throw a UpdateException exception during the process of modifying the data.
2.2 interfaces and abstract methods
Add two abstract methods to the IUserService interface, corresponding to the above two functions.
/ * get the information of the currently logged-in user * @ param uid id * @ return of the currently logged-in user * / User getByUid (Integer uid); / * modify the user profile * @ param uid the currently logged-in user's id * @ param username current login user name * @ param user user's new data * / void changeInfo (Integer uid, String username, User user) 2.3 implement abstract methods
1. Implement the above two abstract methods getByUid (Integer uid) and changeInfo (Integer uid, String username, User user) in the UserServiceImpl implementation class.
@ Overridepublic User getByUid (Integer uid) {/ / call the findByUid () method of userMapper Determine whether the query result is null according to the parameter uid query user data / / Yes: throw a UserNotFoundException exception / / determine whether the isDelete in the query result is 1 / Yes: throw a UserNotFoundException exception / / create a new User object / / encapsulate the username/phone/email/gender in the above query results into a new User object Medium / / returns a new User object return null } @ Overridepublic void changeInfo (Integer uid, String username, User user) {/ / call the findByUid () method of userMapper Determine whether the query result is null according to the parameter uid / / Yes: throw a UserNotFoundException exception / / determine whether the isDelete in the query result is 1 / Yes: throw a UserNotFoundException exception / / complete the data to the parameter user: uid / / complete the data to the parameter user: modifiedUser (username) / / complete the data to the parameter user: modifiedTime (new Date ()) / / call the updateInfoByUid (User user) method of userMapper to perform the modification And get the return value / / to determine whether the number of affected rows returned above is not 1 / / Yes: throw a UpdateException exception}
The concrete code implementation of 2.getByUid (Integer uid) and changeInfo (Integer uid, String username, User user) methods.
@ Overridepublic User getByUid (Integer uid) {/ / call the findByUid () method of userMapper, query the user data User result = userMapper.findByUid (uid) according to the parameter uid; / / determine whether the query result is null if (result = = null) {/ / Yes: throw a UserNotFoundException exception throw new UserNotFoundException ("user data does not exist") } / / determine whether the isDelete in the query result is 1 if (result.getIsDelete (). Equals (1)) {/ / Yes: throw a UserNotFoundException exception throw new UserNotFoundException ("user data does not exist");} / / create a new User object User user = new User () / / encapsulate the username/phone/email/gender in the above query results into the new User object user.setUsername (result.getUsername ()); user.setPhone (result.getPhone ()); user.setEmail (result.getEmail ()); user.setGender (result.getGender ()); / / return the new User object return user } @ Overridepublic void changeInfo (Integer uid, String username, User user) {/ / call the findByUid () method of userMapper, query the user data User result = userMapper.findByUid (uid) according to the parameter uid; / / determine whether the query result is null if (result = = null) {/ / Yes: throw a UserNotFoundException exception throw new UserNotFoundException ("user data does not exist") } / / determine whether the isDelete in the query result is 1 if (result.getIsDelete (). Equals (1)) {/ / Yes: throw a UserNotFoundException exception throw new UserNotFoundException ("user data does not exist");} / / complete data to the parameter user: uid user.setUid (uid) / / complete data to parameter user: modifiedUser (username) user.setModifiedUser (username); / / complete data to parameter user: modifiedTime (new Date ()) user.setModifiedTime (new Date ()); / / call updateInfoByUid (User user) method of userMapper to perform modification and get the return value Integer rows = userMapper.updateInfoByUid (user) / / determine whether the number of affected rows returned above is not 1 if (rows! = 1) {/ / Yes: throw a UpdateException exception throw new UpdateException ("an unknown error occurred while updating user data, please contact the system administrator");}}
3. Unit tests are performed in the UserServiceTests class.
@ Testpublic void getByUid () {try {Integer uid = 20; User user = iUserService.getByUid (uid); System.out.println (user);} catch (ServiceException e) {System.out.println (e.getClass (). GetSimpleName ()); System.out.println (e.getMessage ());} @ Testpublic void changeInfo () {try {Integer uid = 20 String username = "data administrator"; User user = new User (); user.setPhone ("15512328888"); user.setEmail ("admin03@cy.cn"); user.setGender (2); iUserService.changeInfo (uid, username, user); System.out.println ("OK.");} catch (ServiceException e) {System.out.println (e.getClass (). GetSimpleName ()) System.out.println (e.getMessage ());}} 3 user-profile-Controller 3.1 handles exceptions
Description: there is no need to develop again.
3.2 Design request
1. The design user submits a request to display the currently logged-in user information and designs the way to respond.
Request path: / users/get_by_uid
Request parameter: HttpSession session
Request type: GET
Response result: JsonResult
two。 The design user submits a request to modify the user's information and designs the way to respond.
Request path: / users/change_info
Request parameters: User user, HttpSession session
Request type: POST
Response result: JsonResult
3.3 processing requests
1. Process the request to obtain user information
1. Add the getByUid () method to process the request in the UserController class and import the org.springframework.web.bind.annotation.GetMapping package.
@ GetMapping ("get_by_uid") public JsonResult getByUid (HttpSession session) {/ / get uid from HttpSession object / / call business object execution to get data / / response success and data return null;}
The specific code implementation in the 2.getByUid (HttpSession session) method is.
@ GetMapping ("get_by_uid") public JsonResult getByUid (HttpSession session) {/ / get uid Integer uid = getUidFromSession (session) from the HttpSession object; / / call the business object to execute to get data User data = userService.getByUid (uid); / / response success and data return new JsonResult (OK, data);}
3. When you are finished, start the project, open a browser and log in first, and then visit the http://localhost:8080/users/get_by_uid request for testing.
two。 Process requests to modify user's personal information
1. Add a changeInfo (User user, HttpSession session) method to handle the request in the UserController class.
@ RequestMapping ("change_info") public JsonResult changeInfo (User user, HttpSession session) {/ / get uid from HttpSession object and username / / call business object to modify user data / / response successful return null;}
The specific code in the 2.changeInfo (User user, HttpSession session) method is implemented as.
@ RequestMapping ("change_info") public JsonResult changeInfo (User user, HttpSession session) {/ / get uid and username Integer uid = getUidFromSession (session) from the HttpSession object; String username = getUsernameFromSession (session); / / call the business object to perform the modification of user data userService.changeInfo (uid, username, user); / / respond successfully to return new JsonResult (OK);}
3. When you are finished, start the project, open a browser and log in first, and then visit http://localhost:8080/users/change_info?phone=17858800000&email=admin07@cy.com&gender=1 for testing.
4 user-profile-front-end page
1. At the end of the userdata.html page inside the body tag, add the script tag to write the JavaScript program.
$(document) .ready (function () {$.ajax ({url: "/ users/get_by_uid", type: "GET", dataType: "json", success: function (json) {if (json.state = = 200) {console.log ("username=" + json.data.username) Console.log ("phone=" + json.data.phone); console.log ("email=" + json.data.email); console.log ("gender=" + json.data.gender); $("# username") .val (json.data.username); $("# phone") .val (json.data.phone) $("# email") .val (json.data.email); let radio = json.data.gender = = 0? $("# gender-female"): $("# gender-male"); radio.prop ("checked", "checked");} else {alert ("failed to get user information!" + json.message);}) $("# btn-change-info") .click (function () {$.ajax ({url: "/ users/change_info", type: "POST", data: $("# form-change-info") .serialize (), dataType: "json" Success: function (json) {if (json.state = = 200) {alert ("modified successfully!") ; location.href = "login.html";} else {alert ("modification failed!" + json.message);}}, error: function (xhr) {alert ("your login information has expired, please log in again! HTTP response code:" + xhr.status); location.href = "login.html";});})
two。 Start the project after completion, open the browser and log in first, then visit the http://localhost:8080/web/userdata.html page and test the modification of the user's profile.
This is the end of the content about "how to modify springboot user data". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.