I. Front-end environment construction

In the vue-element-admin project, there is a simple and lightweight project called vue-admin-template, which has less initialization content and is suitable for beginners to prevent them from getting confused by so much code.

Fast installation

# # cloning project git clone https://github.com/PanJiaChen/vue-admin-template.git into the project directory CD vue - element - admin # installation depend on NPM install # Can be solved through the following NPM slow download speed of NPM install - registry=https://registry.npm.taobao.org # local development start project NPM run devCopy the code

You can choose either of the two NPM installments. The following is a domestic Taobao image, which is faster.

After the startup, you will see the login page, indicating that the installation is successful.

Click login, you can see the home page.

But we haven’t implemented the back end yet, so why are we logged in? This is because requests in the front-end framework currently follow its built-in mocks, so you’ll have to develop a back-end interface to replace those mocks later.

Second, back-end environment construction

Create an

You can create a SpringBoot application directly using IDEA, which can be quickly created using Spring Initializr.

When you’re done, add the response dependencies to pom.xml.

I checked some items when I created them, and the dependencies will be generated automatically.

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <! --mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> < version > 3.0.5 < / version > < / dependency > < the dependency > < groupId > org. Springframework. Experimental < / groupId > <artifactId>spring-native</artifactId> <version>${spring-native.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-core</artifactId> The < version > 3.0.5 < / version > < / dependency > < / dependencies >Copy the code

It is important to add the mybatis-plus-core dependency and use it later for database interaction.

Configure the application. The properties

The connection information of the database is configured here. My mysql is installed on huawei cloud, and the system is centos8.

# mysql spring.datasource.url=jdbc:mysql://xxx.x.xx.101:3306/bloomtest? characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=xxxxxx Spring. The datasource. The driver - class - name = com. Mysql. Cj. JDBC. Driver spring. The datasource. Hikari. Max - lifetime = address is 1000000 # context server.servlet.context-path=/bloomtestCopy the code
  • spring.datasource.hikari.max-lifetime: The default data source connection pool. The maximum connection lifetime is set to a longer value to prevent disconnection without operation for a long time, which is inconvenient for debugging.
  • server.servlet.context-path: Configures the context path, for example, my login interface path is/user/loginAt the time of your visitlocalhost:8080/bloomtest/user/login.

Three, to achieve login

Login involves users, but also involves permission management and so on, but this is not the current focus, just need to be able to log in normally.

F12 can look at mock login requests. There are two interfaces, so it returns real data based on the data returned by the mock.

The current code roughly has the following structure, first familiar.

1. The mysql table

Login, is to take the front end to pass the user name and password, see whether there is a database user table, there can log in, there is no return failure.

Therefore, we need to create a user table before doing this:

CREATE TABLE 'user' (' id 'bigint NOT NULL AUTO_INCREMENT COMMENT' id ', 'username' varchar(30) DEFAULT NULL COMMENT 'username ',' password 'varchar(30) DEFAULT NULL COMMENT' age ', 'createTime' datetime NOT NULL DEFAULT '1900-01-01 00:00:00' COMMENT 'createTime ', 'updateTime' datetime NOT NULL DEFAULT '1900-01-01 00:00:00' COMMENT 'updateTime ', PRIMARY KEY (' id ') ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT=' 表';Copy the code

Then I manually added three new users:

2. Back-end – Implements the /login interface

(1) create entity class User

package com.pingguo.bloomtest.pojo; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import java.util.Date; @Data public class User { @TableId(type = IdType.ID_WORKER) private Long id; private String username; private String password; @tableField (fill = FieldFill.INSERT) private Date createTime; @tableField (fill = FieldFill.INSERT_UPDATE) // Fill data when adding or modifying data private Date updateTime; }Copy the code

Annotations have been introduced in the spring related technology stack. If you need them, you can go to Baidu directly.

(2) Create the interface UserDAO

package com.pingguo.bloomtest.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pingguo.bloomtest.pojo.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDAO extends BaseMapper<User> {

}
Copy the code

Mybatis – Plus framework is used here, and the content of this framework learned before will be attached at the end of the article for learning reference.

(3) Create the Service layer UserService

This is where the business logic is really handled, providing methods that are called directly to the controller layer.

package com.pingguo.bloomtest.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.pingguo.bloomtest.dao.UserDAO; import com.pingguo.bloomtest.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class UserService { @Autowired private UserDAO userDAO; /** * Return true if the user exists. False * @param username username * @param password user password * @return true,false */ public Boolean isUserExist(String) <User> wrapperUser = new QueryWrapper<>(); AllEq Map<String, Object> Map = new hashmap <>(); map.put("username", username); map.put("password", password); AllEq (map); wrapperuser.alleq (map); Int count = userdao.selectCount (wrapperUser); if (count == 1) { return true; } else { return false; }}}Copy the code

Here is the interaction with mysql, using the syntax of Mybatis – Plus, see the article link attached at the end of the article.

The method returns true to indicate that the user exists in the database and can log in. Otherwise return false.

Create the Controller layer UserController

This is where the front-end requests are received.

package com.pingguo.bloomtest.controller; import com.pingguo.bloomtest.common.Result; import com.pingguo.bloomtest.controller.request.UserRequest; import com.pingguo.bloomtest.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("user") public class UserController { @Autowired UserService userService; @PostMapping("/login") public Result login(@RequestBody UserRequest user) throws Exception { String username = user.getUsername(); String password = user.getPassword(); if (userService.isUserExist(username, password)) { Map<String, Object> userToken = new HashMap<>(4); userToken.put("token","admin-token"); return Result.success(userToken); } else {return result. fail(" wrong username or password "); }}}Copy the code

The Controller layer calls the Service layer, which in turn calls the DAO layer to interact with DB.

This returns a Result of type Result. This is a class wrapper for better data return.

Create a new class Result under the common package:

package com.pingguo.bloomtest.common; import lombok.Data; @Data public class Result { private static final int SUCCESS_CODE = 20000; private static final int FAIL_CODE = 20005; private int code; private String message; private Object data; private Result(int code, String message, Object data) { this.code = code; this.message = message; this.data = data; } public static Result success() {return new Result(SUCCESS_CODE, "SUCCESS_CODE ", null); } public static Result success(Object data) {return new Result(SUCCESS_CODE, "success ", data); } public static Result fail(String message) { return new Result(FAIL_CODE, message, null); } /** * pass the failure status code, Return Result Result * @param code failure status * @param message text message * @return Result Result */ public static Result fail(int code, String message) { return new Result(code, message, null); }}Copy the code

In addition, the pass parameter UserRequest user is also created to facilitate the retrieval of request parameters.

(4) Start the application and test the /login interface

Call directly using Postman.

Change the pass parameter that doesn’t exist.

The interface is normal.

3. Front-end – Modify the code to achieve login

(1) modify.env.development

The front end requests access to the back end http://127.0.0.1:8080 address and port.

(2) modify \ SRC \ API \user.js

So here’s the interface path for the front end request, replaced by the /login that we implemented,

(3) \ SRC \ utils \ request js

As for my back end interface return success code why is 20000? Because there is a unified package in the front-end framework, you can change it yourself if you like.

(4) \ SRC \ views \ login \ index vue

This is where the page is stored, and it’s where the main front end code is.

You know from the binding event of the Login button that the handler Login is the method used to handle the Login, but you don’t need to change that for now.

After rebuilding, click Login and you can see that the real back-end interface is requested.

But the report was wrong.

4. Resolve cross-domain

Error reporting is a cross – domain problem, resolve cross – domain, can be handled in the back end, add a configuration class.

package com.pingguo.bloomtest.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source =  new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); / / 1 allows any domain using corsConfiguration. AddAllowedOrigin (" * "); / / 2 allows any head corsConfiguration. AddAllowedHeader (" * "); / / 3 allows any method (post, get, etc.). CorsConfiguration addAllowedMethod (" * "); return corsConfiguration; }}Copy the code

