SpringMVC [SpringMVC parameter acquisition, SpringMVC processing response] (2) - comprehensive detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

 SpringMVC parameter acquisition_Using Servlet native objects to obtain parameters 

 SpringMVC parameter acquisition_custom parameter type converter

SpringMVC parameter acquisition_encoding filter 

SpringMVC handles the response_configuration view resolver

SpringMVC handles the response_return value of the controller method

SpringMVC handles response _request field setting data 

SpringMVC processes response _session domain setting data


 

 SpringMVC parameter acquisition_Using Servlet native objects to obtain parameters 

 SpringMVC also supports the use of Servlet native objects, and parameters of HttpServletRequest, HttpServletResponse, HttpSession and other types can be directly used in the method by defining parameters of the method.

// 使用Servlet原生对象
@RequestMapping("/c1/param8")
public void servletParam(HttpServletRequest request, HttpServletResponse response,
HttpSession session){  
       // 原生对象获取参数      
       System.out.println(request.getParameter("name"));
       System.out.println(response.getCharacterEncoding());    
       System.out.println(session.getId());
}

Just visit this method: http://localhost:8080/c1/param8?name=bjwan

In general, there are alternatives to the methods of Servlet native objects in SpringMVC, and it is recommended to use SpringMVC instead of Servlet native objects. 

 SpringMVC parameter acquisition_custom parameter type converter

 The parameters from the front end are all of string type, and SpringMVC uses its own converter to convert the string parameters to the required type. like:

// 获取简单类型参数
@RequestMapping("/c1/param1")
public void simpleParam(String username,int age){
    System.out.println(username);    
    System.out.println(age);
}

Request path: http://localhost:8080/c1/param1?username=bz&age=10

But in some cases, the string cannot be converted to the required type, such as:

@RequestMapping("/c1/param9")
public void dateParam(Date birthday){  
    System.out.println(birthday);
}

Since there are many formats of date data, SpringMVC cannot convert strings in all formats into date types. For example, when the parameter format is birthday=2025-01-01, SpringMVC cannot parse the parameter. In this case a custom parameter type converter is required.

 1. Define the type converter class and implement the Converter interface

// 类型转换器必须实现Converter接口,两个泛型代表转换前的类型,转换后的类型
public class DateConverter implements Converter<String, Date> {
    /**
     * 转换方法
     * @param source 转换前的数据
     * @return 转换后的数据
     */
    @Override
    public Date convert(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(source);
       } catch (ParseException e) {
            e.printStackTrace();
       }
        return date;
   }
}

2. Register the type converter object

<!-- 配置转换器工厂 -->
<bean id="dateConverter" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <!-- 转换器集合 -->
    <property name="converters">
        <set>
            <!-- 自定义转换器 -->
            <bean class="com.tong.converter.DateConverter"></bean>
        </set>
    </property>
</bean    
<!-- 使用转换器工厂 -->
<mvc:annotation-driven conversionservice="converterFactory">
</mvc:annotation-driven>

3. At this time, when visiting http://localhost:8080/c1/param9?birthday=2025-01-01, SpringMVC can encapsulate the request parameters into Date type parameters.

SpringMVC parameter acquisition_encoding filter 

 When passing parameters, tomcat8 and above can handle the Chinese garbled characters of the get request, but cannot handle the Chinese garbled characters of the post request

1. Write jsp form

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>编码过滤器</title>
    </head>
    <body>
        <form action="/cn/code" method="post">
           姓名:<input name="username">
            <input type="submit">
        </form>
    </body>
</html>

2. Write the controller method

@RequestMapping("/cn/code")
public void code(String username){
    System.out.println(username);
}

SpringMVC provides a filter for dealing with Chinese garbled characters. Configuring the filter in web.xml can solve the problem of Chinese garbled characters:

<!--SpringMVC中提供的字符编码过滤器,放在所有过滤器的最上方-->
<filter>
    <filter-name>encFilter</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>encFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

SpringMVC handles the response_configuration view resolver

 By default, SpringMVC will jump to the view page after the controller is executed, and the view resolver can find the corresponding view. The previous 404 exception is that the view cannot be found because the view resolver is not configured.

