SpringMVC-2-SpringMVC注解式开发

目录

2.1 @RequestMapping 定义请求规则:GET/POST

2.1.1 指定模块名称

2.1.2 对请求提交方式的定义

2.2 后端处理器方法的参数

2.2.0 HttpServletRequest+HttpServletResponse+HttpSession的使用

2.2.1 逐个参数接收

2.2.2 逐个参数接收的代码演示

2.2.2.1 编写web项目的pom.xml 文件

2.2.2.2 编写web项目的springmvc.xml 文件

2.2.2.3 编写web项目的全局配置文件:web.xml(解决了中文乱码问题)

2.2.2.4 编写一个业务处理的控制器:MyController

2.2.2.5 编写MyController中定位到的视图:some.jsp和other.jsp

2.2.2.6 编写一个前端页面:index.jsp

2.2.2.7 前后端测试

2.2.2.8 最终的项目结构图

2.2.2.9 解决中文乱码问题,直接在web.xml中配置一个字符编码过滤器即可

2.2.3 校正请求参数名 @RequestParam

2.2.4 使用java对象来接收参数

2.2.4.1 定义一个实体类Student

2.2.4.2 编写一个MyController处理器

2.2.4.3 编写前端结果展示页面 receiveObject2.jsp

2.2.4.4 编写前端页面 index.jsp

2.2.4.5 测试结果

2.2.4.6 项目结构

2.3 处理器方法的返回值

2.3.1 返回 ModelAndView

2.3.2 返回 String

2.3.3 返回 void(了解)

2.3.4 返回对象 Object:主要是响应ajax请求的

2.3.5 ==返回单个java对象源代码==

2.3.5.1 编写处理器Controller

2.3.5.2 直接在地址栏中输入URL地址测试

2.3.6 ==返回java对象集合源代码==

2.3.6.1 编写处理器Controller

2.3.6.2 直接在地址栏中输入URL地址测试


2.1 @RequestMapping 定义请求规则:GET/POST

2.1.1 指定模块名称

通过 @RequestMapping 注解可以定义处理器对于请求的映射规则。该注解可以注解在方法上,也可以注解在类上,但意义是不同的。value 属性值常 以 “ / ” 开始。

@RequestMapping 的 value 属性用于定义所匹配请求的 URI。但对于注解在方法上与类上,其 value 属性所指定的 URI,意义是不同的。

一个@Controller 所注解的类中,可以定义多个处理器方法。当然,不同的处理器方法所匹配的 URI 是不同的。这些不同的 URI 被指定在注解于方法之上的@RequestMapping 的 value 属性中。但若这些请求具有相同的 URI 部分,则这些相同的 URI,可以被抽取到注解在类之上的@RequestMapping 的 value 属性中。此时的这个 URI 表示模块的名称。URI 的请求是相对于 Web 的根目录。

换个角度说,要访问处理器的指定方法,必须要在方法指定 URI 之前加上处理器类前定义的模块名称。

项目:spriingmvc-web。在 spriingmvc-web 基础上进行修改。

Step1:修改处理器类 MyController。

Step2:添加视图页面:在 /WEB-INF/jsp 目录下添加 some.jsp 与 other.jsp 页面。

2.1.2 对请求提交方式的定义

对于 @RequestMapping,其有一个属性 method,用于对被注解方法所处理请求的提交方式进行限制,即只有满足该 method 属性指定的提交方式的请求,才会执行该被注解方法。

Method 属性的取值为 RequestMethod 枚举常量。常用的为 RequestMethod.GET 与 RequestMethod.POST,分别表示提交方式的匹配 规则为 GET 与 POST 提交。

以上处理器方法只能处理 POST 方式提交的请求。客户端浏览器常用的请求方式,及其提交方式有以下几种:

也就是说,只要指定了处理器方法匹配的请求提交方式为 POST,则相当于指定了请求发送的方式:要么使用表单请求,要么使用 AJAX 请求,其它请求方式被禁用。

