java SpringBootWeb request response examples detailed _java_ Script home

java SpringBootWeb request response examples

Updated: May 09, 2024 10:44:30 Author: 0cfjg0
SpringBoot is a way to integrate the Spring technology stack (or framework), but also to simplify the Spring of a rapid development of scaffolding, this article mainly introduces you about the java SpringBootWeb request response information, need friends can refer to

Servlet

A server-side program written in java

The client sends a request to the server

The server starts and invokes the Servlet, which generates the response content based on the client request and passes it to the server

The server returns the response to the client

How javaweb works

When developing web applications in SpringBoot, a core Servlet program DispatcherServlet is built in, which is called the core controller.

DispatcherServlet is responsible for receiving requests sent by pages and distributing the requests to the Controller of the request processor deployed in tomcat according to the rules of resource link execution. After the request processor processes the requests, DispatcherServlet finally sends response data to the browser.

After the browser sends a request to the back-end server tomcat,tomcat parses the request data and passes the parsed data to the HttpServletRequest object of the Servlet program, which means that the HttpServletRequest object can obtain the request data. An HttpServletResponse object is also passed to set the response data for the browser.

request: Browser ->HTTP->tomcat(built-in servlet parsing)->request Object -> Data

response: Data ->response Object ->servlet parsing ->HTTP-> Browser

request

Receive the request data passed by the page

The back end receives data passed by the front end

The underlying value depends on the getset method (reflection)

Postman

A powerful Chrome plugin for web debugging and sending web HTTP requests

For interface testing

Interface test: simulate the front-end to send requests and verify the correctness of data transmission

The following table describes the interface functions

Back-end resource links cannot be repeated

Simple parameter

Information about the request can be obtained through the API HttpServletRequest provided in the Servlet

@RequestMapping("/simpleParam") public String simpleParam(HttpServletRequest request){ String name = request.getParameter("name"); String age = request.getParameter("age"); System.out.println(name+" : "+age); return "OK"; } // The request object contains the request data, which can be obtained directly through the getParameter() method

Use SpringBoot

In the SpringBoot environment, the original API is encapsulated and the form of receiving parameters is simpler.

You can directly define parameters with the same name to receive data.

@RequestMapping("/simpleParam")
	public String simpleParam(String name , Integer age ){
	System.out.println(name+" : "+age);
	return "OK";
}

Test with postman

Quickly submit requests with parameters

Parameter names are inconsistent

You can use @RequestParam for mapping

Usage is as follows

@RequestMapping("/simpleParam") public String simpleParam(@RequestParam("username") String name ,Integer age){ System.out.println(name+" : "+age); return "OK"; } // Annotate the parameter to complete the mapping

Physical parameter

If the number of parameters is large, you can encapsulate the data by encapsulating it into a pojo object

The parameter name must be the same as the POJO attribute name

Simple entity object

Define a pojo entity class

public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; }}

The pojo object is passed in the controller method to receive the data

@RequestMapping("/simplePojo") public String simplePojo(User user){ System.out.println(user); return "OK"; } //pojo objects accept arguments that are the same as their attribute names

Complex entity object

One or more properties in an entity class are objects of another entity class

Encapsulation must follow the following rules:

The request parameter name is the same as the attribute name of the parameter object, that is, when receiving the entity class object attribute in the attribute, the parameter needs to be an object. Genus format.

Array set parameter

Array parameter

The request parameter name is the same as the parameter object property name and the request parameter is multiple.

That is, multiple parameters with the same name are received

Transmission form:

assemble

Set parameter

The request parameter name is the same as the parameter collection object name and the request parameter is multiple

Use @RequestParam to bind the parameter relationships

@RequestMapping("/listParam")
public String listParam(@RequestParam List<String> hobby){
	System.out.println(hobby);
	return "OK";
}

Transitive form

Date parameter

When wrapping date-type parameters, you need to use the @DateTimeFormat annotation and its pattern attribute to set the date format

The pattern attribute specifies the specifications for the front-end to pass parameters.

@RequestMapping("/dateParam")
public String dateParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime){
	System.out.println(updateTime);
	return "OK";
}

Transitive form

JSON parameter

