SpringMVC-返回值

一、普通文本、HTML返回值

// 普通文本
@Controller
public class UserController {
    @RequestMapping(value = "/plainText", produces = "text/plain; charset=UTF-8")
    @ResponseBody
    public String plainText() {
        return "This is 普通文本";
    }
}

// HTML
@RequestMapping(value = "/html", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String html() {
        return "<h1>This is 普通文本</h1>";
    }

二、XML返回值(有两种方式)

  • 手动拼接xml格式,繁琐易错
  // 方法1
    @RequestMapping(value = "/xml1", produces = "application/xml; charset=UTF-8")
    @ResponseBody
    public String xml1() {
        Person person = new Person();
        person.setName("Tom");
        person.setAge(20);

        Car car = new Car();
        car.setName("BWM");
        car.setPrice(1234);
        person.setCar(car);
        // 加上xml的识别
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<person name=\"" + person.getName() + "\" age = \"" + person.getAge() + "\">"
                + "<car name=\"" + car.getName() + "\" age = \"" + car.getPrice() + "\"/>"
                +"</person>";
    }

  • 引入三方库进行返回如下:
 <!--模型转XML的库-->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.4.0-b180830.0359</version>
        </dependency>

        <dependency>
            <groupId>javax.xml</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.1</version>
        </dependency>

配置文件设置

  <contexg:component-scan base-package="com.mj"/>
    <mvc:annotation-driven/>

类需要加上xml的注解

package com.mj.domain;

import com.sun.xml.txw2.annotation.XmlElement;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "person")
public class Person {
    private String name;
    private Integer age;
    private Car car;

    @XmlAttribute
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @XmlAttribute
    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @XmlElement
    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }
}

测试类:

    // 方法2
    @RequestMapping(value = "/xml2")
    @ResponseBody
    public Person xml2() {
        Person person = new Person();
        person.setName("Tom");
        person.setAge(20);

        Car car = new Car();
        car.setName("BWM");
        car.setPrice(1234);
        person.setCar(car);
        // 加上xml的识别
        return person;
    }

三、JSON数据格式返回(两种方式)

  • 直接手拼JSON字符串,如下
  @RequestMapping(value = "/json1", produces = "application/json; charset=UTF-8")
    @ResponseBody
    public String json1() {
        return "{\"name\":\"\"Jack, \"age\":20},\"car:{\"name\":\"BWM\",\"price\":1234}}\"";
    }
  • 引入三方库,如下配置
    <!-- Model转JSON字符串 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.2</version>
        </dependency>

配置文件

<?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:contexg="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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <contexg:component-scan base-package="com.mj"/>
    <mvc:annotation-driven>
        <!--处理服务器返回的中文乱码问题-->
        <mvc:message-converters>
            <!--影响返回值是String的内容-->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
            </bean>

            <!--影响返回值是Model对象(最后通过JAXB转成XML字符串)-->
            <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
            </bean>
            
            <!--影响返回值是Model对象(最后通过Jackson转成JSON字符串)-->
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--默认的转发方式-->
    <mvc:default-servlet-handler/>

</beans>

测试类:

 @RequestMapping("/json2")
    @ResponseBody // 默认返回JSON
    public Student json2() {

        List<String> list = new ArrayList<String>();
        list.add("haha1");
        list.add("haha2");
        list.add("haha3");
        Student student = new Student();
        student.setName("xiaomage");
        student.setNickNames(list);
        student.setAge(12);

        Dog dog = new Dog();
        dog.setName("haha");
        dog.setPrice(123);
        student.setDog(dog);

        return student;
    }

 四、返回视图

  • 可以利用ModelAndView将数据和视图绑定到一起,返回给客户端
    /*
     在Java代码中,路径问题总结
     1、假设请求路径是:"http://IP地址:端口/context_path/path1/path2/path3"
     2、假设转发路径是:"/page/test.jsp"
       1> 以斜线(/)开头,参考路径是context_path
       2> 最终转发路径是:"http://IP地址:端口/context_path" + "/page/test.jsp"
     3、假设转发路径是:"page/test.jsp"
       1> 不以斜线开头,参考路径是当前请求路径的上一层路径
       2> 最终转发路径是:"http://IP地址:端口/context_path/path1/path2" + "/page/test.jsp"
       
       
      在jsp、html代码中、路径问题总结
       1、假设请求路径是:"http://IP地址:端口/context_path/path1/path2/path3"
       2、假设跳转路径是:"/page/test.jsp"
            1> 以斜线(/)开头,参考路径是"http://IP地址:端口"
            2> 最终转发路径是:"http://IP地址:端口" + "/page/test.jsp"
       3、假设转发路径是:"page/test.jsp"
            1> 不以斜线开头,参考路径是当前请求路径的上一层路径
            2> 最终转发路径是:"http://IP地址:端口/context_path/path1/path2" + "/page/test.jsp"
    */
    