当然,若不指定 method 属性,则无论是 GET 还是 POST 提交方式,均可匹配,也即对于请求的提交方式无要求。

项目:spriingmvc-web。在 spriingmvc-web 基础上进行修改。

Step1:修改处理器类 MyController。

Step2:修改 index 页面。

2.2 后端处理器方法的参数

后端处理器方法可以包含以下四大类参数,这些参数会在系统调用时由系统自动赋值,即程序员可在方法内直接使用。

(1)HttpServletRequest:HttpServletRequest request

(2)HttpServletResponse:HttpServletResponse response

(3)HttpSession:HttpSession session

(4)请求中所携带的其他请求参数

2.2.0 HttpServletRequest+HttpServletResponse+HttpSession的使用

2.2.1 逐个参数接收

只要保证【请求参数名】与【该请求处理方法的参数名】相同即可。

项目:spriingmvc-web。在 spriingmvc-web 基础上进行修改。

Step1:修改 index 页面

Step2:修改处理器类 MyController

Step3:添加 show 页面:在/WEB-INF/jsp 下添加 show.jsp 页面。

2.2.2 逐个参数接收的代码演示

2.2.2.1 编写web项目的pom.xml 文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wind</groupId>
    <artifactId>springmvc-web2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <!--注册站点用,默认生成的,暂时用不到-->
    <name>springmvc-web Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!--添加servlet依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!--添加SpringMVC依赖,会自动把里面整合的Spring依赖添加进来-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>springmvc-web</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>

                <!-- 编码和编译和JDK版本 -->
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>${maven.compiler.source}</source>
                        <target>${maven.compiler.target}</target>
                    </configuration>
                </plugin>

                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

2.2.2.2 编写web项目的springmvc.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd">

    <!--声名组件扫描器-->
    <context:component-scan base-package="com.wind"/>

    <!--视图解析器:添加前缀和后缀。
    SpringMVC框架为了避免对于请求资源路径与扩展名上的冗余,在视图解析器 InternalResouceViewResolver
    中引入了请求的前辍与后辍。而 ModelAndView 中只需给出要跳转页面的文件名即可,对于具体的文件路径与文件扩展名,
    视图解析器会自动完成拼接。-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--视图文件的路径-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--视图文件的扩展名-->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

2.2.2.3 编写web项目的全局配置文件:web.xml(解决了中文乱码问题)

<?xml version="1.0" encoding="UTF-8"?>
<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/web-app_4_0.xsd"
         version="4.0">


    <!--
    注册SpringMVC的核心对象DispatcherServlet,需要在Tomcat服务器启动的时候创建一个DispatcherServlet实例对象。
    为什么要创建DispatcherServlet对象实例呢?
    因为在创建DispatcherServlet对象实例的时候,会创建SpringMVC容器对象,也即会读取SpringMVC的配置文件,把这个配置文件
    中声名的bean对象都创建好,这样的话,当用户发起请求时就可以直接这些对象来处理ajax请求了。
    servlet的初始化方法init(),DispatcherServlet对象的创建在这个init方法中:
    {
    //读取配置文件,创建SpringMVC的Web容器
    WebApplicationContext ctx = new ClassPathXmlApplicationContext("springmvc.xml");
    //把容器对象放到ServletContext对象中
    getServletContext().setAttribute("key", ctx);
    }
    测试:启动Tomcat的时候报了一个错:Could not open ServletContext resource [/WEB-INF/springMVC-servlet.xml]
    -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--自定义SpringMVC读取的配置文件:
        (1)contextConfigLocation:SpringMVC配置文件位置的属性
        (2)classpath:指定SpringMVC配置文件的位置
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--Tomcat服务器启动后,就开始创建该SpringMVC容器对象。值是一个大于等于的0的整数,值越小,说明被创建的时间越早。-->
        <load-on-startup>1</load-on-startup>
    </servlet>


    <!--解释url-pattern:
    在使用框架的时候,url-pattern可以有两种取值:
    (1)使用扩展名的方式,语法:*.xxx,其中的xxx是自定义的扩展名,比如:*.action,*.do,*.mvc
        此时针对它们有效:
        http://localhost:8008/springmvc-web/*.do
        http://localhost:8008/springmvc-web/*.action
        http://localhost:8008/springmvc-web/*.mvc
    (2)使用斜杠 / :代表所有类型的路由类型
    -->
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--为解决POST请求中的中文乱码问题,设置项目中的编码方式是UTF-8,使用框架自带的过滤器即可-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--设置编码是UTF-8-->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <!--设置请求对象HttpServletRequest使用encoding的编码方式-->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--设置应答对象HttpServletResponse使用encoding的编码方式-->
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--表示所有的请求都先经过过滤处理一下,然后再执行后面的业务逻辑-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

