Spring MVC framework technology summary, Java learning route guide

Keywords: Java Spring Back-end Programmer mvc

@Controller

public class UserController {

    @RequestMapping(value = "/users",method = RequestMethod.POST)

    public String insertUsers(@RequestBody List<User> users){

    System.out.println("insertUsers");

    System.out.println(users);

    return "/success.jsp";

    }

}



3.2.4 summary 🔥

If there are curly braces outside the Json data format, we can receive it with an object or a Map collection

If there are square brackets outside the Json data format, we can use List set or array to receive

3.2.5 precautions 🔥

If you need to use @ RequestBody to get the Json in the request body and convert it, the content type value of the request header should be: application/json.

3.3. Get QueryString format parameters 🔥

  • If the interface parameters are in QueryString format, we can also use spring MVC to quickly obtain parameters.

  • We can use @ RequestParam to obtain parameters in QueryString format.

3.3.1 @ RequestParam example 1 🔥

It is required to define an interface. The request path of the interface is required to be / testRequestParam, and the request method is not required. The parameters are id, name and likes. Pass in the format of QueryString.

3.3.1.1. Parameters are obtained separately 🔥

If we want to get id, name and likes separately, we can use the following expression:

  • Define method parameters in the method. The method parameter name should be consistent with the request parameter name. In this case, we can omit the @ RequestParam annotation.
@RequestMapping("/testRquestParam")

public String testRquestParam(Integer id, String name, String[] likes){

    System.out.println("testRquestParam");

    System.out.println(id);

    System.out.println(name);

    System.out.println(Arrays.toString(likes));

    return "/success.jsp";

}



  • If the method parameter name is inconsistent with the request parameter name, we can add @ RequestParam annotation, for example:
@RequestMapping("/testRquestParam")

public String testRquestParam(@RequestParam("id") Integer uid,@RequestParam("name") String name, @RequestParam("likes")String[] likes){

    System.out.println("testRquestParam");

    System.out.println(uid);

    System.out.println(name);

    System.out.println(Arrays.toString(likes));

    return "/success.jsp";

}



3.3.1.2. Obtain parameters and encapsulate them into entity objects 🔥

If we want to encapsulate these parameters into a User object, we can use the following method:

  • Note: the obtained parameters are encapsulated into entity objects without @ RequestBody annotation
@RequestMapping("/testRquestParam")

//The obtained parameters are encapsulated into entity objects without @ RequestBody annotation

public String testRquestParam(User user){

    System.out.println("testRquestParam");

    System.out.println(user);

    return "/success.jsp";

}



The User class is defined as follows:

@Data

@NoArgsConstructor

@AllArgsConstructor

public class User {

    private Integer id;

    private String name;

    private Integer age;

    private String[] likes;

}



When testing, the request url is as follows:

http://Localhost: 8080 / testrquestparam? Id = 1 & name = sanding cottage & likes = Programming & likes = lesson recording & likes = lol



Note: the member variable in the entity class should correspond to the request parameter name. And provide the corresponding set/get method.

3.4 relevant notes and other attributes 🔥

3.4.1,required🔥

  • The default value is true, that is, there must be corresponding parameters. If not, an error will be reported.

  • If the corresponding parameter can be transferred or not, it can be set to fasle

For example:

@RequestMapping("/testRquestParam")

public String testRquestParam(@RequestParam(value = "id",required = false) Integer uid,@RequestParam("name") Strcing name, @RequestParam("likes")String[] likes){

    System.out.println("testRquestParam");

    System.out.println(uid);

    System.out.println(name);

    System.out.println(Arrays.toString(likes));

    return "/success.jsp";

}



At this time, the uri requested during the test is as follows:

// You can choose to transmit id

http://Localhost: 8080 / testrquestparam? Id = 1 & name = sanding cottage & likes = Programming & likes = lesson recording & likes = lol

// You can also choose not to pass id

http://localhost:8080/testRquestParam?name = sanding cottage & likes = Programming & likes = recording lessons & likes = lol



3.4.2,defaultValue🔥

If the corresponding parameter has no parameters, we can use the defaultValue property to set the default value.

@RequestMapping("/testRquestParam")

public String testRquestParam(@RequestParam(value = "id",required = false,defaultValue = "777") Integer uid,@RequestParam("name") String name, @RequestParam("likes")String[] likes){

    System.out.println("testRquestParam");

    System.out.println(uid);

    System.out.println(name);

    System.out.println(Arrays.toString(likes));

    return "/success.jsp";

}