More complex parameters can be transmitted through JSON format,JSON data key name and parameter object property name are the same, define the POJO type parameter to receive the parameter, the controller method needs to use @RequestBody annotation

Use entity class objects to accept

@RequestMapping("/jsonParam")
public String jsonParam(@RequestBody User user){
	System.out.println(user);
	return "OK";
}

Transitive form

Path parameter

Parameters are passed by the request URL, identified by {}, and the @PathVariable annotation is required to obtain path parameters

Try to use wrapper classes for parameters

@RequestMapping("/path/{id}")
public String pathParam(@PathVariable Integer id){
	System.out.println(id);
	return "OK";
}

@RequestMapping("/path/{id}/{name}")
public String pathParam2(@PathVariable Integer id, @PathVariable
String name){
	System.out.println(id+ " : " +name);
	return "OK";
}

Transitive form

respond

@RestController annotation

Contains the @Controller annotation and the @ResponseBody annotation

The Controller annotation declares the class to be a controller

The ResponseBody parses the return value into JSON or XML format

You can respond to an entity object or collection in the controller class

eg:

Responds to an entity class object

@RequestMapping("/simpleParam")
public String simpleParam( String name , Integer age){
	User user = new User();
    user.setName();
    user.setAge();
    return user;
}

Respond to a set

@RequestMapping("/list")
public ArrayList<String> simpleParam( String name , Integer age){
	ArrayList<String> list = new ArrayList<>();
    return list;
}

Regardless of the response data form, it should be returned as Result (Uniform Specification)

Result

