JAVA编程122——SpringMVC返回值类型控制/跳转方式/JSON响应

一、目录结构

在这里插入图片描述

二、SpringMVC返回值类型控制/跳转方式/JSON响应

1.创建UserController.java

package com.mollen.controller;

import com.mollen.bean.User;
import com.sun.deploy.net.HttpResponse;
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;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName: HelloController
 * @Auther:     Mollen
 * @CreateTime: 2018-11-09  14:49:58
 * @Description:
 */

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

    /******************************【返回值类型控制】**************************************

    /**
     *
     * 1.返回值为字符串:
     *      视图解析器解析为jsp物理路径:/WEB-INF/pages/success.jsp
     */
    @RequestMapping("respStr1")
    public String respStr1(User user, HttpSession session){
        session.setAttribute("login",user);
        return "success";
    }

    /**
     *
     * 2.使用request转发页面
     */
    @RequestMapping("respStr2")
    public void respStr2(User user, HttpServletRequest  request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("login",user);
        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
    }

    /**
     * 3.使用response重定向页面
     */
    @RequestMapping("/respStr3")
    public void respStr3(User user,  HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

    /**
     * 4.使用response响应json结果
     */
    @RequestMapping("/respStr4")
    public void respStr4(User user,  HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //乱码处理
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        response.getWriter().write("jsonData");
    }

    /**
     * 5.返回ModelAndView
     */
    @RequestMapping("/mv")
    public ModelAndView mv(User user) throws ServletException, IOException {
        ModelAndView mv = new ModelAndView();
        //将数据保存到Model中
        mv.addObject("logined", user);
        //设置视图名称
        mv.setViewName("success");
        return mv;
    }


    /******************************【页面跳转方式控制】**************************************/

    /**
     * 1.转发:forward
     */
     @RequestMapping("/forward")
     public String forward(User user,HttpSession session) throws ServletException, IOException {
         session.setAttribute("logined", user);
         return "forward:/WEB-INF/pages/success.jsp";
     }


    /**
     * 2.重定向:redirect
     */
    @RequestMapping("/redirect")
    public String redirect(User user,HttpSession session) throws ServletException, IOException {
        session.setAttribute("logined", user);
        return "redirect:/index.jsp";
    }


    /******************************【响应JSON数据格式】**************************************/

    /**
     * 1.接受请求/使用@RequestBody必须是post请求
     * @return
     */
    @RequestMapping(path="/json1")
    public @ResponseBody User  json(@RequestBody User user) {
        System.out.println(user);
        return user;
    }

}

2.创建response.jsp测试json响应

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

</head>
<body>

<a href="/user/json" >testJson</a>
<br>
<button id="btn">发送ajax的请求</button>

</body>
</html>

3.web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <!--配置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>

    <!--以下资源不拦截-->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</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>
    </filter>

    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

4.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.mollen</groupId>
    <artifactId>springmvc_exam</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-api</artifactId>
            <version>9.0.10</version>
            <scope>provided</scope>
        </dependency>

        <!--json解析依赖-->
        <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>
        
    </dependencies>


</project>

5.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.mollen"></context:component-scan>

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

    <!--配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为5MB -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>

    <!--配置spring开启注解mvc的支持-->
    <mvc:annotation-driven></mvc:annotation-driven>

</beans>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值