SpringMVC frame (2) - request and response

01-SpringMVC data response - a response mode data (understood)

1) Page Jump

Returns a string directly

The object is returned by ModelAndView

2) write-back data

Returns a string directly

Return an object or collection

02-SpringMVC data response - Page Jump - returns a string form (application)

03-SpringMVC response data - the page Jump - Returns ModelAndView form 1 (application)

 ModelAndView method returns the object in the Controller, and set view name

@RequestMapping(value="/quick2")
    public ModelAndView save2(){
        /*
            Model: Model Data encapsulation effect
            View: View action display data
         * / 
        ModelAndView ModelAndView = new new ModelAndView ();
         // set model data 
        modelAndView.addObject ( "username", "itcast" );
         // set view name 
        modelAndView.setViewName ( "Success" );

        return modelAndView;
    }

04-SpringMVC response data - page Jump - Returns ModelAndView form 2 (application)

n in the Controller method parameter declaration ModelAndView directly, without the need to create their own in the method, the object method is provided directly in the view, the same jump page

 @RequestMapping(value="/quick3")
    public ModelAndView save3(ModelAndView modelAndView){
        modelAndView.addObject("username","itheima");
        modelAndView.setViewName("success");
        return modelAndView;
    }
@RequestMapping(value="/quick4")
    public String save4(Model model){
        model.addAttribute("username","博学谷");
        return "success";
    }

05-SpringMVC data response - Page Jump - Returns ModelAndView3 (application)

It can be used directly HttpServeltRequest native objects, only the statement of the method can parameter Controller

@RequestMapping(value="/quick5")
    public String save5(HttpServletRequest request){
        request.setAttribute("username","酷丁鱼");
        return "success";
    }

06-SpringMVC data response - write-back data - Direct write-back string (application)

SpringMVC response frame by the target injection using response.getWriter (). Print ( "hello world") write-back data, then the jump, no view, business methods returning void

Will need to write back the string returned directly, but this time you need to tell SpringMVC framework by @ResponseBody notes, string method returns a jump is not returned directly in the response body http

@RequestMapping(value="/quick7")
    @ResponseBody   // inform SpringMVC frame not directly view the data in response to the jump 
    public String save7 () throws IOException {
         return "Hello itheima" ;
    }

    @RequestMapping(value="/quick6")
    public void save6(HttpServletResponse response) throws IOException {
        response.getWriter().print("hello itcast");
    }

07-SpringMVC data response - write-back data - write directly back to json format string (application)

@RequestMapping(value="/quick8")
    @ResponseBody
    public String save8() throws IOException {
        return "{\"username\":\"zhangsan\",\"age\":18}";
    }

Json format string manually splicing the way a lot of trouble, often develop complex java object you want to convert a string json format, we can use the web through the stages of learning jackson conversion tool to convert json, json format string conversion by jackson , write-back string

@RequestMapping(value="/quick9")
    @ResponseBody
    public String save9() throws IOException {
        User user = new User();
        user.setUsername("lisi");
        user.setAge ( 30 );
         // use json conversion tool to convert the object into a string in the format json return 
        ObjectMapper ObjectMapper = new new ObjectMapper ();
        String json = objectMapper.writeValueAsString(user);

        return json;
    }

08-SpringMVC response data - write-back of data - Returns a collection of objects or (application)

By help us SpringMVC object or collection of the string and converting json writeback, processor configuration parameter message into an adapter, specify jackson object or collection of conversion, and therefore needs to be disposed below the spring-mvc.xml

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
    </bean>
@RequestMapping(value="/quick10")
    @ResponseBody
    // desirable SpringMVC User automatically convert to string format json 
    public User save10 () throws IOException {
        User user = new User();
        user.setUsername("lisi2");
        user.setAge(32);
        return user;
    }

09-SpringMVC response data - write-back of data - Returns a collection of objects or 2 (application)

In the method of adding @ResponseBody may return json string format, but this configuration is relatively cumbersome, the more code configuration, so we can use instead of the drive mvc annotation configuration

<mvc:annotation-driven/>

SpringMVC the various components, the mapping processor, a processor adapter viewresolver as the three components of SpringMVC.

Use <mvc:annotation-driven />automatic loading RequestMappingHandlerMapping (process mapper) and

RequestMappingHandlerAdapter (processing adapter), available in the configuration file Spring-xml.xml

<mvc:annotation-driven />Alternatively annotation configure the processor and adapters.

use simultaneously<mvc:annotation-driven />

The bottom will be integrated jackson default object or collection of json format string conversion

10-SpringMVC response data - to know before summary (understanding, memory)

1) Page Jump

Returns a string directly

The object is returned by ModelAndView

2) write-back data

Returns a string directly

HttpServletResponse object directly write back data, HttpServletRequest objects back to the data, Model objects brought back data or write data back to a string @ResponseBody

Return an object or collection

@ResponseBody+<mvc:annotation-driven/>

 

SpringMVC request

11-SpringMVC request - parameter acquisition request - the request parameter type (understood)

Format client request parameters are: name = value & name = value ......

To obtain the parameters of the request the server side, and sometimes the encapsulated data, SPRINGMVC may receive the following types of parameters

The basic parameters of the type

POJO type parameter

Array type parameters

Collection type parameter

12-SpringMVC request - obtaining request parameters - parameters obtained basic types (application)

Controller method parameter name in the service to be consistent with the request parameter name, parameter value automatically map matching. Type conversion and can be done automatically;

Automatic type conversion refers to the conversion from String to other types of

http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12

@RequestMapping(value="/quick11")
    @ResponseBody
    public void save11(String username,int age) throws IOException {
        System.out.println(username);
        System.out.println(age);
    }

13-SpringMVC request - obtaining request parameters - parameters obtained POJO type (application)

POJO attribute name service method Controller parameters in accordance with a request parameter name, parameter value automatically map matching.

package com.itheima.domain;

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 +
                '}';
    }
}
@RequestMapping(value="/quick12")
    @ResponseBody
    public void save12(User user) throws IOException {
        System.out.println(user);
    }

14-SpringMVC request - obtaining request parameter - to obtain the array type parameters (application)

Controller array name service method in accordance with the request parameter name, parameter value automatically map matching.

@RequestMapping(value="/quick13")
    @ResponseBody
    public void save13(String[] strs) throws IOException {
        System.out.println(Arrays.asList(strs));
    }

15-SpringMVC request - obtaining request parameter - obtaining a set of parameter types (application)

Obtaining a set of parameters, it can be a set of parameters you want to package into a POJO.

<form action="${pageContext.request.contextPath}/user/quick14" method="post">
        <% - indicates that the first object is a username age User -%>
        <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="提交">
    </form>
package com.itheima.domain;

import java.util.List;

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 +
                '}';
    }
}
@RequestMapping(value="/quick14")
    @ResponseBody
    public void save14(VO vo) throws IOException {
        System.out.println(vo);
    }

16-SpringMVC request - obtaining request parameter - set type parameters obtained 2 (application)

When using ajax submit, to be specified contentType json form, the parameters used in the method of @RequestBody position data set may be received directly without the use of packaged POJO

<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
    <script>
        var userList = new Array();
        userList.push({username:"zhangsan",age:18});
        userList.push({username:"lisi",age:28});

        $.ajax({
            type:"POST",
            url:"${pageContext.request.contextPath}/user/quick15",
            data:JSON.stringify(userList),
            contentType:"application/json;charset=utf-8"
        });

    </script>
@RequestMapping(value="/quick15")
    @ResponseBody
    public void save15(@RequestBody List<User> userList) throws IOException {
        System.out.println(userList);
    }

17-SpringMVC request - get the request parameters - open access to static resources (applications)

When there is need to load static resources, such as jquery files through Google developer tools Ethereal found no documents loaded into jquery, because the front-end controller DispatcherServlet SpringMVC of url-pattern configuration is /, representatives of all resources filtration operations, we can specify the release of static resources in two ways:

• Specify the release of resources in the spring-mvc.xml profile

<mvc:resources mapping="/js/**"location="/js/"/>

• Use <mvc:default-servlet-handler/>labels

<! - access to development resources ->
    <!--<mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/img/**" location="/img/"/>-->

    <mvc:default-servlet-handler/>

18-SpringMVC request - obtaining request parameter - the global distortion filter configuration (application)

When the post request, the data will be garbled, we can set a filter to filter coding.

<! - configure the global filtration filter ->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

19-SpringMVC request - obtaining request Parameter - parameter binding annotation @RequestParam (application)

When the service is inconsistent with the parameter names method Controller requests, it is necessary binding displayed by the annotation @RequestParam

<form action="${pageContext.request.contextPath}/quick16" method="post">
    <input type="text" name="name"><br>
    <input type="submit" value="提交"><br>
</form>
@RequestMapping(value="/quick16")
    @ResponseBody
    public void save16(@RequestParam(value="name",required = false,defaultValue = "itcast") String username) throws IOException {
        System.out.println(username);
    }

20-SpringMVC request - the request parameter acquisition parameters obtained -Restful style (application)

Restful is a style of software architecture, design, rather than the standard, but provides a set of design principles and constraints. Mainly used for client and server interaction class of software, based on the style of the software can be more concise, more structured and easier to implement caching mechanism.

Restful style request using "url + Request Mode" indicates a purpose of the request, HTTP protocol operation verbs which four of the following:

GET: for access to resources

POST: New Resource for

PUT: update resource for

DELETE: to delete the resource

E.g:

/ User / 1 GET: id = user 1 is obtained

/ User / 1 DELETE: Delete id = user 1's

/ User / 1 PUT: Update id = user 1 is

/ User POST: New user

1 is above the url request parameters to be obtained in / user / 1, can be used in the placeholder SpringMVC binding of parameters. Address / user / 1 can be written / user / {id}, {id} placeholder is the value corresponding to 1. In business methods we can use @PathVariable annotation matching placeholder get work.

http://localhost:8080/itheima_springmvc1/quick17/zhangsan

@RequestMapping(value="/quick17/{name}")
@ResponseBody
 public void save17(@PathVariable(value="name") String username) throws IOException {
        System.out.println(username);
 }

21-SpringMVC request - obtaining request parameter - custom type converter (application)

SpringMVC default has provided some common types of converters, such as string submitted by the client to int parameter settings.

But not all data types provide a converter, there is no need to provide custom converters, such as: date type of data you need a custom converter.

public  class DateConverter the implements Converter <String, a Date> {
     public a Date Convert (String dateStr) {
         // convert the date string to a date object returns 
        the SimpleDateFormat the format = new new the SimpleDateFormat ( "the MM-dd-YYYY" );
        Date date = null;
        try {
            date = format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace ();
        }
        return date;
    }
}
@RequestMapping(value="/quick18")
    @ResponseBody
    public void save18(Date date) throws IOException {
        System.out.println(date);
    }

22-SpringMVC request - obtaining request parameter - Servlet obtain relevant API (Application)

ServletAPI SpringMVC favor of the original object as a parameter to control the injection process, commonly used objects are as follows:

HttpServletRequest

HttpServletResponse

HttpSession

@RequestMapping(value="/quick19")
    @ResponseBody
    public void save19(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        System.out.println(request);
        System.out.println(response);
        System.out.println(session);
    }

23-SpringMVC request - obtaining request parameter - header information acquisition request (application)

Use @RequestHeader request header information can be obtained, the equivalent of web learning stage request.getHeader (name)

@RequestHeader annotation attributes are as follows:

value: request header name

required: Do you have to carry this request header

@RequestMapping(value="/quick20")
    @ResponseBody
    public void save20(@RequestHeader(value = "User-Agent",required = false) String user_agent) throws IOException {
        System.out.println(user_agent);
    }

Use @CookieValue can get the specified value of Cookie

@CookieValue annotation attributes are as follows:

value: Specifies the name of the cookie

required: Do you have to carry this cookie

 @RequestMapping(value="/quick21")
    @ResponseBody
    public void save21(@CookieValue(value = "JSESSIONID") String jsessionId) throws IOException {
        System.out.println(jsessionId);
    }

Guess you like

Origin www.cnblogs.com/j9527/p/12039550.html