@Controller
public class JspController {

    @RequestMapping("/path1/jsp1")
    public ModelAndView jsp1() {
        ModelAndView mv = new ModelAndView();
        Dog dog = new Dog();
        dog.setName("大黄");
        dog.setPrice(200);
        // 本质就是request.setAttribute
        mv.addObject(dog);
        // 转发
        mv.setViewName("/page/jsp1.jsp");
        return mv;
    }
}

/*
 在Java代码中,路径问题总结
 1、假设请求路径是:"http://IP地址:端口/context_path/path1/path2/path3"
 2、假设转发路径是:"/page/test.jsp"
   1> 以斜线(/)开头,参考路径是context_path
   2> 最终转发路径是:"http://IP地址:端口/context_path" + "/page/test.jsp"
 3、假设转发路径是:"page/test.jsp"
   1> 不以斜线开头,参考路径是当前请求路径的上一层路径
   2> 最终转发路径是:"http://IP地址:端口/context_path/path1/path2" + "/page/test.jsp"
   
   
  在jsp、html代码中、路径问题总结
   1、假设请求路径是:"http://IP地址:端口/context_path/path1/path2/path3"
   2、假设跳转路径是:"/page/test.jsp"
        1> 以斜线(/)开头,参考路径是"http://IP地址:端口"
        2> 最终转发路径是:"http://IP地址:端口" + "/page/test.jsp"
   3、假设转发路径是:"page/test.jsp"
        1> 不以斜线开头,参考路径是当前请求路径的上一层路径
        2> 最终转发路径是:"http://IP地址:端口/context_path/path1/path2" + "/page/test.jsp"
*/

  • 不加@ResponseBody的String返回值,也代表viewName

de34e016335d4adab60695044ddaba19.png

  • 在viewName前面加上"redirect:"表示重定向,比如:"redirect:/page/jsp4.jsp"
  •  
  • 可以使用<mvc:view_controller>直接配置请求路径和viewName,如果以下两个都存在,会以java代码优先级高。也就是当没有Controller去处理这个path时才会交给配置文件。
 <mvc:view-controller path="/jsp5" view-name="/WEB-INF/page/jsp5.jsp"/>
 @RequestMapping("/jsp5")
    public String jsp5() {
        // 转发
        return "/WEB-INF/page/jsp4.jsp";
    }

可以通过InternalResourceViewResolver设置试图路径的公共前缀、后缀,受InternalResourceViewResolver影响的有如下:

  • 通过返回值ModelAndView设置viewName
  • 通过返回值String设置的viewName
  • 通过<mvc:view-controller>设置的viewName

可以配置多个InternalResourceViewResolver

  • order值越小,优先级越高

0c2d5af16cd04707a40654b2285ba225.png

@Controller
@RequestMapping("/test")
public class Jsp2Controller {

    @RequestMapping("/jsp1")
    public String jsp1() {
        return "jsp1";
    }


    @RequestMapping("/jsp2")
    public ModelAndView jsp2() {
        return new ModelAndView("jsp2");
    }

}

以下两种情况不受InternalResourceViewResolver影响:

  • 在viewName前面加上"forward:"活"redirect:"
  • 通过ModeAndView的setView方法

b3938407eb8e4b269fe875ee875caac2.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

RiversTree

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

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

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

打赏作者

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

抵扣说明:

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

余额充值