SpringMVC中響應數據和結果視圖(完整代碼演示)

代碼目錄結構

在這裏插入圖片描述
User類:

package com.Keafmd.domain;

import java.io.Serializable;

/**
 * Keafmd
 *
 * @ClassName: User
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-30 9:59
 */
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 +
                '}';
    }
}

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.keafmd</groupId>
  <artifactId>springmvc_day02_01_response</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc_day02_01_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.2.6.RELEASE</spring.version>

  </properties>


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

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

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.11.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.11.2</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>



  </dependencies>

  <build>
    <finalName>springmvc_day02_01_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>

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

    <!-- 開啓註解掃描,配置spring創建容器時要掃描的包 -->
    <context:component-scan base-package="com.Keafmd"></context:component-scan>

    <!-- 配置視圖解析器 -->
    <bean id="viewResolver" 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="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />




    <!-- 開啓SpringMVC框架註解支持,註解配置spring開啓註解mvc的支持 -->
    <mvc:annotation-driven/>


</beans>

success.jsp:

<%--
  Created by IntelliJ IDEA.
  User: Keafmd
  Date: 2021/1/30
  Time: 9:40
  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>

    <h1>執行成功</h1>

    ${
   
   user.toString()}

</body>
</html>

返回值分類

字符串

UserController類:

package com.Keafmd.controller;

import com.Keafmd.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-30 9:52
 */
@Controller
@RequestMapping("/user")
public class UserController {
   
   

    /**
     * 返回字符串
     * @param model
     * @return
     */
    @RequestMapping("/testString")
    public String testString(Model model){
   
   

        String clazz = Thread.currentThread().getStackTrace()[1].getClassName();
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("執行了:"+clazz+" - "+method);
        //模擬從數據庫中查詢User對象
        User user = new User();
        user.setUsername("Keafmd");
        user.setPassword("123456");
        user.setAge(21);
        //model對象
        model.addAttribute("user",user);
        return "success";
    }

}

response.jsp:

<%--
  Created by IntelliJ IDEA.
  User: Keafmd
  Date: 2021/1/30
  Time: 9:40
  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>

    <a href="user/testString">testString</a><br/>
    
</body>
</html>

運行效果:

執行了:com.Keafmd.controller.UserController - testString

在這裏插入圖片描述

void

1.如果控制器的方法返回值編寫成void,執行程序報404的異常,默認查找JSP頁面沒有找到,文.件[/WEB-INF/pages/user/testVoid.jsp] 未找到
2.可以使用請求轉發或者重定向跳轉到指定的頁面。

UserController類:

    /**
     * 返回void
     * 請求轉發是一次請求,不用編寫項目的名稱
     * @param
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
   

        String clazz = Thread.currentThread().getStackTrace()[1].getClassName();
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("執行了:"+clazz+" - "+method);
        //文.件[/WEB-INF/pages/user/testVoid.jsp] 未找到

        //編寫請求轉發程序
        //手動轉發不會使用視圖解析器,需要自己寫路徑
        //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        //如果這後面有代碼,還是會繼續執行的,不想執行加上return

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

        //設置中文亂碼
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //直接進行響應
        response.getWriter().println("hello牛哄哄的柯南");

        return;
    }

response.jsp:

<a href="user/testVoid">testVoid</a><br/>

運行效果:

執行了:com.Keafmd.controller.UserController - testVoid

在這裏插入圖片描述

ModelAndView

ModelAndView對象是Spring提供的一個對象,可以用來調整具體的JSP視圖。

UserController類:

    /**
     * 返回 ModelAndView
     * 返回String底層調用的就是ModelAndView
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
   
   
        String clazz = Thread.currentThread().getStackTrace()[1].getClassName();
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("執行了:"+clazz+" - "+method);

        //創建ModelAndView對象
        ModelAndView mv = new ModelAndView();
        //模擬從數據庫中查詢User對象
        User user = new User();
        user.setUsername("小蘭");
        user.setPassword("123456");
        user.setAge(21);
        //把User對象存到mv對象中,也會把user對象存入request對象
        mv.addObject("user",user);
        //跳轉到哪個頁面
        mv.setViewName("success");

        return mv;
    }

response.jsp:

<a href="user/testModelAndView">testModelAndView</a><br/>

運行效果:

執行了:com.Keafmd.controller.UserController - testModelAndView

在這裏插入圖片描述

轉發和重定向

UserController類:

    /**
     * 使用關鍵字進行轉發或重定向
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){
   
   
        String clazz = Thread.currentThread().getStackTrace()[1].getClassName();
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("執行了:"+clazz+" - "+method);

        //請求的轉發
        //return "forward:/WEB-INF/pages/success.jsp";

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

response.jsp:

<a href="user/testForwardOrRedirect">testForwardOrRedirect</a><br/>

運行效果:

執行了:com.Keafmd.controller.UserController - testForwardOrRedirect

在這裏插入圖片描述

ResponseBody響應json數據

json字符串和JavaBean對象互相轉換的過程中,需要使用jackson的jar包:

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.11.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.11.2</version>
    </dependency>

response.jsp:

<%--
  Created by IntelliJ IDEA.
  User: Keafmd
  Date: 2021/1/30
  Time: 9:40
  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.min.js" type="text/javascript"></script>
    <script>
        //頁面加載,綁定頁面單擊事件
        $(function (){
   
   
            $('#btn').click(function (){
   
   
                //alert("hello btn")
                $.ajax({
   
   
                    //編寫json格式。設置屬性和值
                    url:"user/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"username":"Keafmd","password":"666","age":"21"}',
                    dataType:"json",
                    type:"post",
                    success:function (data){
   
   
                        //data指的是服務器端響應的數據,進行解析
                        alert(data);
                        alert(data.username);
                        alert(data.password);
                        alert(data.age);
                    }
                });
            });
        });
    </script>
</head>
<body>

    <button id="btn">發送ajax的請求</button>

</body>
</html>

UserController類:

package com.Keafmd.controller;

import com.Keafmd.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-30 9:52
 */
@Controller
@RequestMapping("/user")
public class UserController {
   
   

    /**
     * 模擬異步請求響應
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
   
   
        String clazz = Thread.currentThread().getStackTrace()[1].getClassName();
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("執行了:"+clazz+" - "+method);
        //客戶端發送ajax請求,傳的是json字符串,後端把json字符串封裝到user對象中
        System.out.println(user);
        //做相應,模擬查詢數據庫
        user.setUsername("小蘭");
        user.setPassword("123");

        return user;
    }

}

運行效果:

執行了:com.Keafmd.controller.UserController - testAjax
User{
   
   username='Keafmd', password='666', age=21}

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

以上就是SpringMVC中響應數據和結果視圖的全部內容。

看完如果對你有幫助,感謝點贊支持!
如果你是電腦端的話,看到右下角的 “一鍵三連” 了嗎,沒錯點它[哈哈]

在這裏插入圖片描述

加油!

共同努力!

Keafmd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章