02-1 data response mode and annotation of spring MVC

1@Controller , @ RequestMapping, @ RequestParam annotation

1.1@Controller 

@The Controller annotation is used to declare that an instance of a class is a Controller,

@Controller
public class UserController {
    //Business code

}

Note: the annotation based controller class in the application needs to be found through the Spring MVC scanning mechanism. In order for the controller class to be scanned by the Spring MVC framework, the spring context needs to be declared in the configuration file and used  < context:component-scan/>   Element specifies the base package of the controller class (please ensure that all controller classes are under the base package and its sub packages)

  <context:component-scan base-package="com.nie.controller" />

1.2@RequestMapping

@RequestMapping is used to establish the corresponding relationship between the request URL and the request processing method, and is responsible for mapping the request to the corresponding controller method.

@RequestMapping can be used on classes and methods. It means that all methods in the class that respond to requests take this address as the parent path.

Common attributes:

         Value: the value attribute is used to specify the URL of the request and the default attribute of the @ RequestMapping annotation. Therefore, if there is only the value attribute, the attribute name can be omitted. If there are other attributes, the value attribute name must be written. Its function is the same as that of the path attribute.
        Method: the method property indicates which HTTP requests the method supports. If the method attribute is omitted, it indicates that the method supports all HTTP requests.
        Params: the params property is used to specify the conditions that limit the request parameters. It supports simple expressions. The key and value as like as two peas for the request parameters must be exactly the same as those configured.

@Controller
public class UserController {
    @RequestMapping(value = "/getUser",method = RequestMethod.GET,params ={ "name","age"})
    public String getUer(){
        System.out.println("getUser.....");
        return "/index.jsp";
    }
}

Detailed properties can be viewed through the source code

1.3@RequestParam

When the requested parameter name is inconsistent with the business method parameter name of the Controller, the annotation needs to be bound through the parameter @The RequestParam annotation shows the binding.
  • value: the name of the request parameter
  • required: whether the specified request parameters must be included. The default is true. If there is no such parameter during submission, an error will be reported
  • defaultValue: when no request parameter is specified, the specified default value is used for assignment
 @RequestMapping(value = "/getUser",method = RequestMethod.GET)
    @ResponseBody
    public void getUer(@RequestParam(value = "name",required = false) String username, @RequestParam(defaultValue = "18") int age ){
        System.out.println(username);
        System.out.println(age);
    }

2 data request response method - request data

The request parameters that spring MVC can receive are

  • Basic type parameters
  • POJO type parameters
  • Array type parameter
  • Set type parameter

① Basic type parameters

The parameter name of the business method in the Controller should be consistent with the name of the request parameter, and the parameter value will be mapped and matched automatically.
http://localhost:8080/springMVC/getUser?username=zhangsan&age=12
   @RequestMapping(value = "/getUser",method = RequestMethod.GET)
    @ResponseBody
    public void getUer(String username,int age){
        System.out.println(username);
        System.out.println(age);
    }

② POJO type parameters

http://localhost:8080/springMVC/getUser?username=zhangsan&age=12
The property name of the POJO parameter of the business method in the Controller is consistent with the name of the request parameter, and the parameter value will be mapped and matched automatically.
public class User {
        private String username;
        private int age;
        getter/setter...
}
@RequestMapping("/getUser")
@ResponseBody
public void getUser(User user) throws IOException {
        System.out.println(user);
}

  ③ Array type parameter

//Request address
http://localhost:8080/springMVC/getUser?user1=zhangsan&user1=lisi
//controller method
@RequestMapping("/getUser")
@ResponseBody
public void getUser(String[] users) throws IOException {
        System.out.println(Arrays.asList(users));
}

④ Collection data type
        Encapsulated into an entity class or received directly through a List

Encapsulate to entity class

--Front end code
< form action= " ${ pageContext.request.contextPath } /getUser" method= "post" >
< input type= "text" name= "userList[0].username" >< br >
< input type= "text" name= "userList[0].age" >< br >
< input type= "text" name= "userList[1].username" >< br >
< input type= "text" name= "userList[1].age" >< br >
< input type= "submit" value= " Submit " >< br >

</form>

--Controller layer code

@RequestMapping ( "/saveUser" )
@ResponseBody
public void saveUser (Vo vo) throws IOException {
System. out .println(vo.getUserList());
}

 -- Entity class

public class VO {

    private List<User> userList;

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    @Override
    public String toString() {
        return "VO{" +
                "userList=" + userList +
                '}';
    }
}
public class User {

    private String username;
    private int age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}

Receive via List:
         When submitting with ajax, you can specify the content type as json, so using @ RequestBody at the method parameter position can directly receive the collection data without using POJO for packaging.

< script >
// Analog data
var userList = new Array ();
userList . push ({ username : "zhangsan" , age : "20" });
userList . push ({ username : "lisi" , age : "20" });
$ . ajax ({
type : "POST" ,
url : "/springMVC/saveUser" ,
data : JSON . stringify ( userList ),
contentType : 'application/json;charset=utf-8'
});
</ script >
@RequestMapping("/saveUser")
@ResponseBody
public void saveUser(@RequestBody List<User> userList) throws 
IOException {
    System.out.println(userList);
}

3 data response mode - response data

3.1 return to page Jump

Directly return string: this method will splice the returned string with the front suffix of the view parser and jump.
For example, if the index is returned, it will be spliced and forwarded to the resource address / jsp/index.jsp according to the spring-mvc.xml configuration file

 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--  /jsp/xxx.jsp -->
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

The controller method is

  //Page Jump return string
    @RequestMapping(value = "test01",method = RequestMethod.GET,params = {"value1","value2"})
    public String test01(){
        System.out.println("Return string test");
        return  "index";
    }

Return to ModelAndView:

    /*Page jump back to ModelAndView
               Model:Model action encapsulates data
               View: View function: display data
     */
    @RequestMapping(value="/test02")
    public ModelAndView test02(){
        ModelAndView modelAndView = new ModelAndView();
        //Set model data
        modelAndView.addObject("testkey","testvalue");
        //Set view name
        modelAndView.setViewName("test02");//    /jsp/test02.jsp
        return modelAndView;
    }

3.2 page updating data

Injected response object
The response object injected through the spring MVC framework uses response.getWriter().print("hello world") to write back data. At this time, view jump is not required, and the return value of the business method is void

  @RequestMapping(value="/test")
    public void test(HttpServletResponse response) throws IOException {
        response.getWriter().print("test springmvc");
    }

Annotation through @ ResponseBody (common)
Return the string to be written back directly, but at this time, you need to inform the spring MVC framework through the @ ResponseBody annotation that the string returned by the method is not a jump, but directly returned in the http response body.

    @RequestMapping(value="/test")
    @ResponseBody  //Tell the spring MVC framework to respond directly to data without view jump
    public String test() throws IOException {
        return "test springmvc";
    }

Tags: Java Spring MVC

Posted on Wed, 10 Nov 2021 12:58:14 -0500 by kooper