zoukankan      html  css  js  c++  java
  • SpringMVC02_响应数据和结果视图

    本教程源码请访问:tutorial_demo

    一、环境搭建

    1.1、创建工程

    在idea中从原型创建Maven工程,选择org.apache.maven.archetypes:maven-archetype-webapp,在pom.xml中添加如下的坐标:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <!-- Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <!-- JSP -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</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>
    

    这里注意,由于我们这个是JavaWeb项目,一定要添加Servlet和JSP的坐标。

    1.2、在项目中创建存放源码和配置文件的目录

    在src/main目录下创建java和resources两个目录,java目录用来存放Java源码,resources用来存放配置文件。这样创建的目录是普通目录,编译时不能被正确识别,此时还需要进行如下操作:

    1. 在java目录上右键-->Make Directory as-->Sources root;
    2. 在resources目录上右键-->Make Directory as-->Resources Root;

    以后的教程里面,只要涉及到Maven的Java Web工程,都要这样做。

    1.3、编写SpringMVC的配置文件

    在resources目录下新建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="org.codeaction"></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>
    
        <!--
            配置静态资源不过滤
            location:表示路径
            mapping:表示文件
            **表示该目录下的文件以及子目录文件
         -->
        <mvc:resources location="/css/" mapping="/css/**" />
        <mvc:resources location="/images/" mapping="/images/**" />
        <mvc:resources location="/js/" mapping="/js/**" />
    
        <!-- 配置spring开启注解mvc的支持-->
        <mvc:annotation-driven></mvc:annotation-driven>
    </beans>
    

    1.4、在web.xml中添加配置

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
      <!-- SpringMVC的核心控制器 -->
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置Servlet的初始化参数,读取springmvc的配置文件,创建spring容器 -->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- 配置servlet启动时加载对象 -->
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    
      <!-- 解决POST请求乱码 -->
      <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>
      </filter>
      <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    </web-app>
    

    1.5、增加jquery文件

    在webapp目录下新建js目录,拷贝jquery文件到该目录下。

    二、返回值类型

    这里的返回值类型是指控制器方法的返回值类型。

    2.1、字符串

    Controller方法返回字符串可以指定逻辑视图的名称,根据视图解析器为物理视图的地址。

    2.1.1、编写控制器类

    package org.codeaction.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class ResultController {
        @RequestMapping("/testString")
        public String testString() {
            System.out.println("hello...");
            return "success";
        }
    }
    

    2.1.2、编写相关页面

    index.jsp,在webapp目录下

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <body>
        <p>
            <a href="${pageContext.request.contextPath}/testString">测试返回字符串</a>
        </p>
    </body>
    </html>
    

    这里有一个超链接,用来访问控制器类。

    在WEB-INF目录下创建pages目录,编写success.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
        <head>
            <title>SUCCESS</title>
        </head>
        <body>
            <h1>Success</h1>
        </body>
    </html>
    

    2.1.3、启动tomcat服务器测试

    在idea中配置tomcat服务器,运行。

    在地址栏输入http://localhost:8080/result/index.jsp,点击弹出页面中的超链接,页面显示Success

    2.2、void

    如果控制器的方法返回值编写成void,执行程序报404的异常,默认查找JSP页面没有找到。

    可以通过在控制器方法绑定ServletAPI的方式绑定requestresponse,实现转发、重定向、响应特定数据。

    2.2.1、在控制器类中添加方法

    在ResultController中添加如下的方法

        @RequestMapping("/testVoid")
        public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("void...");
            //1.转发
            //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
            //2.重定向
            //response.sendRedirect(request.getContextPath() + "/testString");
            //3.向浏览器返回数据
            PrintWriter out = response.getWriter();
            out.println("hahahahaha....");
        }
    

    1、2、3是三个功能,测试的时候要分别测试。

    2.2.2、编写相关页面

    在index.jsp中添加如下内容

    <p>
        <a href="${pageContext.request.contextPath}/testVoid">测试返回void</a>
    </p>
    

    2.3、ModelAndView

    ModelAndView是SpringMVC为我们提供的一个对象,该对象可以用作控制器方法的返回值。

    2.3.1、在控制器类中添加方法

    在ResultController中添加如下的方法

    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        //创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
    
        //创建User对象
        User user = new User();
        user.setName("Tom");
        user.setAge(10);
    
        //在request域中存放名为user的对象
        mv.addObject("user", user);
        //设置逻辑视图名称
        mv.setViewName("success");
    
        //返回ModelAndView
        return mv;
    }
    

    注意:这里在ModelAndView中添加的对象是保存在了request域当中。

    2.3.2、修改相关页面

    在index.jsp中添加如下内容

    <p>
        <a href="${pageContext.request.contextPath}/testModelAndView">测试返回ModelAndView</a>
    </p>
    

    在success.jsp中添加如下内容

    <p>name:${requestScope.user.name}</p>
    <p>age:${requestScope.user.age}</p>
    

    2.3.3、启动tomcat服务器测试

    点击超链接,浏览器显示如下

    Success
    name:Tom
    age:10
    

    三、转发和重定向

    目前已知的转发方式:

    • 通过控制器方法绑定ServletAPI的方式绑定request,通过request实现转发;
    • 通过返回ModelAndView,设置View实现转发。

    目前已知的重定向方式:

    • 通过控制器方法绑定ServletAPI的方式绑定response,通过response实现转发。

    除了上面的方式,也可以SpringMVC框架提供的方式进行转发和重定向。

    3.1、转发

    新建控制器类

    package org.codeaction.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class JumpController {
    
        //转发
        @RequestMapping("/testForward")
        public String testForward() {
            System.out.println("testForward...");
            return "forward:/WEB-INF/pages/success.jsp";
        }
    }
    

    通过forward关键字实现转发,由于这里不走视图解析器了,需要写完整的路径。

    3.2、重定向

    在控制器类JumpController中添加如下方法

    //重定向
    @RequestMapping("/testRedirect")
    public String testRedirect() {
        System.out.println("testRedirect");
        return "redirect:/testString";
    }
    

    3.3、修改相关页面

    在index.jsp中添加如下内容

    <p>
    	<a href="${pageContext.request.contextPath}/testForward">测试转发</a>
    </p>
    <p>
    	<a href="${pageContext.request.contextPath}/testRedirect">测试重定向</a>
    </p>
    

    启动tomcat服务器,分别点击两个超链接,实现转发和重定向的功能。

    四、ResponseBody响应JSON数据

    作用:将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据。

    前提:需要在pom.xml中加入jackson的包,我们之前的环境搭建中已经添加了相应坐标。

    4.1、编写控制器类

    package org.codeaction.controller;
    
    import org.codeaction.bean.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class JsonController {
    
        @RequestMapping("/testJSON")
        @ResponseBody
        public User testJSON(@RequestBody User user) {
            System.out.println(user);
            return user;
        }
    }
    

    4.2、修改相关页面

    修改index.jsp,引入jQuery,添加JS代码,如下:

    <script src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
    <script>
        $(function () {
        $("#btn").click(function () {
            $.ajax({
                url: "${pageContext.request.contextPath}/testJSON",
                contentType: "application/json;charset=UTF-8",
                data: '{"name":"Tom","age":20}',
                dataType: "JSON",
                type: "POST",
                success: function(data) {
                    console.log(data);
                }
            });
        });
    });
    </script>
    

    添加触发JS操作的按钮

    <p>
        <button id="btn" type="button">测试返回JSON数据</button>
    </p>
    
  • 相关阅读:
    推荐两个漂亮的编程字体【华为云技术分享】
    【云速建站】几个基本概念和流程解释【华为云技术分享】
    Too many open files的四种解决办法【华为云技术分享】
    基于Docker快速搭建ELK【华为云技术分享】
    重磅!普惠AI--华为云语音语义万次调用1元购,有奖问答@评论区等你来!【华为云技术分享】
    图库网站Unsplash高清原图爬虫【华为云技术分享】
    冒泡的问题及阻止冒泡
    封装可视区域大小的函数
    点击空白处隐藏案例
    计算滚动条的高度
  • 原文地址:https://www.cnblogs.com/codeaction/p/13156780.html
Copyright © 2011-2022 走看看