SpringMVC--请求和响应

上篇SpringMVC--初入SpringMVC中,我们对SpringMVC有了初步的认识,作为开发者,我们日常使用SpringMVC,只需要关注Controller层的业务代码,其余的都由SpringMVC容器帮助处理。

一、@RequestMapping注解

@RequestMapping注解除了用于指定请求的路径,还有以下功能

指定请求方式

注解中指定method参数的值来表示请求的方式:

@RequestMapping(value = "hello2.do",method = RequestMethod.POST)

限制请求参数的条件

注解中指定params参数

// 请求参数必须有name和pwd,并且name不能为空
@RequestMapping(value = "hello2.do", params = {"name!=", "pwd"})

限制请求消息头的条件

注解中指定headers参数

// 请求头的Accept-Encoding必须为gzip, deflate
@RequestMapping(value = "hello2.do", headers = {"Accept-Encoding=gzip, deflate"})

二、接收请求参数

除了支持servlet的方式获取HttpServletRequest,HttpServletResponse,SpringMVC还支持以下方式

1. 直接使用传参接收

controller中定义请求:

@RequestMapping("requestParam1")
    @ResponseBody
    public String requestParam1(String username) {
        System.out.println(username);
        return "success";
    }

@ResponseBody注解表示返回值使用字符串处理,不做视图处理

jsp中定义表单:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
hello2 jsp

<form action="requestParam1">
    <input type="text" name="username">
    <input type="submit" value="提交">
</form>
</body>
</html>

结果:

控制台输出:

2. 使用@RequestParam注解指定参数名

上面默认使用传参的变量名作为接收参数名,还可以通过@RequestParam注解指定参数名

controller代码:

@RequestMapping("requestParam2")
    @ResponseBody
    public String requestParam2(String username, @RequestParam("pwd") String password) {
        System.out.println("username:" + username + "password:" + password);
        return "success";
    }

form表单代码:

<form action="requestParam2">
    username:<input type="text" name="username">
    pwd:<input type="text" name="pwd">
    <input type="submit" value="提交">
</form>
3.实体类接收参数

定义实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private String name;
    private Integer gender;
    private Integer age;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;
}

针对日期格式可以使用@DateTimeFormat注解指定

定义controller中请求:

@RequestMapping("requestParam3")
    @ResponseBody
    public String requestParam3(User user) {
        System.out.println(user.toString());
        return "success";
    }

表单代码:

<form action="requestParam3">
    <p>name:<input type="text" name="name"></p>
    <p>gender:<input type="radio" name="gender" value="0">男  <input type="radio" name="gender" value="1">女</p>
    <p>age:<input type="text" name="age"></p>
    <p>birthday:<input type="text" name="birthday"></p>
    <p><input type="submit" value="提交"></p>
</form>

测试结果:

4. REST风格

需要使用@PathVariable注解指定参数名

@RequestMapping("requestParam4/{id}/{name}")
    @ResponseBody
    public String requestParam4(@PathVariable("id") Integer id, @PathVariable("name") String name) {
        System.out.println("id:" + id.toString() + "name:" + name);
        return "success";
    }

直接浏览器请求:

控制台打印:

三、返回响应

通过之前的使用,我们对SpringMVC请求返回有了一个大致了解,默认需要返回一个字符串,是视图的相对路径,可以通过配置视图解析器的前缀和后缀来简化使用。而争对需要直接返回数据的情况,在方法上加上@ResponseBody注解,接下来来详细使用SpringMVC的请求响应

1. 请求转发

除了使用servlet请求对象进行转发外,SpringMVC还提供了以下几种方式

1.1 forward字符串拼接

返回时,在字符串前面加上"forward:/"前缀

@RequestMapping(value = "helloForward")
    public String forward() {
        return "forward:/hello2";
    }

SpringMVC默认使用的就是这种方式,所以前缀可以省略不加

1.2 使用View对象

我们还可以指定返回为View视图对象,告诉SpringMVC我们返回的是一个视图
转发对应的View实现类为InternalResourceView

@RequestMapping(value = "helloForwardView")
    public View forwardView() {
        View ret = new InternalResourceView("hello2");
        return ret;
    }
1.3 使用ModelAndView对象

ModelAndView既包含了数据,又包含了视图
ModelAndView即支持设置View的方法,也支持设置ViewName的方法

@RequestMapping(value = "helloForwardModelView")
    public ModelAndView forwardModelView() {
        ModelAndView ret = new ModelAndView();
//        ret.setView(new InternalResourceView("hello2"));
        ret.setViewName("hello2");

        return ret;
    }
2. 请求重定向

和转发对应的,重定向也可以使用上面的几种方式

2.1 redirect字符串拼接
@RequestMapping(value = "helloRedirect")
    public String redirect() {
        return "redirect:/hello2";
    }
2.2 使用View对象

重定向使用的实现类为RedirectView

@RequestMapping(value = "helloRedirectView")
    public View redirectView() {
        View ret = new RedirectView("hello2");
        return ret;
    }
2.3 使用ModelAndView对象
@RequestMapping(value = "helloRedirectModelView")
    public ModelAndView redirectModelView() {
        ModelAndView ret = new ModelAndView();
//        ret.setView(new RedirectView("hello2"));
        ret.setViewName("redirect:/hello2");

        return ret;
    }
3. 响应Json

开发中使用最多的方式就是请求返回Json数据,SpringMVC返回Json数据也很简单

3.1 引入jackson依赖
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.1</version>
    </dependency>
3.2 返回Json

会自动的转化成Json数据返回

@RequestMapping(value = "respJson")
    @ResponseBody
    public User respJson() throws JsonProcessingException {
        return new User("张三", 0, 18, new Date());
    }

浏览器直接访问:

3.3 使用ajax获取

导入jquery:

配置静态资源放行:

<?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:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/util
       http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
...

    <!--静态资源放行-->
    <mvc:resources mapping="/js/**" location="/WEB-INF/js/"></mvc:resources>

</beans>

html中增加js方法:

<html>
<head>
    <title>Title</title>
    <script src="js/jquery-1.10.2.min.js"></script>
    <script>
        $(function () {
            $("#btn_json").click(
                function () {
                    $.get("respJson",{name:'小明',age:'20'},function (data) {
                        console.log(data.name)
                        console.log(data.age)
                        console.log(data.gender)
                        console.log(data.birthday)
                    })
                }
            )
        })
    </script>
</head>
<body>
hello2 jsp

<form action="requestParam1">
    <input type="text" name="username">
    <input type="submit" value="提交">
</form>

<form action="requestParam2">
    username:<input type="text" name="username">
    pwd:<input type="text" name="pwd">
    <input type="submit" value="提交">
</form>

<form action="requestParam3" method="post">
    <p>name:<input type="text" name="name"></p>
    <p>gender:<input type="radio" name="gender" value="0">男  <input type="radio" name="gender" value="1">女</p>
    <p>age:<input type="text" name="age"></p>
    <p>birthday:<input type="text" name="birthday"></p>
    <p><input type="submit" value="提交"></p>
</form>

<button id="btn_json">ajax获取json</button>

</body>
</html>

项目地址:

https://gitee.com/aruba/spring-mvcstudy.git

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值