This chapter introduces the database and accesses the page through database verification
1, Import database
Create a new table directly using Navicat, a visual tool of MySQL
2, Login using database authentication
In the previous article, we directly used the password to write the account to the back-end controller for verification
The following database validation logic can be used:
1. Get the user name and password information sent by the front end
2. Query whether there are a bunch of user names and passwords in the database
3. Result(400) is returned if it exists, and Result(200) is returned if it does not exist
3, Project configuration using database
Modify pom.xml in the project to update the dependencies in the Maven library
Database import mysql
The user class written under data JPA needs to be used
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
Connect to the database in IDEA
After configuring the dependency, you also need to configure the database. Open src\main\resources\application.properties and add the following statement based on the original
spring.datasource.url= jdbc:mysql://localhost:3306/bs?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username= root spring.datasource.password= 123456 spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto = none
cj must be filled in mysql8.0 driver class name
4, Perfect login controller
Project description needs to be modified
User class
Modify the User class code as follows to establish the mapping to the database.
package com.example.wei.pojo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.springframework.boot.autoconfigure.domain.EntityScan; import javax.persistence.*; @Entity @Table(name = "user") @JsonIgnoreProperties({"handler","hibernateLazyInitializer"}) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") int id; @Column(name = "username") String username; @Column(name = "password") String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Annotation description
@Entity indicates that this is an entity class
@Table(name = "user") indicates the corresponding user table
@JsonIgnoreProperties({"handler", "hibernateLazyInitializer"}) simplifies database operations and uses the Java Persistence API (JPA) to ignore some properties in bean s that do not need to be converted during json serialization
The front and back ends are separated, and the front and back end data interaction uses json format. Then the User object is converted to json data. In this project, jpa is used to persist the entity class. By default, jpa will use hibernate. During the work of jpa, a proxy class will be created to inherit the User, and two properties that do not need json, handler and hibernateLazyInitializer, will be added. Therefore, we need to use JsonIgnoreProperties to ignore these two properties.
UserDao
Data access object, Dao, is used to operate database objects. Objects can be developed by themselves. We can use the framework to build Dao layer by inheriting JpaRepository
Explanation of addition, deletion and modification of JpaRepository blog
Create a new package, name dao, and then create a UserDao interface
package com.example.wei.dao; import com.example.wei.pojo.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserDao extends JpaRepository<User,Integer> { User findByUsername(String username); User getByUsernameAndPassword(String username,String password); }
Method name usage. Using JPA, you don't need to build SQL statements manually, but only need to provide the name of the method according to the specification to add, delete, modify and query the database.
For example, findByUsername is to query the corresponding row through the username field and return it to the User class.
Two methods are constructed, one is to query through user name, the other is to query through user name and password.
UserService
Create a new package, name service, and then create a UserService class
package com.example.wei.service; import com.example.wei.dao.UserDao; import com.example.wei.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired UserDao userDao; public boolean isExist(String username) { User user = getByName(username); return null!=user; } public User getByName(String username) { return userDao.findByUsername(username); } public User get(String username,String password){ return userDao.getByUsernameAndPassword(username, password); } public void add(User user){ userDao.save(user); } }
The UserDao is encapsulated twice here. Generally speaking, we only define the basic addition, deletion, modification and query operations in the dao, and the specific operations need to be completed by the dao.
Since our operation is relatively simple, it seems that we have simply renamed it here
For example, the method of "query and obtain objects through user name and password" is named get.
LoginController
The login controller queries the database through the get method provided by UserService. If the returned object is empty, the verification fails, otherwise the verification succeeds.
package com.example.wei.controller; import com.example.wei.pojo.User; import com.example.wei.result.Result; import com.example.wei.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.util.HtmlUtils; import java.util.Objects; @Controller public class LoginController { @Autowired UserService userService; // LoginController loginController; @PostMapping(value = "/api/login") @ResponseBody @CrossOrigin public Result login(@RequestBody User requsetUser){ String username = requsetUser.getUsername(); username = HtmlUtils.htmlEscape(username); // if (!Objects.equals("admin",username) || !Objects.equals("123456", requsetUser.getPassword())){ // String message = "account password error"; // System.out.println("test"); // return new Result(400); // }else{ // return new Result(200); // } User user =userService.get(username,requsetUser.getPassword()); if (null == user){ return new Result(400); }else{ return new Result(200); } } }
Specific description of three-tier architecture (Dao + Service + Controller)
- Dao is used for direct operation with the database and defines the operations of adding, deleting, modifying and querying
- Service is responsible for business logic. The code related to functions is generally written here to write and call various methods to operate the data obtained by DAO
- The Controller is responsible for data interaction, receiving the data sent by the front end, obtaining the processed data and returning it by calling the Service
In practice, it tends to make the Controller appear cleaner, which is convenient for code readers to find the entrance of analysis function. (later reconstruction)
5, Testing
Run the front-end and back-end projects at the same time, visit localhost:8080/#/login, and enter the user name admin and password 123
Click login to successfully enter localhost:8080/#/index and output hello word