spring—SpringMVC的请求和响应

SpringMVC的数据响应-数据响应方式

  1. 页面跳转

直接返回字符串

   @RequestMapping(value = {"/qq"},method = {RequestMethod.GET},params = {"name"})
    public  String method()
    {
     System.out.println("controller");
     return "success";
    }
    <bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="suffix" value=".jsp"/>
        <property name="prefix" value="/WEB-INF/"/>
    </bean>

通过ModelAndView对象返回

    @RequestMapping(value = {"/qq2"})
    public  ModelAndView method2(ModelAndView modelAndView)
    {
       modelAndView.addObject("name","ccc");
       modelAndView.setViewName("success");
        return modelAndView;
    }
    @RequestMapping(value = {"/qq3"})
    public  String method3(Model model)
    {
        model.addAttribute("name","kkk");

        return "success";
    }

2) 回写数据

直接返回字符串

返回对象或集合

SpringMVC的数据响应-回写数据-返回对象或集合

在方法上添加@ResponseBody就可以返回json格式的字符串,但是这样配置比较麻烦,配置的代码比较多,因此,我们可以使用mvc的注解驱动代替上述配置

<mvc:annotation-driven/>

在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。

使用<mvc:annotation-driven />自动加载 RequestMappingHandlerMapping(处理映射器)和

RequestMappingHandlerAdapter( 处 理 适 配 器 ),可用在Spring-xml.xml配置文件中使用

<mvc:annotation-driven />替代注解处理器和适配器的配置。

同时使用<mvc:annotation-driven />

默认底层就会集成jackson进行对象或集合的json格式字符串的转换

<?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:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <context:component-scan base-package="com.controller" />
<!--    <mvc:annotation-driven />-->



    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="suffix" value=".jsp"/>
        <property name="prefix" value="/WEB-INF/"/>
    </bean>
</beans>
    @RequestMapping(value = {"/qq5"})
    @ResponseBody
    public  Student method5(Model model)
    {

        Student student=new Student();
        student.setName("gg");
        student.setSno("1122");
        return student;
    }

SpringMVC的请求

SpringMVC的请求-获得请求参数-请求参数类型

客户端请求参数的格式是:name=value&name=value……

服务器端要获得请求的参数,有时还需要进行数据的封装,SpringMVC可以接收如下类型的参数

基本类型参数

POJO类型参数

数组类型参数

集合类型参数

SpringMVC的请求-获得请求参数-获得基本类型参数(应用)

Controller中的业务方法的参数名称要与请求参数的name一致,参数值会自动映射匹配。并且能自动做类型转换;

http://localhost:8080/qq6?name=zzx&sno=17582

自动的类型转换是指从String向其他类型的转换

    @RequestMapping(value = {"/qq6"})
    @ResponseBody
    public  void method6(String name,String sno)
    {
        System.out.println(name);
        System.out.println(sno);
    }

SpringMVC的请求-获得请求参数-获得POJO类型参数(应用)

Controller中的业务方法的POJO参数的属性名与请求参数的name一致,参数值会自动映射匹配。

    @RequestMapping(value = {"/qq7"})
    @ResponseBody
    public  void method7(Student student)
    {
        System.out.println(student);

    }

SpringMVC的请求-获得请求参数-获得数组类型参数

Controller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配。

    @RequestMapping(value = {"/qq8"})
    @ResponseBody
    public  void method8(String[] student)
    {
        System.out.println(Arrays.asList(student));

    }

SpringMVC的请求-获得请求参数-获得集合类型参数

获得集合参数时,要将集合参数包装到一个POJO中才可以。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/qq9" method="post">
    <%--表明是第一个User对象的username age--%>
    <input type="text" name="students[0].name"><br/>
    <input type="text" name="students[0].sno"><br/>
    <input type="text" name="students[1].name"><br/>
    <input type="text" name="students[1].sno"><br/>
    <input type="submit" value="提交">
</form>
</body>
</html>

    @RequestMapping(value = {"/qq9"})
    @ResponseBody
    public  void method9(VO student)
    {
        System.out.println(student);

    }
    public class VO {
    List<Student> students;

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "VO{" +
                "students=" + students +
                '}';
    }
}