{Integer code//1: success 0: failure String msg// Response code description string Object data// The Object type can be used to receive any data. static Result success(data){integer code//1: success 0: failure string // Return result on success} static Result error(msg){// Return result on failure}}

Comprehensive case (parses xml file to front page)

Front end

Page binding js data, data binding hook function request data

Hook function:

mounted() {
       axios.get("/User").then(result=>(
            this.tableData=result.data.data
       ))
},

Data is requested asynchronously using axios during the component load phase

rear-end

Read and parse xml files

String file = class name. class// Gets the bytecode file. getClassLoader()// Gets the class loader.getResource ()// Gets the resources.file ()// File path XmlParserUtils.parse(file) parses the xml to produce a collection of objects

Call the success method in result

Return success object

 return Result.success(list);

Hierarchical decoupling

Three-tier architecture

Data Access -> Logical Access -> Request Processing

Data access:

Responsible for service data maintenance operations, including adding, deleting, modifying, and checking operations

Logical processing:

The code responsible for business logic processing

Request processing, response data:

Responsible for receiving page requests and giving page response data

The code is divided into three layers according to the three components

Controller(Control layer)

Receives requests sent by the front end, processes the requests, and responds to the data

Service(Business layer)

Process the specific business logic and process the data

Dao/Mapper(Data Access Layer/Persistence Layer)

Responsible for data access operations, including adding, deleting, modifying and checking data

Hierarchical decoupling

Cohesion: The functional connections within the functional modules in the software

Coupling: The degree of dependency between the layers (modules) in the software

IOC/DI Technology (inversion of control/dependency injection)

The objects managed in an IOC container are called beans

@Component(added to the implementation class)

The @Primary annotation is preferred when there are multiple implementation class objects

Placing the implementation class object directly into the IOC container (inversion of control)

@Autowired(added to declaration object statement)

Taking objects out of the IOC container (dependency injection)

Resolves the coupling that occurs when objects are created

UserService a = new UserService(); // The left side is decoupled by implementing the interface to achieve polymorphism // The right side is solved by the IOC/DI idea

Bean declaration

To hand the object over to the IOC container, replace @Component with the following annotation

Dao layer ->@Repository(custom name (default class name lowercase))

Service layer ->@Service(custom name (default class name lowercase))

Controller layer ->@Controller(custom name (default class name lowercase))

Other class objects ->@Componet(custom name (default class name lowercase))

The above four annotations need to be scanned by component scan annotation @ComponentScan to take effect

The default scan scope is the package in which the boot class resides and its subpackages

Bean injection

@Primary The object of this class is preferred

@Qualifier(" str ") Select the bean object with the name str for use

Provided by the SpringBoot framework

@Resource(name= "str") Select the bean object whose name is str to use

Provided by java

rvice(); // The left side is decoupled by implementing the interface to achieve polymorphism // The right side is solved by the IOC/DI idea

The #### Bean declaration hands the object over to the IOC container and replaces the @Component Dao layer with the following comment ->@Repository(custom name (default class name lowercase)) Service layer ->@Service(default class name lowercase)) Controller layer ->@Controller(Custom name (default class name in lower case)) Other class objects ->@Componet(Custom name (default class name in lower case)) The preceding four comments take effect only after being scanned by components The default scan range is for the package in which the boot class resides and its subpackages #### Bean injection @Primary using the class object @Qualifier("str") to select a bean object named str for use provided by the SpringBoot framework @Resource(name="str") Select the bean object whose name is str to use provided by java

Sum up

To this article about java SpringBootWeb request response is introduced to this, more related java SpringBootWeb request response content please search the script home previous articles or continue to browse the following related articles hope that you will support the script home in the future!

Related article

  • Java Comparable 和 Comparator 的详解及区别

    The detailed explanation and difference of Java Comparable and Comparator

    This article mainly introduces the detailed explanation of Java Comparable and Comparator and the difference between the relevant information,Comparable natural sorting and Comparator custom sorting examples, the need of friends can refer to the next
    2016-12-12
  • 10分钟带你理解Java中的反射

    10 minutes to understand reflection in Java

    Reflection is a powerful tool in java that makes it easy to create flexible code. This article takes you ten minutes to quickly understand reflection in Java and can be used as a reference if you need it.
    2016-08-08
  • Spring Boot利用@Async异步调用:使用Future及定义超时详解

    Spring Boot uses @Async asynchronous calls: use Future and define timeout details

    This article mainly introduces the information about Spring Boot using @Async asynchronous call: using Future and defining timeout, the article introduces very detailed through the example code, for everyone to learn or use spring boot has a certain reference learning value, the need of friends can refer to the next
    2018-05-05
  • Spring的跨域的几个方案

    Spring's cross-domain solutions

    This article mainly introduces several cross-domain solutions of Spring, CrossOrigin, addCorsMappings, CorsFIlter and other solutions, which have certain reference value. You may refer to them in need, I hope it will be helpful to you
    2022-02-02
  • CentOS7和8中安装Maven3.8.4的简单步骤

    Simple steps to install Maven3.8.4 in CentOS7 and 8

    maven is a tool belonging to apache, mainly compile and package java to solve dependencies, the following article mainly introduces the relevant information about the installation of Maven3.8.4 in CentOS7 and 8, the need of friends can refer to the next
    2022-04-04
  • lombok注解介绍小结

    lombok annotations introduction summary

    lombok is a tool class that can help us simplify java code writing, this article mainly introduces lombok annotation summary, Xiaobian feel very good, now share to you, also give you a reference. Let's take a look
    2018-11-11
  • 详解Kotlin 高阶函数 与 Lambda 表达式

    Detail Kotlin higher-order functions and Lambda expressions

    This article mainly introduces the detailed understanding of Kotlin higher-order functions and Lambda expressions related information, need friends can refer to the next
    2017-06-06
  • java中重写equals()方法的同时要重写hashcode()方法(详解)

    In java, the equals() method should be overridden at the same time as the hashcode() method.

    The following Xiaobian will bring you a java rewrite equals() method at the same time to rewrite hashcode() method (detailed explanation). Xiaobian feel very good, now to share with you, but also to give you a reference. Let's take a look
    2017-05-05
  • Spring activiti如何实现指定任务处理者

    How does Spring activiti implement the specified task handler

    This article mainly introduces Spring activiti how to achieve the specified task processor, the article through the example code is very detailed, for everyone's study or work has a certain reference learning value, need friends can refer to
    2020-11-11
  • Java Redis配置Redisson的方法详解

    Description How to configure Redisson on Java Redis

    This article mainly introduces the relevant information of Java Redis configuration Redisson in detail, and the example code in the article is explained in detail, which has certain reference value for our study or work, and you can understand it if you are interested
    2022-08-08

Latest comments