spring boot project exercise

Official document for spring boot:https://docs.spring.io/spring-boot/docs/current/reference/html/

The browser sends a hello request, the server accepts and processes the request, and responds to the Hello World string;
1. Create a maven project
2. Import Dependency

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>//Imported components on which the web module depends to function properly
        </dependency>
    </dependencies>

Write Main Program Class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication//Label main program class, entry
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);//Start spring Application
    }
}

Write business logic

@RestController//Includes @ResponseBody, @Controller
public class HelloController {


    @RequestMapping("/hello")
    public String hand01(){
        return "Hello,Spring Boot";
    }
}

yaml profile

  • Case Sensitive
  • Use indentation to represent hierarchical relationships
  • Tab keys are not allowed for indentation, only spaces are allowed
  • The number of indented spaces is not important as long as the elements of the same level are aligned to the left
  • Use # for comments
#object
friends:
  lastName: zhangsan 
  age: 20
 
 friends: {lastName: zhangsan,age: 18}
 
 #array
 pets: 
   ‐ cat 
   ‐ dog 
   ‐ pig
 
 pets: [cat,dog,pig]


person: 
  lastName: hello 
  age: 18 
  boss: false 
  birth: 2017/12/12 
  maps: {k1: v1,k2: 12} 
  lists: 
    ‐ lisi 
    ‐ zhaoliu 
  dog:
    name: puppy 
    age: 12

#Allocate database
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver 
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/tdoor_user?

@PropertySource: Load the specified configuration file;
@PropertySource: Load the specified configuration file;
SpringBoot recommends adding components to containers;Recommended use of full comment
1. Configuration class@Configuration------>Spring configuration file
2. Add components to containers using @Bean

Static resource access:

By default, if there are / static, /public, /resource, /META-INF/resources under the class path, the static resource is placed below and accessible.
Static resource access defaults to no prefix and can be prefixed in the configuration file

spring: 
  mvc: 
    static-path-pattern: /res/**   

Static resource access paths can also be changed

resources: 
  static-locations: classpath:/aaa

Welcome Page

  • index.html under static resource path
    Create a new html file in the static resource path
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Static Resource Welcome Page</h1>
</body>
</html>
//directhttp://localhost:8080/index.html
  • controller processing
@Controller
public claa IndexController{
 	@GetMapping("/index")
	 public String welcome(){
  	return "index.html";
  }
}

@Controller: In Spring Boot, is dedicated to handling Http requests.

  • @RequetMapping("/Request Path")
  • @RequetMapping(value ='/request path', method = RequestMethod.way)

@Date: Can I leave the getset method blank?
@AllArgsConstructor: parametric constructor
@NoArgsConstructor: parameterless constructor
In the configuration file, Debug=true can see the automatic configuration Report
form

<form action="/user" method="get">
		<input value="REST-POST Submit " type="sumbit"/>
</form>

WebMvcConfigurer Configuration
AddViewControllers: Page jump.Override the addViewControllers() method in WebMvcConfigurer.

@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/toLogin").setViewName("login");
        registry.addViewController("/index.html").setViewName("index");
    }
   //AddViewController ('/toLogin'), which is the URL path, ishttp://localhost:8080/toLogin

	//setViewName("/login") is your HTML page name

AddResourceHandlers: If you want to customize the static resource mapping directory, simply override the addResourceHandlers() method

  • addResoureHandler: Exposed access path
  • addResourceLocations: Path to internal file placement
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
    }
}

MVC mode
DAO Layer: Mainly for data persistence, some of the tasks responsible for contacting the database are encapsulated here
Service layer: mainly responsible for the logical application design of business modules.
Controller layer: Responsible for the control of a specific business module process in which the interface of the Service layer is invoked to control the business process.
View layer: mainly responsible for the presentation of foreground jsp pages.

Example:https://www.cnblogs.com/almm/p/10801796.html

student entity class

@Entity  // For persistence of entity classes, when JPA detects that our entity class has an @Entity annotation, the corresponding table structure information is generated in the database.
@Table(name = "student")  //Generating student tables in a database
//@Entity applies on entity classes @Table(name = "student") applies on entity classes, and the name attribute is the database table name
//Entity classes are primarily used to store and manage data within the system and provide access to that data
public class Student {
    @Id  //Declares that the attributes of an entity class are mapped to the primary key column of the database.
    @GeneratedValue(strategy = GenerationType.IDENTITY) //Label the primary key generation strategy, specified by the strategy attribute
    //ID Self-Increasing
    private  Integer id;  //You can distinguish whether a property has been set to a value, int defaults to 0, Integer defaults to null
    private String name;
    private  int age;
    private  String sex;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }

    public Student() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

GenerationType.****

StudentDao:
@param assigns the value of the name attribute in the form to the formal parameter in the method
@Qurey:name refers to the method name, and sql can be executed when nativeQuery = true.
JpaRepository simple query, spring data is implemented by default, custom simple query is to automatically generate SQL based on method name, the main syntax is findXXBy,readAXXBy,queryXXBy,countXXBy, getXXBy followed by property name (https://blog.csdn.net/fly910905/article/details/78557110/)

 List<Student> findStuByName(@Param("name") String name);
 @Query(name = "findStuByName",nativeQuery = true,value   "select * from student where name=:name")//Pass the name to the String name and assign it to the name of the sql statement.

UserDao
If two User users have the same usernam or password, 500 errors are returned
This method cannot be logged in with username or password

@Query(name="login",nativeQuery = true,value =
        "select * from user where username=:username and password=:password")
User login(@Param("username") String username, @Param("password") String password);

StudentService:

public interface StudentService {
    Student save(Student student);//Add Students
    Student update(Student student);//modify
    void  delete(Integer id);//Delete students by id
    Student findStuById(Integer id);//Find students by ID, there is no such method in the interface, create in StudentDao interface
    List<Student> findStuByName(String name);//Create in StudentDao interface by student name lookup

    /**
     * Paging Query for All Data
     * @param page //Current Page
     * @param pageSize //Number of records per page
     * @return
     */
    Page<Student> findAll(int page,int pageSize);//Calls the parent JPA interface paging method of the Dao interface.

}

StudentServiceImpl: Implement Interface

StudentController:

@RestController  
@RequestMapping("/s")
public class StudentController {

    @Autowired//Dependent Injection
    private StudentService studentService;

    /**
     * Add Students
     * @param student To add a student object
     * @return
     */
    @PostMapping("/add")
    /*@PostMapping
    Map a POST request
*/
    
    public  Student save(Student student){
        return studentService.save(student);
    }

    /**
     * Modify Students
     * @param student
     */
    @PostMapping("/update")
    public  Student update(Student student){
        return studentService.save(student);
    }

    /**
     * Delete Students
     * @param  id   To delete student id
     * @return
     */
    @GetMapping("/del/{id}")
    public  String del(@PathVariable  int id){
        studentService.delete(id);
        return  "yes";
    }

    @GetMapping("/findByName/{name}")
    public List<Student> findByName(@PathVariable String name){
    return  studentService.findStuByName(name);
    }

Tags: Java Spring Spring Boot

Posted on Fri, 03 Sep 2021 12:36:46 -0400 by programming.name