Veröffentlicht aminDevAufrufe: Symbole im Artikel gezählt: 1.3k WörterLesezeit ≈2 min
In this post, we will implement the User Login feature in Spring Boot. The dependencies we need are JDBC and MyBatis. After we are done with the backend logic, we will use a frontend template to bootstrap the page view.
Preparation
We will start the configuration based on the setup and codes in the previous post.
Project Structure
Before we start, the project structure looks like this (under /src/main/java/merikanto/demo):
<insertid="addUser"parameterType="merikanto.demo.entity.User"> insert into user(username,password_hash) values(#{userName},#{password}) </insert>
<insertid="insertUsersBatch"> insert into user(username,password_hash) VALUES <foreachcollection="Users"index="index"item="User"open=""separator=","close=""> (#{User.userName}, #{User.password}) </foreach> </insert>
<selectid="findUsers"parameterType="Map"resultMap="UserResult"> select id,username,create_time from user order by id desc <iftest="start!=null and limit!=null"> limit #{start},#{limit} </if> </select>
<selectid="getTotalUser"parameterType="Map"resultType="int"> select count(*) from user </select>
<selectid="getUserByUserNameAndPassword"resultMap="UserResult"> select id,username,token from user where username = #{userName} and password_hash = #{passwordHash} ORDER BY id DESC limit 1 </select>
<selectid="getUserByToken"resultMap="UserResult"> select id,username,token from user where token = #{userToken} ORDER BY id DESC limit 1 </select>
<selectid="getUserById"resultMap="UserResult"> select username,token from user where id=#{id} ORDER BY id DESC limit 1 </select>
<selectid="getUserByUserName"resultMap="UserResult"> select id,username,token from user where username = #{userName} ORDER BY id DESC limit 1 </select>
<updateid="updateUserToken"> update user set token = #{newToken} where id =#{userId} </update>
<updateid="updateUserPassword"> update user set password_hash = #{newPassword},user_token ='' where id =#{userId} </update>
<deleteid="deleteBatch"> delete from user where id in <foreachitem="id"collection="array"open="("separator=","close=")"> #{id} </foreach> </delete>
<selectid="getAllUsers"resultMap="UserResult"> select id,username,create_time from user order by id desc </select> </mapper>
Service: Business Logic
UserService
Add class UserService under service package.
1 2 3 4 5 6 7 8 9
package merikanto.demo.service;
import merikanto.demo.entity.User;
publicinterfaceUserService{
// User Login User updateTokenAndLogin(String userName, String password); }
UserServiceImpl
Then add class UserServiceImpl under /service/impl.
@RequestMapping(value = "/login", method = RequestMethod.POST) public Result login(@RequestBody User user){ Result result = ResultGenerator.genFailResult("Oops... Login Failed!"); if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) { result.setMessage("Please fill in the login info!"); } User loginUser = UserService.updateTokenAndLogin(user.getUserName(), user.getPassword()); if (loginUser != null) { result = ResultGenerator.genSuccessResult(loginUser); } return result; } }
publicstatic Result genSuccessResult(){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_SUCCESS); result.setMessage(DEFAULT_SUCCESS_MESSAGE); return result; }
publicstatic Result genSuccessResult(String message){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_SUCCESS); result.setMessage(message); return result; }
publicstatic Result genSuccessResult(Object data){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_SUCCESS); result.setMessage(DEFAULT_SUCCESS_MESSAGE); result.setData(data); return result; }
publicstatic Result genFailResult(String message){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_SERVER_ERROR); if (StringUtils.isEmpty(message)) { result.setMessage(DEFAULT_FAIL_MESSAGE); } else { result.setMessage(message); } return result; }
publicstatic Result genNullResult(String message){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_BAD_REQUEST); result.setMessage(message); return result; }
publicstatic Result genErrorResult(int code, String message){ Result result = new Result(); result.setResultCode(code); result.setMessage(message); return result; } }
privatestatic String byteArrayToHexString(byte b[]){ StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) { resultSb.append(byteToHexString(b[i])); }
return resultSb.toString(); }
privatestatic String byteToHexString(byte b){ int n = b; if (n < 0) { n += 256; } int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; }
// Generate random numbers of fixed length publicstaticintgenRandomNum(int length){ int num = 1; double random = Math.random(); if (random < 0.1) { random = random + 0.1; } for (int i = 0; i < length; i++) { num = num * 10; } return (int) ((random * num)); }