SpringMVC响应数据和结果视图

本文介绍在Spring MVC框架中,如何通过不同类型的响应方法处理客户端请求,包括返回字符串、void、ModelAndView类型,以及使用forward和redirect进行页面跳转,同时展示了如何通过AJAX实现异步请求响应。
摘要由CSDN通过智能技术生成

IDEA中创建maven项目,选择webapp骨架

整体构架

在这里插入图片描述

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.uek</groupId>
  <artifactId>springmvc02-study01-response</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc02-study01-response 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>
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <!--JSON相关的jar-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>

      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
        <version>2.9.0</version>
      </dependency>
  </dependencies>

  <build>
    <finalName>springmvc02-study01-response</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <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>

entity

public class User implements Serializable {

    private String username;
    private String password;
    private Integer age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

controller

@Controller
@RequestMapping("/user")
public class UserController {

    //响应之返回值是String类型
    @RequestMapping("/testString")
    public String testString(Model model){
        System.out.println("testString方法执行了...");
        //模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("张三");
        user.setPassword("123456");
        user.setAge(20);
        model.addAttribute("user",user);
        return "success";
    }

    /**
     * 响应只返回值是void类型
     * 请求转发一次请求,不用编写项目名称
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("testVoid方法执行了...");
        //编写请求转发的程序
      //  request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);

        //重定向
       // response.sendRedirect(request.getContextPath()+"/index.jsp");

        //设置中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //直接会进行响应
        response.getWriter().print("你好");
        return;
    }

    /**
     * 响应只返回值是ModelAndView类型
     */
    @RequestMapping("/testModelAndView")
     public ModelAndView testModelAndView(){
        ModelAndView mv = new ModelAndView();
        System.out.println("testModelAndView方法执行了...");
        //模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("李四");
        user.setPassword("123456");
        user.setAge(23);

        //把User对象存储到mv对象中,也会把user对象存入到request对象中
        mv.addObject("user",user);

        //跳转到哪个页面
        mv.setViewName("success");
        return mv;
     }

    /**
     * 响应之使用forward和redirect进行页面跳转
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){
        System.out.println("testForwardOrRedirect方法执行了...");

        //请求的转发
        //return "forward:/WEB-INF/pages/success.jsp";

        //重定向
        return "redirect:/index.jsp";
    }

    /**
     * 模拟异步请求响应
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax方法执行了...");
        //客户端发送ajax请求,传的是json字符串,后端把json字符串封装到user对象中
        System.out.println(user);
        //做响应,模拟查询数据库
        user.setUsername("haha");
        user.setAge(20);
        //做响应
        return user;
    }
}

spirngmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解的扫描-->
    <context:component-scan base-package="com.uek"></context:component-scan>

    <!--视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--告诉前端控制器,哪些静态资源不拦截-->
    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>

    <!--开启SpringMVC框架注解的支持-->
    <mvc:annotation-driven ></mvc:annotation-driven>

</beans>

response.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020-01-31
  Time: 22:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-1.9.1.min.js"></script>

    <script>
        //页面加载,绑定单击事件
        $(function(){
           $("#btn").click(function () {
             // alert("hello btn");
               //发送ajax请求
               $.ajax({
                   //编写json格式,设置属性和值
                   url:"user/testAjax",
                   contentType:"application/json;charset=UTF-8",
                   data:'{"username":"hehe","password":"123","age":30}',
                   dataType:"json",
                   type:"post",
                   success:function (data) {
                       //data:服务器端响应的json数据,进行解析
                        alert(data);
                        alert(data.username);
                        alert(data.password);
                        alert(data.age);
                   }
               });
           });
        });
    </script>
</head>
<body>

    <%--返回字符串类型--%>
    <a href="user/testString">testString</a>

    <br/>

    <%--返回值是void类型--%>
    <a href="user/testVoid">testVoid</a>

    <br/>

    <%--返回值是ModelAndView类型--%>
    <a href="user/testModelAndView">testModelAndView</a>

    <br/>
    <%--使用forward和redirect进行页面跳转--%>
    <a href="user/testForwardOrRedirect">testForwardOrRedirect</a>

    <br/>

    <%--响应json数据之过滤静态资源--%>
    <button id="btn">发送ajax的请求</button>
</body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020-01-30
  Time: 20:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>执行成功</h3>
    ${user.username}
    ${user.password}
    ${user.age}
</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值