2.2.2.4 编写一个业务处理的控制器:MyController

package com.wind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(value = "/controller")
public class MyController {
    
    @RequestMapping(value = "/some.do", method = RequestMethod.POST)
    public ModelAndView doSome(String name, Integer age) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("myname", name);
        modelAndView.addObject("myage", age);
        modelAndView.setViewName("show");
        return modelAndView;
    }

    @RequestMapping(value = "/other.do", method = RequestMethod.GET)
    public ModelAndView doOther() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", "使用注解的SpringMVC应用项目");
        modelAndView.addObject("fun", "doOther处理器");
        modelAndView.setViewName("other");
        return modelAndView;
    }

}

2.2.2.5 编写MyController中定位到的视图:some.jsp和other.jsp

(1)come.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>/WEB-INF/jsp/show.jsp从request作用域中myController控制器获取的处理结果:POST</h3>
<h3>name数据是:${myname}</h3>
<h3>age数据是:${myage}</h3>
</body>
</html>

(2)other.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>/WEB-INF/jsp/other.jsp从request作用域中myController控制器获取的处理结果:GET</h3>
<h3>msg数据是:${msg}</h3>
<h3>fun数据是:${fun}</h3>
</body>
</html>

2.2.2.6 编写一个前端页面:index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<base href="http://localhost:8080/springmvc-web2/">
<body>
<p>第一个SpringMVC项目</p><br/>
<p>
<form action="controller/some.do" method="post">
    姓名:<input type="text" name="name"/><br/>
    年龄:<input type="text" name="age"/> <br/>
    <input type="submit" name="注册"/><br/>
</form>
<br/>
</p>

<p>
    <a href="controller/other.do">发起一个other.do的请求:GET</a>
    <br/>
</p>
</body>
</html>

2.2.2.7 前后端测试

2.2.2.8 最终的项目结构图

2.2.2.9 解决中文乱码问题,直接在web.xml中配置一个字符编码过滤器即可

对于前面所接收的请求参数,若含有中文,则会出现中文乱码问题。 Spring 对于请求参数中的中文乱码问题,

给出了专门的字符集过滤器: spring-web-5.2.5.RELEASE.jar 的 org.springframework.web.filter 包下的 CharacterEncodingFilter 类

在 web.xml 中注册字符集过滤器,即可解决 Spring 的请求参数的中文乱码问题。不过,最好将该过滤器注册在其它过滤器之前。因为过滤器的执行是 按照其注册顺序进行的。

