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"})@ResponseBodypublic  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"})@ResponseBodypublic  void method6(String name,String sno){System.out.println(name);System.out.println(sno);}

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

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

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

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

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

    @RequestMapping(value = {"/qq8"})@ResponseBodypublic  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"})@ResponseBodypublic  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;}@Overridepublic 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"})@ResponseBodypublic  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"})@ResponseBodypublic  void method6(String name,String sno){System.out.println(name);System.out.println(sno);}

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

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

    @RequestMapping(value = {"/qq11"})@ResponseBodypublic  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}"})@ResponseBodypublic  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"})@ResponseBodypublic  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"})@ResponseBodypublic  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"})@ResponseBodypublic  void method16(@RequestHeader(value = "User-Agent",required = false) String User ){System.out.println(User);}

@CookieValue注解的属性如下:

value:指定cookie的名称

required:是否必须携带此cookie

    @RequestMapping(value = {"/qq17"})@ResponseBodypublic  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"})@ResponseBodypublic  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"})@ResponseBodypublic  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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391889.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Maven+eclipse快速入门

1.eclipse下载 在无外网情况下&#xff0c;无法通过eclipse自带的help-install new software输入url来获取maven插件&#xff0c;因此可以用集成了maven插件的免安装eclipse(百度一下有很多)。 2.jdk下载以及环境变量配置 JDK是向前兼容的&#xff0c;可在Eclipse上选择编译器版…

源码阅读中的收获

最近在做短视频相关的模块&#xff0c;于是在看 GPUImage 的源码。其实有一定了解的伙伴一定知道 GPUImage 是通过 addTarget 链条的形式添加每一个环节。在对于这样的设计赞叹之余&#xff0c;想到了实际开发场景下可以用到的场景&#xff0c;借此分享。 我们的项目中应该有很…

马尔科夫链蒙特卡洛_蒙特卡洛·马可夫链

马尔科夫链蒙特卡洛A Monte Carlo Markov Chain (MCMC) is a model describing a sequence of possible events where the probability of each event depends only on the state attained in the previous event. MCMC have a wide array of applications, the most common of…

PAT乙级1012

题目链接 https://pintia.cn/problem-sets/994805260223102976/problems/994805311146147840 题解 就比较简单&#xff0c;判断每个数字是哪种情况&#xff0c;然后进行相应的计算即可。 下面的代码中其实数组是不必要的&#xff0c;每取一个数字就可以直接进行相应计算。 // P…

我如何在昌迪加尔大学中心组织Google Hash Code 2019

by Neeraj Negi由Neeraj Negi 我如何在昌迪加尔大学中心组织Google Hash Code 2019 (How I organized Google Hash Code 2019 at Chandigarh University Hub) This is me !!! Neeraj Negi — Google HashCode Organizer这就是我 &#xff01;&#xff01;&#xff01; Neeraj …

leetcode 665. 非递减数列(贪心算法)

给你一个长度为 n 的整数数组&#xff0c;请你判断在 最多 改变 1 个元素的情况下&#xff0c;该数组能否变成一个非递减数列。 我们是这样定义一个非递减数列的&#xff1a; 对于数组中所有的 i (0 < i < n-2)&#xff0c;总满足 nums[i] < nums[i 1]。 示例 1: …

django基于存储在前端的token用户认证

一.前提 首先是这个代码基于前后端分离的API,我们用了django的framework模块,帮助我们快速的编写restful规则的接口 前端token原理: 把(token加密后的字符串,keyname)在登入后发到客户端,以后客户端再发请求,会携带过来服务端截取(token加密后的字符串,keyname),我们再利用解密…

数据分布策略_有效数据项目的三种策略

数据分布策略Many data science projects do not go into production, why is that? There is no doubt in my mind that data science is an efficient tool with impressive performances. However, a successful data project is also about effectiveness: doing the righ…

cell 各自的高度不同的时候

1, cell 根据文字、图片等内容&#xff0c;确定自己的高度。每一个cell有自己的高度。 2&#xff0c;tableView 初始化 现实的时候&#xff0c;不是从第一个cell开始显示&#xff0c;&#xff08;从第二个&#xff1f;&#xff09;&#xff0c;非非正常显示。 a:cell 的高度问题…