SpringMVC的请求-获得请求参数-获得集合类型参数2

当使用ajax提交时,可以指定contentType为json形式,那么在方法参数位置使用@RequestBody可以直接接收集合数据而无需使用POJO进行包装

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>
    var userList = new Array();
    userList.push({name:"zhangsan",sno:"c11"});
    userList.push({name:"lisi",sno:"c12"});

    $.ajax({
        type:"POST",
        url:"${pageContext.request.contextPath}/qq10",
        data:JSON.stringify(userList),
        contentType:"application/json;charset=utf-8"
    });

</script>
</body>
</html>



    @RequestMapping(value = {"/qq10"})
    @ResponseBody
    public  void method10(@RequestBody List<Student> userList)
    {
        System.out.println(userList);

    }

SpringMVC的请求-获得请求参数-静态资源访问的开启

<url-pattern>/</url-pattern>拦截所有请求包括静态资源,springMVC会将静态资源当做一个普通的请求处理,从而也找不到相应的处理器导致404错误.这时候dispatchServlet完全取代了default servlet,将不会再访问容器中原始默认的servlet,而对静态资源的访问就是通过容器默认servlet来处理的,故而这时候静态资源将不可访问。
当有静态资源需要加载时,比如jquery文件,通过谷歌开发者工具抓包发现,没有加载到jquery文件,原因是SpringMVC的前端控制器DispatcherServlet的url-pattern配置的是/,代表对所有的资源都进行过滤操作,我们可以通过以下两种方式指定放行静态资源:

•在spring-mvc.xml配置文件中指定放行的资源

<mvc:resources mapping="/js/**"location="/js/"/>

•使用<mvc:default-servlet-handler/>标签