4. Type converter 🔥

===========================================================================

Although it seems very easy to get parameters earlier, there may be some problems in this process.

For example, if the request parameter is success=1, we expect to get the request parameter and assign it to a Boolean variable.

This will involve the type conversion of Stirng - > Boolean. In fact, spring MVC has many built-in type converters for type conversion. There is also a StringToBooleanConverter for Stirng - > boolean type conversion.

If it complies with the conversion rules of spring MVC built-in converter, the conversion can be easily implemented. But what if it doesn't comply with the rules of the converter?

For example, the request parameter is birthday=2004-12-12. We expect to get the request parameter and assign it to a variable of type Date. It doesn't comply with the built-in rules. The built-in can convert the format of 2004 / 12 / 12. In this case, we can choose Custom type conversion.

4.1. Custom type converter

â‘  Create a class to implement the Converter interface

String to Date type conversion

public class StringToDateConverter implements Converter<String, Date> {

    public Date convert(String source) {

        return null;

    }

}



â‘¡ Implement convert method

public class StringToDateConverter implements Converter<String, Date> {

    public Date convert(String source) {

        //String->Date   2005-12-12 

        Date date = null;

        try {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            date = simpleDateFormat.parse(source);

        } catch (ParseException e) {

            e.printStackTrace();

        }

        return date;

    }

}



â‘¢ Configure spring MVC to use custom converters

<!--Resolve response garbled code-->

<mvc:annotation-driven conversion-service="myConversionService">

    <mvc:message-converters>

        <bean class="org.springframework.http.converter.StringHttpMessageConverter">

            <constructor-arg value="utf-8"/>

        </bean>

    </mvc:message-converters>

</mvc:annotation-driven>



<bean class="org.springframework.context.support.ConversionServiceFactoryBean" id="myConversionService">

    <property name="converters">

        <set>

            <bean class="com.sangeng.converter.StringToDateConverter"></bean>

        </set>

    </property>

</bean>



5. Responder response data 🔥

=============================================================================

Whether it is RestFul style or asynchronous requests we have contacted in the web stage before, we need to convert the data into Json and put it into the response body.

5.1. Put the data into the responder 🔥

Spring MVC provides us with @ ResponseBody to easily put Json into the response body.

Location: on a class or method (see the source code)

  • On class: the return values of all methods in this class are put into the response body

  • Method: put the return value of this method into the response body

5.2 data conversion to Json 🔥

Spring MVC can convert us to Json, but it needs to be configured accordingly

5.2.1 configuration 🔥

  1. Import jackson dependency
<!-- jackson,Help with json transformation-->

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.9.0</version>

</dependency>



  1. Enable annotation driven mvc
<mvc:annotation-driven></mvc:annotation-driven>



5.2.2 example 1 of @ ResponseBody

  • Just return the data to be converted directly as the return value of the method.

  • Spring MVC will help us convert the return value into json

It is required to define a RestFul style interface, which can be used to query users according to id. The request path must be / response/user, and the request method must be GET. The request parameter id should be written on the request path, such as / response/user/1, where 1 is the id. It is required to obtain the parameter id, query the User information of the corresponding id (just simulate the query, you can choose to directly new a User object), and convert it into a json response to the response body.

@Controller

@RequestMapping("/response")

public class ResponseController {

    @GetMapping("/user/{id}")

    @ResponseBody //Put the return value of this method into the response body

    public User testResponse(@PathVariable Integer id){

        User user = new User(id,null,null,null);

        return user;//Because of json configuration, the return value will be converted into json

    }

}





5.2.3 example 2 of @ ResponseBody

It is required to define a RestFul style interface, which can query all users. The request path must be / response/user, and the request method must be GET. To query all User information (just simulate the query, you can choose to directly create a collection and add several User objects), and convert it into a json response to the response body.

@Controller

@RequestMapping("/response")

@ResponseBody  //The return values of all methods in this class are placed in the response body

public class ResponseController {



    @GetMapping("/user/{id}")

    public User testResponse(@PathVariable Integer id){

        User user = new User(id,null,null,null);

        return user;

    }



    @GetMapping("/user")

