Spring MVC parameters and return values

Catalog

One with jsp

You can return String or ModelAndView

@RequestMapping("/demo2")
@Controller
public class TestController2 {

    @RequestMapping("/string")
    public String demo2(HttpServletRequest request){
        request.setAttribute("name","Wang Da hammer");

        return "demo2";
    }

    @RequestMapping("/mav")
    public ModelAndView mav1(ModelAndView modelAndView) {
        // Pass the results to the page

        modelAndView.addObject("name","Pikachu" );
        // Set logical view
        modelAndView.setViewName("demo2");
        return modelAndView;
    }


    @RequestMapping("/mav2")
    public ModelAndView mav2() {
        // Pass the results to the page
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name","Little intelligence" );
        // Set logical view
        modelAndView.setViewName("demo2");
        return modelAndView;
    }


    @RequestMapping("/model")
    public String model(Model model) {
        // Pass the results to the page
        model.addAttribute("name","Fire dragon");
        // Set logical view

        return "demo2";
    }


}

jsp

%@ page import="java.util.Date" %><%--
  Created by IntelliJ IDEA.
  User: zyc
  Date: 2019/6/9
  Time: 20:03
  To change this template use File | Settings | File Templates.
--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>demo2</title>
</head>
<body>

    <h1>${requestScope.name}</h1>
    <%
        Date date = new Date();
        out.print(date);
    %>

    <%= date %>
</body>
</html>

Two parameter binding

Common types

POJO:Spring MVC will automatically match the request parameter name and POJO property name, and automatically fill in the property value for the object. Cascade properties are supported.
For example: dept.deptId, dept.address.tel, etc.

    	@RequestMapping("/testPojo")
    	public String testPojo(User user) {
    		System.out.println("testPojo: " + user);
    		return SUCCESS;
    	}

Support for servlet native API

    /**
     * You can use the servlet native API as the parameter of the target method to specifically support the following types
     * 
     * HttpServletRequest 
     * HttpServletResponse 
     * HttpSession
     * java.security.Principal 
     * Locale 
     * InputStream 
     * OutputStream 
     * Reader 
     * Writer
     * @throws IOException 
     */
    @RequestMapping("/testServletAPI")
    public void testServletAPI(HttpServletRequest request,
    		HttpServletResponse response, Writer out) throws IOException {
    	System.out.println("testServletAPI, " + request + ", " + response);
    	out.write("hello springmvc");
    	}

Default supported parameter types

The following types of parameters are added to the processor parameters, which are identified and assigned by the processing adapter by default.

  • HttpServletRequest: obtain the request information through the request object.
  • HttpServletResponse: process response information through response.
  • HttpSession: get the object stored in the session through the session object.
  • Model/ModelMap: ModelMap is the implementation class of the model interface, through which we can transfer data to the page.

Simple data type binding

When the parameter name of the Request is consistent with the processor parameter name, the Request parameter is bound to the parameter. The method of taking parameters from Request can be further simplified
@RequestParam
The @ RequestParam annotation is often used to handle simple type bindings.

  • Value: parameter name, that is, the request parameter name of the input parameter. For example, value = "item UU ID" indicates that the value of the parameter whose name is item UU ID in the parameter area of the request will be passed in.
  • Required: required or not. The default value is true, which means there must be corresponding parameters in the request. Otherwise, the following error will be reported:
  • defaultValue: the default value, which means the default value if there is no parameter with the same name in the request.

Request garbled processing

post

<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>

get
Modify tomcat configuration file to add code consistent with project code

<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

Custom Converter

Do not submit data of date type in the form, otherwise a 400 error will be reported. If you want to submit data of date type, you need to use the content bound by later custom parameters.
Implementation class

public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(source);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;

    }

}

configuration file
Mode 1: expand < MVC: annotation driven / >

!-- Configure an annotation driver. If you configure this label, you can avoid configuring the processor mapper and processor adapter. -->
<mvc:annotation-driven conversion-service="conversionService" />
<!-- Converter configuration -->
<bean id="conversionService"
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.zyc.controller.DateConverter"/>
        </set>
    </property>
</bean>


Mode 2: customize webBinder

<!-- Converter configuration -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.zyc.controller.DateConverter"/>
            </set>
        </property>
    </bean>
    <!-- custom webBinder -->
    <bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <property name="conversionService" ref="conversionService" />
    </bean>

Three methods return value

Return to ModelAndView

Return to void

  1. Use request to forward pages
request.getRequestDispatcher("Page path").forward(request, response);
  1. response to realize page redirection
response.sendRedirect("url")
  1. Response response
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json strand");

Return string

Logical view name

spring mvc encapsulates strings as logical view names into a ModelAndView

Redirect, forward

return "redirect:/item/itemList.action?id=xxx&name=xxx";

return "forward:/item/itemList.action";

Reference resources

  1. Spring MVC learning (5) -- parameter binding of spring MVC
  2. Spring MVC learning (7) -- method return value of Controller class

Keywords: Spring JSP Java Session

Added by donbonzo on Sun, 27 Oct 2019 10:02:46 +0200