<!--开发资源的访问-->
    <!--<mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/img/**" location="/img/"/>-->

    <mvc:default-servlet-handler/>

这里有有一点要注意,default servlet对于使用beanName方式配置的处理器,是可以访问的.但是对于@RequestMapping注解方式配置的处理器是不起作用的,
因为没有相应的HandlerMapping和HandlerAdapter支持注解的使用。这时候可以使用<mvc:annotation-driven/>配置在容器中注册支持@RequestMapping注解的组件即可.

SpringMVC的请求-获得请求参数-配置全局乱码过滤器

当post请求时,数据会出现乱码,我们可以设置一个过滤器来进行编码的过滤。

    <filter>
        <filter-name>filter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>ending</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    @RequestMapping(value = {"/qq6"})
    @ResponseBody
    public  void method6(String name,String sno)
    {
        System.out.println(name);
        System.out.println(sno);
    }

19-SpringMVC的请求-获得请求参数-参数绑定注解@RequestParam(应用)

当请求的参数名称与Controller的业务方法参数名称不一致时,就需要通过@RequestParam注解显示的绑定

    @RequestMapping(value = {"/qq11"})
    @ResponseBody
    public  void method11(@RequestParam(value="name",required = false, defaultValue = "xxx") String userName)
    {
        System.out.println(userName);

    }


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hhhh</title>
</head>
<body>
<h1>hello</h1>
<form action="${pageContext.request.contextPath}/qq11" method="post">
    <input type="text" name="name"><br>
    <input type="submit" value="提交"><br>
</form>
</body>
</html>

SpringMVC的请求-获得请求参数-Restful风格的参数的获取

Restful是一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。主要用于客户端和服务器交互类的软件,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存机制等。

Restful风格的请求是使用“url+请求方式”表示一次请求目的的,HTTP 协议里面四个表示操作方式的动词如下:

GET:用于获取资源

POST:用于新建资源

PUT:用于更新资源

DELETE:用于删除资源

例如:

/user/1 GET : 得到 id = 1 的 user

/user/1 DELETE: 删除 id = 1 的 user

/user/1 PUT: 更新 id = 1 的 user

/user POST: 新增 user

上述url地址/user/1中的1就是要获得的请求参数,在SpringMVC中可以使用占位符进行参数绑定。地址/user/1可以写成/user/{id},占位符{id}对应的就是1的值。在业务方法中我们可以使用@PathVariable注解进行占位符的匹配获取工作。

http://localhost:8080/qq12/xxx

    @RequestMapping(value = {"/qq12/{name}"})
    @ResponseBody
    public  void method12(@PathVariable(value="name",required = false) String userName)
    {
        System.out.println(userName);

    }

SpringMVC的请求-获得请求参数-自定义类型转换器

SpringMVC 默认已经提供了一些常用的类型转换器,例如客户端提交的字符串转换成int型进行参数设置。

但是不是所有的数据类型都提供了转换器,没有提供的就需要自定义转换器,例如:日期类型的数据就需要自定义转换器。

public class DateConverter implements Converter<String, Date> {

    public Date convert(String s) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date date=null;
        try {
            date =simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
    @RequestMapping(value = {"/qq13"})
    @ResponseBody
    public  void method13(Date date)
    {
        System.out.println(date);

    }
    <mvc:annotation-driven conversion-service="conversionService2"/>


    <mvc:default-servlet-handler/>
    <bean id="conversionService2" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.controller.DateConverter"/>
            </list>
        </property>
    </bean>

SpringMVC的请求-获得请求参数-获得Servlet相关API

SpringMVC支持使用原始ServletAPI对象作为控制器方法的参数进行注入,常用的对象如下:

HttpServletRequest

HttpServletResponse

HttpSession

    @RequestMapping(value = {"/qq14"})
    @ResponseBody
    public  void method14(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession httpSession)
    {
        System.out.println(httpServletRequest);
        System.out.println( httpServletResponse);
        System.out.println(httpSession);
    }

SpringMVC的请求-获得请求参数-获得请求头信息

使用@RequestHeader可以获得请求头信息,相当于web阶段学习的request.getHeader(name)
@RequestHeader注解的属性如下:

value:请求头的名称

required:是否必须携带此请求头

使用@CookieValue可以获得指定Cookie的值

    @RequestMapping(value = {"/qq16"})
    @ResponseBody
    public  void method16(@RequestHeader(value = "User-Agent",required = false) String User )
    {
        System.out.println(User);
    }

@CookieValue注解的属性如下:

value:指定cookie的名称

required:是否必须携带此cookie

    @RequestMapping(value = {"/qq17"})
    @ResponseBody
    public  void method17(@CookieValue(value = "JSESSIONID",required = false) String User )
    {
        System.out.println(User);
    }

SpringMVC的请求-文件上传-客户端表单实现

文件上传客户端表单需要满足:

表单项type=“file”

表单的提交方式是post

表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”

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

<form action="${pageContext.request.contextPath}/qq18" method="post" enctype="multipart/form-data">
    名称 <input type="text" name="name"><br/>
    文件1<input type="file" name="multipartFile"><br/>
    <input type="submit" value="提交">
</form>

</body>
</html>

3-SpringMVC的请求-文件上传-单文件上传的代码实现

添加依赖

<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.3</version>
    </dependency>

配置多媒体解析器

<!--配置文件上传解析器,id必须为multipartResolver,否则会出错-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="500000"/>
    </bean>

完成文件上传

    @RequestMapping(value = {"/qq18"})
    @ResponseBody
    public  void method17(String name, MultipartFile multipartFile)
    {
        System.out.println(name);
        try {
            multipartFile.transferTo(new File("e://"+multipartFile.getOriginalFilename()));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

SpringMVC的请求-文件上传-多文件上传的代码实现

多文件上传,只需要将页面修改为多个文件上传项,将方法参数MultipartFile类型修改为MultipartFile[]即可

    @RequestMapping(value = {"/qq19"})
    @ResponseBody
    public  void method19(String name, MultipartFile[] multipartFiles)
    {
        System.out.println(name);
        try {
            for (MultipartFile multipartFile : multipartFiles) {
                multipartFile.transferTo(new File("e://"+multipartFile.getOriginalFilename()));
            }

        } catch (IOException ioException) {
            ioException.printStackTrace();
        }


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

<form action="${pageContext.request.contextPath}/qq19" method="post" enctype="multipart/form-data">
    名称 <input type="text" name="name"><br/>
    文件1<input type="file" name="multipartFile"><br/>
    文件2<input type="file" name="multipartFile"><br/>
    <input type="submit" value="提交">
</form>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值