Annotations for binding request data in SPRINGMVC and Configuration view resolver

Source: Internet
Author: User

Annotations for binding request data in SPRINGMVC

In the previous article, we briefly introduced @requestmapping and @requestparam annotations and learned how to configure address mapping, and this article introduces some annotations for handling the request data.

[email protected] Note, which is used to process the header part of the request, which is the part of the HTTP header, which binds the value of the header part to the parameters of the method, example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestHeader;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/test")public class Test {    @RequestMapping("test.do")    public void method(            @RequestHeader("Host") String host,            @RequestHeader("Content-Type") String contentType    ){        System.out.println(host);        System.out.println(contentType);    }}

Access using postman, accessed as follows:

Console Print Results:

localhost:8080application/json

As you can see from the printed results, the above code binds the host in the HTTP request header and the value of the Content-type field to the method parameter of the annotation configuration, which is what the @requestheader annotation does.

[email protected] Note, which is used to bind the value of the cookie in the HTTP request header to the parameters of the method, example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.CookieValue;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/test")public class Test {    @RequestMapping("test.do")    public void method(            @CookieValue("JSEESIONID") String cookie    ){        System.out.println(cookie);    }}

Access using postman, accessed as follows:

Console Print Results:

415A4AC178C59DACE0B2C9CA727CDD84

As above, @CookieValue annotations help us bind the value of Jseesionid in the cookie to the parameters of the method.

[email protected] annotations, which can bind the values of the URL placeholder mappings configured in the @requestmapping annotations to the corresponding method parameters, example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/test")public class Test {    // 将URL上映射的值绑定到方法参数上,用 {} 来进行绑定    @RequestMapping("test.do/{typeid}/{id}")    public void method(            @PathVariable String typeid,            @PathVariable String id    ) {        System.out.println(typeid);        System.out.println(id);    }}

Access using postman, accessed as follows:

Console Print Results:

845125

[email protected] annotations, which are commonly used to process data such as Application/json, Application/xml, which is used to process HTTP request body content. This annotation makes it easy to get the data from the request body, and no longer reads through the stream as it did with the servlet, for example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controller@RequestMapping("/test")public class Test {    @RequestMapping("/test.do")    public void method(            @RequestBody String json    ) {        System.out.println(json);    }}

Access using postman, accessed as follows:

Console Print Results:

{    "name" : "Jon",    "age" : 23,    "address" : "usa"}