比如:在项目中,web.xml 文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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/web-app_4_0.xsd"
         version="4.0">


    <!--
    注册SpringMVC的核心对象DispatcherServlet,需要在Tomcat服务器启动的时候创建一个DispatcherServlet实例对象。
    为什么要创建DispatcherServlet对象实例呢?
    因为在创建DispatcherServlet对象实例的时候,会创建SpringMVC容器对象,也即会读取SpringMVC的配置文件,把这个配置文件
    中声名的bean对象都创建好,这样的话,当用户发起请求时就可以直接这些对象来处理ajax请求了。
    servlet的初始化方法init(),DispatcherServlet对象的创建在这个init方法中:
    {
    //读取配置文件,创建SpringMVC的Web容器
    WebApplicationContext ctx = new ClassPathXmlApplicationContext("springmvc.xml");
    //把容器对象放到ServletContext对象中
    getServletContext().setAttribute("key", ctx);
    }
    测试:启动Tomcat的时候报了一个错:Could not open ServletContext resource [/WEB-INF/springMVC-servlet.xml]
    -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--自定义SpringMVC读取的配置文件:
        (1)contextConfigLocation:SpringMVC配置文件位置的属性
        (2)classpath:指定SpringMVC配置文件的位置
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--Tomcat服务器启动后,就开始创建该SpringMVC容器对象。值是一个大于等于的0的整数,值越小,说明被创建的时间越早。-->
        <load-on-startup>1</load-on-startup>
    </servlet>


    <!--解释url-pattern:
    在使用框架的时候,url-pattern可以有两种取值:
    (1)使用扩展名的方式,语法:*.xxx,其中的xxx是自定义的扩展名,比如:*.action,*.do,*.mvc
        此时针对它们有效:
        http://localhost:8008/springmvc-web/*.do
        http://localhost:8008/springmvc-web/*.action
        http://localhost:8008/springmvc-web/*.mvc
    (2)使用斜杠 / :代表所有类型的路由类型
    -->
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--为解决POST请求中的中文乱码问题,设置项目中的编码方式是UTF-8,使用框架自带的过滤器即可-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--设置编码是UTF-8-->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <!--设置请求对象HttpServletRequest使用encoding的编码方式-->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--设置应答对象HttpServletResponse使用encoding的编码方式-->
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--表示所有的请求都先经过过滤处理一下,然后再执行后面的业务逻辑-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

2.2.3 校正请求参数名 @RequestParam

所谓校正请求参数名,是指若请求 URL 所携带的参数名称与处理方法中指定的参数名不相同时,则需在处理方法参数前,

添加一个注解 @RequestParam(“请求参数名”),指定请求 URL 所携带参数的名称。该注解是对处理器方法参数进行修饰的,value 属性指定请求参数的名称。

Step1:修改 index 页面 将表单中的参数名称修改的与原来不一样。

Step2:修改处理器类 MyController

注意:required 属性:

2.2.4 使用java对象来接收参数

将处理器方法的参数定义为一个对象,只要保证请求参数名与这个对象的属性同名即可。

2.2.4.1 定义一个实体类Student

package com.wind.vo;

import java.io.Serializable;
public class Student implements Serializable {
    private static final long serialVersionUID = 4580308019312269782L;
    /**
     * 注意:使用该对象来接收前端请求的参数,属性名称需要和前端请求参数保持一致
     */
    private String name;
    private Integer age;

    public Student() {
        System.out.println("Student的无参构造done...");
    }
    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        System.out.println("Student的setName()done...");
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        System.out.println("Student的setAge()done...");
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2.2.4.2 编写一个MyController处理器

package com.wind.controller;

import com.wind.vo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/controller")
public class MyController {