leetcode 978. 最长湍流子数组(滑动窗口)

当 A 的子数组 A[i], A[i1], …, A[j] 满足下列条件时&#xff0c;我们称其为湍流子数组&#xff1a; 若 i < k < j&#xff0c;当 k 为奇数时&#xff0c; A[k] > A[k1]&#xff0c;且当 k 为偶数时&#xff0c;A[k] < A[k1]&#xff1b; 或 若 i < k < j&…

spring boot源码下载地址

github下载&#xff1a; https://github.com/spring-projects/spring-boot/tree/1.5.x git地址&#xff1a; https://github.com/spring-projects/spring-boot.git 因为项目中目前使用的就是spring boot 1.5.19版本&#xff0c;因此这里先研究spring boot 1.5版本源码.转载于:h…

java基础学习——5、HashMap实现原理

一、HashMap的数据结构 数组的特点是&#xff1a;寻址容易&#xff0c;插入和删除困难&#xff1b;而链表的特点是&#xff1a;寻址困难&#xff0c;插入和删除容易。那么我们能不能综合两者的特性&#xff0c;做出一种寻址容易&#xff0c;插入删除也容易的数据结构&#xff1…

看懂nfl定理需要什么知识_NFL球队为什么不经常通过?

看懂nfl定理需要什么知识Debunking common NFL myths in an analytical study on the true value of passing the ball在关于传球真实价值的分析研究中揭穿NFL常见神话 Background背景 Analytics are not used enough in the NFL. In a league with an abundance of money, i…

Docker初学者指南-如何创建您的第一个Docker应用程序

您是一名开发人员&#xff0c;并且想要开始使用Docker&#xff1f; 本文是为您准备的。 (You are a developer and you want to start with Docker? This article is made for you.) After a short introduction on what Docker is and why to use it, you will be able to cr…

mybatis if-else(写法)

mybaits 中没有else要用chose when otherwise 代替 范例一 <!--批量插入用户--> <insert id"insertBusinessUserList" parameterType"java.util.List">insert into business_user (id , user_type , user_login )values<foreach collection…

spring—拦截器和异常

SpringMVC的拦截器 SpringMVC拦截器-拦截器的作用 Spring MVC 的拦截器类似于 Servlet 开发中的过滤器 Filter&#xff0c;用于对处理器进行预处理和后处理。 将拦截器按一定的顺序联结成一条链&#xff0c;这条链称为拦截器链&#xff08;InterceptorChain&#xff09;。在…

29/07/2010 sunrise

** .. We can only appreciate the miracle of a sunrise if we have waited in the darkness .. 人们在黑暗中等待着&#xff0c;那是期盼着如同日出般的神迹出现 .. 附&#xff1a;27/07/2010 sunrise ** --- 31 July 改动转载于:https://www.cnblogs.com/orderedchaos/archi…

密度聚类dbscan_DBSCAN —基于密度的聚类方法的演练

密度聚类dbscanThe idea of having newer algorithms come into the picture doesn’t make the older ones ‘completely redundant’. British statistician, George E. P. Box had once quoted that, “All models are wrong, but some are useful”, meaning that no model…

node aws 内存溢出_在AWS Elastic Beanstalk上运行生产Node应用程序的现实

node aws 内存溢出by Jared Nutt贾里德努特(Jared Nutt) 在AWS Elastic Beanstalk上运行生产Node应用程序的现实 (The reality of running a production Node app on AWS Elastic Beanstalk) 从在AWS的ELB平台上运行生产Node应用程序两年的经验教训 (Lessons learned from 2 y…

Day2-数据类型

数据类型与内置方法 数据类型 数字字符串列表字典元组集合字符串 1.用途 用来描述某个物体的特征&#xff1a;姓名&#xff0c;性别&#xff0c;爱好等 2.定义方式 变量名 字符串 如&#xff1a;name huazai 3.常用操作和内置方法 1.按索引取值&#xff1a;&#xff08;只能取…