SpringMVC-Controller的返回值

SpringMVC-处理器的返回值

一、ModelAndView

ResultController.java

package com.dapan.controller;

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

@Controller
@RequestMapping("result")
public class ResultController {

    //返回ModelAndView : 返回值既有资源的跳转和数据的携带,可以选择该种方式
    @RequestMapping("test01")
    public ModelAndView test01() {
        ModelAndView mv = new ModelAndView();
        //携带数据
        mv.addObject("stuName", "赵依依"); //相当于request.setAttribute("stuName","赵依依");
        mv.setViewName("result");   //经过视图解析器InternalResourceViewResolver的处理,将逻辑视图名称加上前后缀变为物理资源路径 /result.jsp
        return mv;
    }
}

result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>result</title>
</head>
<body>
<h1>Result---------</h1>
<h3>test01---------${stuName}</h3>
</body>
</html>

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

    <!-- spring配置-->
    <context-param>
        <!--contextConfigLocation:表示用于加载 Bean的配置文件-->
        <param-name>contextConfigLocation</param-name>
        <!--
            指定spring配置文件的位置
            这个配置文件也有一些默认规则,它的配置文件名默认就叫 applicationContext.xml ,
            如果将这个配置文件放在 WEB-INF 目录下,那么这里就可以不用 指定配置文件位置,只需要指定监听器就可以。
            这段配置是 Spring 集成 Web 环境的通用配置;一般用于加载除控制器层的 Bean(如dao、service 等),以便于与其他任何Web框架集成。
        -->
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- springmvc的控制器-->
    <servlet>
        <!--
             前端控制器:所有的请求都会经过此控制器,然后通过此控制器分发到各个分控制器.
             前端控制器本质上还是一个Servlet,因为SpringMVC底层就是使用Servlet编写的
       -->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 创建前端控制器的时候读取springmvc配置文件启动ioc容器 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- Tomcat启动就创建此对象 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- 配置拦截路径url,所有以.do结尾的请求都会被前端控制器拦截处理 -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
<!--    配置中文乱码过滤器-->
    <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>
<!--        设置下面两个属性为true后,即使在控制器中设置了其他编码方式,也会失效,统一按照web.xml的编码方式进行-->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <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>

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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <!--springmvc的配置文件:控制器的bean对象都在这里扫描-->
    <context:component-scan base-package="com.dapan.controller"/>

    <!--    告知处理请求注解-->
    <mvc:annotation-driven/>
    <!--    配置视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

<!--    解决静态资源访问不到 方案一:-->
<!--    <mvc:default-servlet-handler/>-->

    <!--
    方案二:
    location: 表示静态资源所在目录。当然,目录不要使用/WEB-INF/及其子目录。
    mapping: 表示对该资源的请求。注意,后面是两个星号**
    -->
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
</beans>

applicationContext.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
">
    <!--spring的配置文件:除了控制器之外的bean对象都在这里扫描-->
    <context:component-scan base-package="com.dapan.service,com.dapan.dao,com.dapan.entity"/>
</beans>

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.dapan</groupId>
    <artifactId>SpringMVC01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--web项目-->
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <!--spring-webmvc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <!--springmvc底层还是servlet,所以必须添加servlet依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope><!--插件运行的时候没有范围插件启动会失败-->
        </dependency>
        <!--处理json-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 编码和编译和JDK版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>

            <!--tomcat插件-->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                    <port>8080</port>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

运行结果:

在这里插入图片描述

二、String

在ResultController中新增test02方法

//返回字符串
@RequestMapping("test02")
    public String test02(HttpServletRequest request) {
        Student student = new Student();
        student.setStuId(1001);
        student.setStuName("赵依依");
        student.setStuAge(18);
        request.setAttribute("student",student);    //存到request作用域中
        request.getSession().setAttribute("student",student);   //存在session作用域中,虽然同名,但是作用域不同,可以获取对象
        return "result";//经过视图解析器InternalResourceViewResolver的处理,将逻辑视图名称加上前后缀变为物理资源路径 /result.jsp
    }

result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>result</title>
</head>
<body>
<h1>Result---------</h1>
<h3>test01---------${stuName}</h3>
<h3>test02---RequestScope------${requestScope.student.stuId}------${requestScope.student.stuName}----${requestScope.student.stuAge}</h3>
<h3>test02---SessionScope------${sessionScope.student.stuId}------${sessionScope.student.stuName}----${sessionScope.student.stuAge}</h3>
</body>
</html>

运行结果:

在这里插入图片描述

三、返回对象类型

1、直接返回String字符串

在ResultController中新增test031()

 	//返回对象类型:Integer、Double、String、自定义类型、List、Map,
    // 返回的不是逻辑视图,而直接返回数据本身,一般搭配ajax使用,返回的数据是json格式
    //一定要与@ResponseBody一起使用
    @RequestMapping("test03-1")
    @ResponseBody
    public String test031() {
        return "result";
    }

运行结果:

在这里插入图片描述

2、直接返回对象

在ResultController中新增test032()

   @RequestMapping("test03-2")
    @ResponseBody	//一定要加@ResponseBody注解才可以
    public Student test032() {
        Student student = new Student();
        student.setStuId(1002);
        student.setStuName("钱二二");
        student.setStuAge(18);
        return student;
    }

运行结果:

在这里插入图片描述

3、直接返回List集合

在ResultController中新增test033()

 @RequestMapping("test03-3")
    @ResponseBody
    public List<Student> test033() {
        List<Student> studentList = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            Student student = new Student();
            student.setStuId(1000+i);
            student.setStuName("孙珊珊"+i);
            student.setStuAge(18+i);
            studentList.add(student);
        }
        return studentList;
    }

运行结果:

在这里插入图片描述

4、直接返回Map集合

在ResultController中新增test034()

 @RequestMapping("test03-4")
    @ResponseBody
    public Map<String,Student> test034() {
        Map<String, Student> map = new HashMap<>();
        for (int i = 1; i <= 5; i++) {
            Student student = new Student();
            student.setStuId(1000+i);
            student.setStuName("李思思"+i);
            student.setStuAge(18+i);
            student.setRegisterTime(new Date());	//需要在实体类的registerTime属性上加上@JsonFormat(pattern = "yyyy-MM-dd")注解
            map.put(student.getStuId()+"", student);
        }
        return map;
    }

运行结果:

在这里插入图片描述

四、返回void

1、转发

在ResultController中新增test041()

	//没有返回 void 就是原生的servlet使用方式
    //转发 
    @RequestMapping("test04-1")
    public void test041(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/ok.jsp").forward(request,response);	//必须要给全路径,否则会找不到页面
    }

运行结果:

在这里插入图片描述

2、重定向

在ResultController中新增test042()

  //没有返回 void 就是原生的servlet使用方式
    // 重定向
    @RequestMapping("test04-2")
    public void test042(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("/ok.jsp");//必须要给全路径,否则会找不到页面
    }

运行结果:

在这里插入图片描述

3、响应数据

在ResultController中新增test043()

  @RequestMapping("test04-3")
    public void test043(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("返回void类型测试----直接返回字符串");
        writer.flush();
        writer.close();
    }

运行结果:

在这里插入图片描述

以上就是我所学习的处理器返回值的全部内容,欢迎各位大佬批评指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

What大潘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值