    @RequestMapping(value = "/receiveObject.do", method = RequestMethod.POST)
    public ModelAndView receiveObject(Student student) {
        ModelAndView modelAndView = new ModelAndView();
        if (student != null) {
            modelAndView.addObject("myname", student.getName());
            modelAndView.addObject("myage", student.getAge());
            modelAndView.addObject("mystudent", student.toString());
            modelAndView.setViewName("receiveObject2");
        }
        return modelAndView;
    }
}

2.2.4.3 编写前端结果展示页面 receiveObject2.jsp

<%--
  Created by IntelliJ IDEA.
  Date: 2021/1/1
  Time: 12:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>/WEB-INF/jsp/receiveObject2.jsp从request作用域中myController控制器获取的处理结果:POST</h3>
<h3>name数据是:${myname}</h3>
<h3>age数据是:${myage}</h3>
<h3>student数据是:${mystudent}</h3>
</body>
</html>

2.2.4.4 编写前端页面 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<base href="http://localhost:8080/springmvc-web2/">
<body>
<p>第一个SpringMVC项目</p><br/>

<p>POST请求测试:使用java对象来接受参数<br/>
<form action="controller/receiveObject.do" method="post">
    姓名:<input type="text" name="name"/><br/>
    年龄:<input type="text" name="age"/> <br/>
    <input type="submit" name="注册"/><br/>
</form>
</p><br/>

</body>
</html>

2.2.4.5 测试结果

2.2.4.6 项目结构

2.3 处理器方法的返回值

使用@Controller 注解的处理器的处理器方法,其返回值常用的有四种类型:

(1)第一种:ModelAndView

(2)第二种:String

(3)第三种:无返回值 void

(4)第四种:返回自定义类型对象 根据不同的情况,使用不同的返回值。

2.3.1 返回 ModelAndView

若处理器方法处理完后,需要跳转到其它资源,且又要在跳转的资源间传递数据,此时处理器方法返回 ModelAndView 比较好。当然,若要返回 ModelAndView,则处理器方法中需要定义 ModelAndView 对象。在使用时,若该处理器方法只是进行跳转而不传递数据,或只是传递数据 而并不向任何资源跳转(如对页面的 Ajax 异步响应),此时若返回 ModelAndView,则将总是有一部分多余:要么 Model 多余,要么 View 多 余。即此时返回 ModelAndView 将不合适。

2.3.2 返回 String

处理器方法返回的字符串可以指定内部资源的逻辑视图名,通过视图解析器解析可以将其转换为物理视图地址。

若要跳转的资源为内部资源,则视图解析器可以使用 InternalResourceViewResolver 内部资源视图解析器。此时处理器方法返回的 字符串就是要跳转页面的文件名去掉文件扩展名后的部分。这个字符串与视图 解析器中的 prefix、suffix 相结合,即可形成要访问的 URI。

2.3.3 返回 void(了解)

对于处理器方法返回 void 的应用场景,AJAX 响应。若处理器对请求处理后,无需跳转到其它任何资源,此时可以让处理器方法返回 void。例如,对于 AJAX 的异步请求的响应。

2.3.4 返回对象 Object:主要是响应ajax请求的

(1)步骤:

(2)加入注解驱动前后的区别:

2.3.5 ==返回单个java对象源代码==

2.3.5.1 编写处理器Controller

package com.wind.controller;

import com.wind.vo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/controller")
public class MyController {

    @ResponseBody
    @RequestMapping(value = "/returnStudentToJson.do", method = RequestMethod.GET)
    public Student returnStudentToJson(@RequestParam(value = "name", required = false) String name,
                                       @RequestParam(value = "age", required = false) Integer age) {
        Student student = new Student();
        student.setName("默认是名称是风暴");
        if (name != null) {
            student.setName(name);
        }
        student.setAge(11);
        if (age != null) {
            student.setAge(age);
        }
        System.out.println(student.toString());
        return student;
    }
}

2.3.5.2 直接在地址栏中输入URL地址测试

2.3.6 ==返回java对象集合源代码==

2.3.6.1 编写处理器Controller

package com.wind.controller;

import com.wind.vo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/controller")
public class MyController {

    @ResponseBody
    @RequestMapping(value = "/returnStudentListToJson.do", method = RequestMethod.GET)
    public List<Student> returnStudentListToJson() {
        List<Student> students = new ArrayList<>();
        Student student1 = new Student("默认是名称是风暴", 1);
        students.add(student1);
        Student student2 = new Student("默认是名称是风暴2", 2);
        students.add(student2);
        return students;
    }
}

2.3.6.2 直接在地址栏中输入URL地址测试

注:快捷键:

(1)查看一个类的方法:command+7

(2)查看一个类实现类:fn+control+H

猜你喜欢

转载自blog.csdn.net/cmm0401/article/details/112060771
今日推荐