Try again, the login request succeeded, but can not jump, because there is another interface not implemented, that is /useInfo.

5. Back-end – Implement the /useInfo interface

This is the same as above, but because you write the same data as the mock returns, you add a new controller method under the Controller class to handle the returns directly.

@GetMapping("/useInfo") public Result useInfo(HttpServletRequest request) throws Exception { String token = request.getParameter("token"); Map<String, Object> result = new HashMap<>(8); ArrayList roles = new ArrayList<>(); String allowableToken = "admin-token"; if (token.equals(allowableToken)) { roles.add("admin"); result.put("roles", roles); Result. put("introduction", "I am the super administrator "); result.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"); } return Result.success(result); }Copy the code

Restart the application. You can log in to the application.

6. Back-end – Enables the /logout interface

Finally, add an interface for logging out.

    @PostMapping("/logout")
    public Result logout() throws Exception {
        return Result.success();
    }
Copy the code

To restart the test, click the logout icon to exit the login page successfully.

Four, summary

The content of this article is mainly about the environment tune-through, as well as the realization of the basic login, the follow-up can be normal first important function development.

Attached are the study notes of Mybatis – Plus, which are simple and easy to use for reference only.

【 Mybatis -plus】 What is optimistic lock? 【 Mybatis -plus】 What is optimistic lock? How to implement “optimistic lock” 【mybatis-plus】 paging, logical deletion 【mybatis-plus】 conditional query