13 view resolvers are provided in SpringMVC to support different view technologies. InternalResourceViewResolver is the default view resolver of SpringMVC, which is used to resolve JSP views.

<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 视图前缀 -->
    <property name="prefix" value="/" />
    <!-- 视图后缀 -->
    <property name="suffix" value=".jsp" />
</bean>

SpringMVC handles the response_return value of the controller method

 We can set the jump view through the return value of the controller method. The controller method supports the following return value types:

The return value is void

At this point, it will jump to the jsp page whose name is prefix + method path name + suffix

1. Write the controller method

// 路径是helloMVC,方法执行完后会跳转到/helloMVC.jsp
@RequestMapping("/helloMVC")
public void helloMVC(){
    System.out.println("hello SpringMVC!");
}

2. Write helloMVC.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>MVC</title>
    </head>
    <body>
        <h1>欢迎来到SpringMVC</h1>
    </body>
</html>

The return value is String 

At this time, it will jump to the jsp page whose name is prefix + return value + suffix

Write the controller method

// 返回值为String
@RequestMapping("/c2/hello1")
public String helloMVC1(){
    System.out.println("hello SpringMVC!");
    // 方法执行完后会跳转到/helloMVC.jsp
    return "helloMVC";
}

The return value is ModelAndView

This is an object provided by SpringMVC, which can set data to the request field and specify the page to jump to. This object contains Model object and View object.

1. Model: Set data to the request field.

2. View: Specify the page to jump to.

 1. Write the controller method

// 返回值为ModelAndView
@RequestMapping("/c2/hello2")
public ModelAndView useMAV(){
    System.out.println("返回值类型为ModelAndView");
    // 1.创建ModelAndView对象
    ModelAndView modelAndView = new ModelAndView();
    // 2.获取Model对象,本质是一个Map
    Map<String, Object> model = modelAndView.getModel();
    // 3.使用Model对象向request域设置数据
    model.put("name","程序员");
    // 4.使用View对象设置跳转的路径为/tong.jsp
    modelAndView.setViewName("baizhan");
    return modelAndView;
}

2. Write jsp pages

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
    <head>
        <title>百千万</title>
    </head>
    <body>
        <h1>你好!${requestScope.name}</h1>
    </body>
</html>

3. Modify the web.xml namespace so that jsp pages support el expressions by default

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                            http://xmlns.jcp.org/xml/ns/javaee/webapp_3_1.xsd"
         version="3.1">
</web-app>

SpringMVC handles response _request field setting data 

 When the return value of the controller is ModelAndView, we can set data to the request field. We also have the following methods to set data to the request field:

Use native HttpServletRequest

@RequestMapping("/c2/hello3")
public String setRequestModel(HttpServletRequest request){
    request.setAttribute("username","面涂学堂");
    return "baizhan";
}

Use Model, ModelMap

SpringMVC provides the Model interface and the ModelMap class. The controller method adds these two types of parameters, uses the parameters to set the data, and the data will be stored in the request field.

@RequestMapping("/c2/hello4")
public String setRequestModel2(Model model, ModelMap modelMap){
    // 使用Model将数据存入request域
    // model.addAttribute("username","辛苦学堂");
    // 使用ModelMap将数据存入request域
    modelMap.addAttribute("username","辛苦学堂");
    return "baizhan";
}

Use the Map collection

The bottom layer of the Model interface is a Map collection. We can set parameters of the Map type for the controller method, add key-value pairs to the Map, and the data will also be stored in the request field.

@RequestMapping("/c2/hello5")
public String setRequestModel3(Map map){
    map.put("username","辛苦学堂");
    return "baizhan";
}

SpringMVC processes response _session domain setting data

 Session scope means that it is valid in the current session. In SpringMVC for

 Session scope pass value can only be realized by using HttpSession object.

1. Write the controller method

@RequestMapping("/c2/hello6")
public String setSeesionModel(HttpSession session){
    session.setAttribute("address","北京");
    return "baizhan";
}

2. Write jsp pages

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
    <head>
        <title>百战不败</title>
    </head>
    <body>
       <h1>你好!${requestScope.name}</h1>
       <h1>地址是!${sessionScope.address}</h1>
    </body>
</html>

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131744994