    public List<User> testResponse2(){

        List<User> list = new ArrayList<User>();

        list.add(new User(1,"third night watch",15,null));

        list.add(new User(2,"Four more",16,null));

        list.add(new User(3,"Five Watch",17,null));

        return list;

    }

}



At this time, @ ResponseBody is added to the class, indicating that the return values of all methods in the modified class will be placed in the response body. And converted to Json format.

We can use the @ RestController annotation to replace the @ Controller and @ ResponseBody annotations

@RequestMapping("/response")

@RestController //Equivalent to @ Controller+@ResponseBody

public class ResponseController {



    @GetMapping("/user/{id}")

    public User testResponse(@PathVariable Integer id){

        User user = new User(id,null,null,null);

        return user;

    }



    @GetMapping("/user")

    public List<User> testResponse2(){

        List<User> list = new ArrayList<User>();

        list.add(new User(1,"third night watch",15,null));

        list.add(new User(2,"Four more",16,null));

        list.add(new User(3,"Five Watch",17,null));

        return list;

    }

}



6. Get native object 🔥

============================================================================

We used to use request objects, response objects and session objects in the web phase. We can also get these objects through spring MVC( However, we rarely get these objects in MVC, because there is a simpler way to avoid using the relatively cumbersome API of these native objects.)

We only need to add the parameters of the corresponding type on the method, but pay attention to the data type. Spring MVC will pass the objects we need to our formal parameters.

For example:

@Controller

public class RequestResponseController {

    @RequestMapping("/getReqAndRes")

    public String getReqAndRes(HttpServletRequest request, HttpServletResponse response, HttpSession session){

        System.out.println();

        return "test";

    }

}



7. Get request header and Cookie 🔥

==================================================================================

7.1. Get request header 🔥

Define a parameter in the method, add @ RequestHeader annotation before the parameter, know the request header name to get, and then get the value of the corresponding request header.

For example:

To get the device type request header, you can define the method as follows.

@Controller

public class RequestResponseController {

    @RequestMapping("/getHeader")

    public String getHeader(@RequestHeader(value = "device-type") String deviceType){

        System.out.println(deviceType);

        return "test";

    }

}



7.2. Obtain cookies 🔥

Define a parameter in the method, and add the @ cookie value annotation before the parameter. You can get the value of the corresponding cookie by knowing the cookie name to be obtained.

For example:

Want to get the cookie value of JSESSIONID. You can define the method as follows.

@Controller

public class RequestResponseController {



    @RequestMapping("/getCookie")

    public String getCookie(@CookieValue("JSESSIONID") String sessionId){

        System.out.println(sessionId);

        return "test";

    }

}



8. JSP development pattern (understand)

===============================================================================

If we use JSP for development, we need to save data in the domain, then jump to the corresponding JSP page, obtain the data in the domain in the JSP page, and then carry out relevant processing.

If the development mode is similar to JSP, it will involve the operation of saving data to the domain and carrying data to jump to the page.

So let's take a look at the related operations with spring MVC.

8.1. Save data to the request field and jump

8.1.1. Use Model

We can use Model to store data in the current domain. Then use the previous method to realize page Jump.

For example:

When accessing / testRequestScope, we need to save name and title data in the Request field, and then jump to / WEB-INF/page/testScope.jsp. Get the data in the domain in Jsp.

You can use the following wording:

@Controller

public class JspController {

    @RequestMapping("/testRquestScope")

    public String testRquestScope(Model model){

        //Save data to the request field

        model.addAttribute("name","third night watch");

        model.addAttribute("title","Unknown Java course UP main");

        return "testScope";

    }

}



8.1.2. Use ModelAndView

We can use ModelAndView to save data and page Jump from and to the domain.

For example:

We require that when accessing / testRequestScope2, we can save name and title data into the domain, and then jump to / WEB-INF/page/testScope.jsp. Get the data in the domain in Jsp.

You can use the following wording:

@Controller

public class JspController {

    @RequestMapping("/testRquestScope2")

    public ModelAndView testRquestScope2(ModelAndView modelAndView){

        //Add data to domain

        modelAndView.addObject("name","third night watch");

        modelAndView.addObject("title","Unknown Java course UP main");

        //Page Jump

        modelAndView.setViewName("testScope");

        return modelAndView;

    }

}



  • Note that the modelAndView object should be returned as the return value of the method

8.2. Get data from the Request field

Posted by al3x8730 on Sun, 05 Sep 2021 20:24:36 -0700