[email protected] annotation, which is used to bind the value in the method parameter to the attribute of HttpSession, which is written on the class, example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import java.util.Map;@Controller@SessionAttributes("name")@RequestMapping("/test")public class Test {    @RequestMapping("/test.do")    public void method(Map<String, Object> map) {        // 由于@SessionAttributes注解的作用,这对键值会被存储一份到HttpSession对象的attribute中        map.put("name", "Jon");    }}

The note has value, types, two properties that specify the data that needs to be stored in the HttpSession, by name and type, as an example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import java.util.Map;@Controller@SessionAttributes(value = "name", types = Object.class)@RequestMapping("/test")public class Test {    @RequestMapping("/test.do")    public void method(Map<String, Object> map) {        // 由于@SessionAttributes注解的作用,这对键值会被存储一份到HttpSession对象的attribute中        map.put("name", "Jon");    }}

[email protected] annotations, which are used to access property values in pre-existing httpsession, such as the value of a name stored in HttpSession, The value of this name can be removed by @sessionattribute annotations and can be bound to the parameters of the method, so this annotation is written on the method parameter, example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controller@RequestMapping("/test")public class Test {    @RequestMapping("/test.do")    // 拿出HttpSession中键为name的值,绑定到方法参数name上    public void method(@SessionAttribute("name") String name) {    }}

[email protected] Note, the note has two usages, one for the method and one for the parameter:

    • When used on a method: the model that needs to be queried from the background to bind the request before processing @requestmapping;
    • When used on parameters: used to bind the value of the corresponding name to the parameter bean of the annotation by name, and the value to be bound is derived from:
      • @SessionAttributes enabled on the attribute object;
      • @ModelAttribute the model object specified on the method;
      • In either case, new is a bean object that needs to be bound, and then binds the value in the request to the bean in the same way as the name.

Example code to use on the method:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controller@RequestMapping("/test")public class Test {    @ModelAttribute    @RequestMapping("/test.do")    public Account method(@RequestParam String number) {        return accountManager.findAccount(number);    }}

Example code to use on the parameter:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controller@RequestMapping("/test")public class Test {    @RequestMapping("/test.do")    public void method(@ModelAttribute String name) {    }}
Get HttpRequest and HttpResponse objects

In the controller to obtain HttpRequest and HttpResponse objects is very simple, directly on the method to declare the parameters of these two objects, example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@Controller@RequestMapping("/test")public class Test {    @RequestMapping("/test.do")    public void method(HttpServletRequest request, HttpServletResponse response) {        System.out.println(request.getRequestURI());        System.out.println(response.getStatus());    }}

Access using postman, accessed as follows:

Console Print Results:

/test/test.do200
Encapsulates a URL parameter into an object's properties

Usually there are several parameters on the URL, we want to encapsulate these parameters into the properties of an object, so that there is no need to declare multiple parameters on the method, only need to declare an object. And SPRINGMVC can help us do this automatically, we just need to create a wrapper class. For example, I create a student class that encapsulates the properties corresponding to the URL parameter:

The student class code is as follows:

package org.zero01.test;public class Student {    private String sname;    private int age;    private String address;    public String getSname() {        return sname;    }    public void setSname(String sname) {        this.sname = sname;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }}

The controller code is as follows:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controller@RequestMapping("/test")public class Test {    @RequestMapping("/test.do")    // 只需要在方法上声明一个对象参数即可    public void method(Student student) {        System.out.println(student.getSname());        System.out.println(student.getAge());        System.out.println(student.getAddress());    }}

Access using postman, accessed as follows:

Console Print Results:

Jon2215

Note: The name of the URL parameter corresponds to the name of the object property, otherwise it cannot be bound. Such as:

Console Print Results:

Jon0null
Array parameter binding

SPRINGMVC In addition to automatically bind parameters to the Pojo object, you can also automatically bind parameters to the array object, where the array refers to an integer, stirng, long and other basic data types of the wrapper class array, as well as int, long, An array of basic data types such as Byte, example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controllerpublic class Test {    @RequestMapping(value = "/test.do")    public void method(String[] names) {        for (String name : names) {            System.out.println(name);        }    }}

Access using postman, accessed as follows:

Console Print Results:

JonMackAlinStevenEson

An array of basic data types is the same:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controllerpublic class Test {    @RequestMapping(value = "/test.do")    public void method(int[] numbers) {        for (int number : numbers) {            System.out.println(number);        }    }}

Access using postman, accessed as follows:

Console Print Results:

12345
Collection type parameter binding

For parameter bindings of collection types such as list, set, map, if we try to bind directly, it will fail, we must use it as a member property of a concrete class object, we can also call this concrete class object as a wrapper class.

The Pojo class code is as follows:

package org.zero01.test;import java.util.*;public class Student {    private Map<String, Integer> map;    private List<String> list;    private Set<String> set;    public Map<String, Integer> getMap() {        return map;    }    public void setMap(Map<String, Integer> map) {        this.map = map;    }    public List<String> getList() {        return list;    }    public void setList(List<String> list) {        this.list = list;    }    public Set<String> getSet() {        return set;    }    public void setSet(Set<String> set) {        this.set = set;    }}

The controller code is as follows:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controllerpublic class Test {    @RequestMapping(value = "/test.do")    public void method(Student student) {        System.out.println(student.getMap());        System.out.println(student.getList());        System.out.println(student.getSet());    }}

Access using postman, accessed as follows:

Console Print Results:

{one=1, three=3, tow=2}[4, 5, 6][7, 8, 9]
Forward to view by method return value

In Springmvc, the controller only needs to be forwarded to a specified view by the return value of the method, as an example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controllerpublic class Test {    @RequestMapping(value = "/test.do", method = RequestMethod.GET)    public String method() {        return "index.jsp";    }}

Index.jsp content is as follows:

Access with postman, with the following results:

By default, no keyword is used for the forwarding mechanism (forward), and if you precede the view name with the redirect keyword you use the redirect mechanism (redirect) example:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controllerpublic class Test { @RequestMapping(value = "/test.do", method = RequestMethod.GET) public String method() { return "redirect:index.jsp"; }}

However, most of the time for security, we usually put JSP files in the Web-inf directory, and the JSP files placed in this directory can not be redirected to access, can only be accessed through the forwarding mechanism. Because the file under the Web-inf directory is not allowed to be accessed externally, redirects are external access, and external access is reported with a 404 error, as follows:

can only be accessed through internal forwarding:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controllerpublic class Test { @RequestMapping(value = "/test.do") public String method() { return "WEB-INF/index.jsp"; }}

Access results:

Configuring the View resolver

In the above experiment, we only put the JSP file in the Web-inf directory, but if the JSP file is in many levels of directory, then we are forwarded to the JSP by the return value, we need to write the path is very long. For example, I create a pages directory under the Web-inf directory, create an index directory in the pages directory, and then put the index.jsp file in this index directory, then we need to write a path like this:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controllerpublic class Test {    @RequestMapping(value = "/test.do")    public String method() {        return "WEB-INF/pages/index/index.jsp";    }}

If you do not want to write such a long path, you need to use the view parser in Springmvc, in the spring configuration file, add the following:

    <!-- 配置视图解析器 -->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- 视图名称的前缀 -->        <property name="prefix" value="/WEB-INF/pages/index/"/>        <!-- 视图名称的后缀 -->        <property name="suffix" value=".jsp"/>    </bean>

Controller code:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;@Controllerpublic class Test {    @RequestMapping(value = "/test.do")    public String method() {        return "index";    }}

As you can see from the controller code, after the view resolver is configured, we only need to write the name of the view, so we don't have to write the full path.

Access results:

Annotations for binding request data in SPRINGMVC and Configuration view resolver

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.