Develop user login registration and user information (5-6 Develop user interface 5-7 swagger2 use and interface testing)

Learning objectives:

5-6 Develop interfaces for registered users
5-7 swagger2 usage and interface testing

Learning content:

5-6 Develop interfaces for registered users

After using mybatis to reverse-generate the pojo entity class, you start writing controller s.

Here is the User inside my pojo. The reverse generated code of the java file is different from the teacher's. I copied the source code, and I don't know what the problem is.

Solved, just change the name of the table!

1. First introduce com. Imooc. Tool class inside utils

MD5Utils.java is a tool class for MD5 encryption of passwords;
IMoocJSONResult.java is used for back-argument, that is, after an interface call, you need to return the information. When you go back, you need to wrap some relevant information into a JSON to return.


IMoocJSONResult. The code for Java is as follows:

package com.imooc.utils;

/**
 * @Description: Custom Response Data Structure
 * 				This class is for Portal, ios, Android, WeChat
 * 				Once the portal accepts this type of data, it needs to use this class's methods to convert to the data type format (class, or list) for the
 * 				Other self-treatment
 * 				200: Indicate success
 * 				500: Represents an error with error information in the msg field
 * 				501: bean Validation errors, no matter how many errors are returned as map s
 * 				502: Interceptor intercepted user token error
 * 				555: Exception throw information
 */
public class IMoocJSONResult {

    // Response to business status
    private Integer status;

    // Response message
    private String msg;

    // Data in response
    private Object data;
    
    private String ok;	// Do not use

    public static IMoocJSONResult build(Integer status, String msg, Object data) {
        return new IMoocJSONResult(status, msg, data);
    }

    public static IMoocJSONResult ok(Object data) {
        return new IMoocJSONResult(data);
    }

    public static IMoocJSONResult ok() {
        return new IMoocJSONResult(null);
    }
    
    public static IMoocJSONResult errorMsg(String msg) {
        return new IMoocJSONResult(500, msg, null);
    }
    
    public static IMoocJSONResult errorMap(Object data) {
        return new IMoocJSONResult(501, "error", data);
    }
    
    public static IMoocJSONResult errorTokenMsg(String msg) {
        return new IMoocJSONResult(502, msg, null);
    }
    
    public static IMoocJSONResult errorException(String msg) {
        return new IMoocJSONResult(555, msg, null);
    }

    public IMoocJSONResult() {

    }

    public IMoocJSONResult(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public IMoocJSONResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOK() {
        return this.status == 200;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

	public String getOk() {
		return ok;
	}

	public void setOk(String ok) {
		this.ok = ok;
	}

}

MD5Utils. The code for Java is as follows:

package com.imooc.utils;

import java.security.MessageDigest;

import org.apache.commons.codec.binary.Base64;

public class MD5Utils {

	/**
	 * @Description: md5 encryption of strings
	 */
	public static String getMD5Str(String strValue) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		String newstr = Base64.encodeBase64String(md5.digest(strValue.getBytes()));
		return newstr;
	}

	public static void main(String[] args) {
		try {
			String md5 = getMD5Str("imooc");
			System.out.println(md5);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

2. New controller for user registration and login

package com.enhypen.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.enhypen.pojo.Users;
import com.enhypen.service.UserService;
import com.enhypen.utils.IMoocJSONResult;
import com.enhypen.utils.MD5Utils;

@RestController //Note that since all controllers interact with our mobile applets in a JSON format, the comment used above all controllers must be @RestController
public class RegistLoginController {
	
	@Autowired
	private UserService userService;
		
	@PostMapping("/regist") 

	public IMoocJSONResult regist(@RequestBody Users user) throws Exception {
		
		//1. Decide that the username and password must not be empty
		if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())) {
			return IMoocJSONResult.errorMsg("User name and password cannot be empty");
		}
		
		//2. Determine if the user name exists
		boolean usernameIsExist=userService.queryUsernameIsExist(user.getUsername());
		
		//3. Save users, register information
		if(!usernameIsExist) {
			user.setNickname(user.getUsername());
			user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
			user.setFansCounts(0);
			user.setReceiveLikeCounts(0);
			user.setFollowCounts(0);
			user.setFaceImage(null);
			userService.saveUser(user);
			
		}else {
			return IMoocJSONResult.errorMsg("User name already exists, please try another one!");
		}
		return IMoocJSONResult.ok();
	}
	
}

3. New service for user registration and login

Create a new com.enhypen.service package and create a new UserService interface in the package:


The UserService code is as follows:

package com.enhypen.service;

import com.enhypen.pojo.Users;

public interface UserService {
	
	/**
	 * Determine whether the user name exists
	 */
	public boolean queryUsernameIsExist(String username);
	
	/**
	 * Save User (User Registration)
	 */
	public void saveUser(Users user);
	
}

New Interface Implementation Class UserServiceImpl

package com.enhypen.service;

import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.enhypen.mapper.UsersMapper;
import com.enhypen.pojo.Users;

public class UserServiceImpl implements UserService {

	@Autowired
	private UsersMapper UserMapper;
	
	@Autowired
	private Sid sid;
	
	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public boolean queryUsernameIsExist(String username) {

		Users user=new Users();
		user.setUsername(username);
		
		Users result= UserMapper.selectOne(user);
		
		return result==null?false:true;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void saveUser(Users user) {
		
		String userId=sid.nextShort();
		user.setId(userId);
		UserMapper.insert(user);

	}

}

5-7 swagger2 usage and interface testing

swagger2 can build documentation for a very powerful online restful API, generate documented APIs and provide them to different teams, develop faster, and deploy plug-in tools more easily.

Front-end personnel open the web address to see the interface provided by the back-end personnel, better involve other teams in the development, can save a lot of document development.

Easy to self-test and leaders to check workload

word documents that do not require much redundancy (refresh versions in time)

1. POM in common. Configuration in XML file

		<!-- swagger2 To configure -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.4.0</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.4.0</version>
		</dependency>

2. Create a new Swagger2 configuration file in the following location on mini-api: Information on building an API document

package com.enhypen;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {
	
	/**
	 * @Description:swagger2 Configuration file, here you can configure some basic contents of swagger2, such as scanned packages, etc.
	 */
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
				.apis(RequestHandlerSelectors.basePackage("com.enhypen.controller"))
				.paths(PathSelectors.any()).build();
	}

	/**
	 * @Description: Information for building api documents
	 */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				// Set Page Title
				.title("Use swagger2 Build Short Video Backend api Interface Documentation")
				// Set up contacts
				.contact(new Contact("enhypen-Wang Yi", "http://www.imooc.com", "ay15272838320@163.com"))
				// describe
				.description("Welcome to the Short Video Interface Document, here is the description")
				// Define Version Number
				.version("1.0").build();
	}


}

3. Add API description information to the ReistLoginController file of mini-api:

4. Add api description information to pojo's users file:


5. Error after running Application:

A @Service definition is required in the following figure: that is, the program cannot scan at the time of the scan without comment.

Run again and find errors:

You need to configure the mapper in the following figure: you need to set the path to scan


In addition, the following three packages need to be scanned as Component s due to the additional introduction of them:


6. After running Application again: get the page


Error 1 found:

Solution:

Application. The Java startup file imports tk.mybatis.spring.annotation.MapperScan; Not org.mybatis.spring.annotation.MapperScan;

Error 2:

Run Successfully:

You can find the data in the database:

Tags: Database MySQL Java Spring

Posted by agriz on Thu, 02 Jun 2022 20:23:56 +0530