Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable (转)
Spring静态资源路径是指系统可以直接访问的路径,且路径下的所有文件均可被用户直接读取。
在Springboot中默认的静态资源路径有:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,从这里可以看出这里的静态资源路径都是在classpath中(也就是在项目路径下指定的这几个文件夹)
试想这样一种情况:一个网站有文件上传文件的功能,如果被上传的文件放在上述的那些文件夹中会有怎样的后果?
网站数据与程序代码不能有效分离;
当项目被打包成一个.jar文件部署时,再将上传的文件放到这个.jar文件中是有多么低的效率;
网站数据的备份将会很痛苦。
此时可能最佳的解决办法是将静态资源路径设置到磁盘的某个目录。
在Springboot中可以直接在配置文件中覆盖默认的静态资源路径的配置信息:
application.properties配置文件如下:
server.port=1122
web.upload-path=D:/file/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
注意:web.upload-path这个属于自定义的属性,指定了一个路径,注意要以/结尾;
spring.mvc.static-path-pattern=/**表示所有的访问都经过静态资源路径;
spring.resources.static-locations在这里配置静态资源路径,这里的配置会覆盖默认配置,所以需要将默认的也加上否则static、public等这些路径将不能被当作静态资源路径,
在这个最末尾的file:${web.upload-path}之所有要加file:是因为指定的是一个具体的硬盘路径,其他的使用classpath指的是系统环境变量
自定义资源映射
上面我们介绍了Spring Boot 的默认资源映射,一般够用了,那我们如何自定义目录?
这些资源都是打包在jar包中的,然后实际应用中,我们还有很多资源是在管理系统中动态维护的,并不可能在程序包中,对于这种随意指定目录的资源,如何访问?
自定义目录
以增加 /myres/* 映射到 classpath:/myres/* 为例的代码处理为:
实现类继承 WebMvcConfigurerAdapter 并重写方法 addResourceHandlers (对于 WebMvcConfigurerAdapter 上篇介绍拦截器的文章中已经有提到)
import org.springboot.sample.interceptor.MyInterceptor1;
import org.springboot.sample.interceptor.MyInterceptor2;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter { @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/");
super.addResourceHandlers(registry);
} }
访问myres 文件夹中的fengjing.jpg 图片的地址为 http://localhost:8080/myres/fengjing.jpg
这样使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用。
如果我们将/myres/* 修改为 /* 与默认的相同时,则会覆盖系统的配置,可以多次使用 addResourceLocations 添加目录,优先级先添加的高于后添加的。
// 访问myres根目录下的fengjing.jpg 的URL为 http://localhost:8080/fengjing.jpg (/** 会覆盖系统默认的配置)
// registry.addResourceHandler("/**").addResourceLocations("classpath:/myres/").addResourceLocations("classpath:/static/");
其中 addResourceLocations 的参数是多参,可以这样写 addResourceLocations(“classpath:/img1/”, “classpath:/img2/”, “classpath:/img3/”);
/**
* Add one or more resource locations from which to serve static content. Each location must point to a valid
* directory. Multiple locations may be specified as a comma-separated list, and the locations will be checked
* for a given resource in the order specified.
* <p>For example, {{@code "/"}, {@code "classpath:/META-INF/public-web-resources/"}} allows resources to
* be served both from the web application root and from any JAR on the classpath that contains a
* {@code /META-INF/public-web-resources/} directory, with resources in the web application root taking precedence.
* @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation
*/
public ResourceHandlerRegistration addResourceLocations(String... resourceLocations) {
for (String location : resourceLocations) {
this.locations.add(resourceLoader.getResource(location));
}
return this;
}
使用外部目录
如果我们要指定一个绝对路径的文件夹(如 H:/myimgs/ ),则只需要使用 addResourceLocations 指定即可。
// 可以直接使用addResourceLocations 指定磁盘绝对路径,同样可以配置多个位置,注意路径写法需要加上file:
registry.addResourceHandler("/myimgs/**").addResourceLocations("file:C:/myimgs/");
通过配置文件配置【会覆盖默认配置,操作时,要明白操作的业务含义】
上面是使用代码来定义静态资源的映射,其实Spring Boot也为我们提供了可以直接在 application.properties(或.yml)中配置的方法。
配置方法如下:
# 默认值为 /**
spring.mvc.static-path-pattern=
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开,
使用 spring.mvc.static-path-pattern 可以重新定义pattern,如修改为 /myres/** ,则访问static 等目录下的fengjing.jpg文件应该为 http://localhost:8080/myres/fengjing.jpg ,修改之前为 http://localhost:8080/fengjing.jpg
使用 spring.resources.static-locations 可以重新定义 pattern 所指向的路径,支持 classpath: 和 file: (上面已经做过说明)
注意 spring.mvc.static-path-pattern 只可以定义一个,目前不支持多个逗号分割的方式。
参考了
https://www.cnblogs.com/ceshi2016/p/6704693.html
http://blog.csdn.net/catoop/article/details/50501706
相关参考:
Spring 注解学习手札(一) 构建简单Web应用
Spring 注解学习手札(二) 控制层梳理
Spring 注解学习手札(三) 表单页面处理
Spring 注解学习手札(四) 持久层浅析
Spring 注解学习手札(五) 业务层事务处理
Spring 注解学习手札(六) 测试
Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable
Spring 注解学习手札(八) 补遗——@ExceptionHandler
SpringMVC层跟JSon结合,几乎不需要做什么配置,代码实现也相当简洁。再也不用为了组装协议而劳烦辛苦了!
一、Spring注解@ResponseBody,@RequestBody和HttpMessageConverter
Spring 3.X系列增加了新注解@ResponseBody,@RequestBody
- @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
- @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。
HttpMessageConverter接口,需要开启<mvc:annotation-driven />。
AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdapter的getMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter
可以理解为,只要有对应协议的解析器,你就可以通过几行配置,几个注解完成协议——对象的转换工作!
PS:Spring默认的json协议解析由Jackson完成。
二、servlet.xml配置
Spring的配置文件,简洁到了极致,对于当前这个需求只需要三行核心配置:
<context:component-scan base-package="org.zlex.json.controller" />
<context:annotation-config />
<mvc:annotation-driven />
mvc:annotation-driven是一种简写的配置方式,那么mvc:annotation-driven到底做了哪些工作呢?如何替换掉mvc:annotation-driven呢?
<mvc:annotation- driven/>在初始化的时候会自动创建两个对 象,
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
和
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter,
我们如果想不使用<mvc:annotation-driven/>这种简写方式,将其替换掉的话,就必须自己手动去配置这两个bean对 象。下面是这两个对象的配置方法,和详细的注视说明。
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="useDefaultSuffixPattern" value="false" />
<property name="interceptors">
<list>
<bean class="org.mspring.mlog.web.interceptor.RememberMeInterceptor" />
<bean class="org.mspring.mlog.web.interceptor.SettingInterceptor" />
<bean class="org.mspring.platform.web.query.interceptor.QueryParameterInterceptor" />
</list>
</property>
</bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<-- 这个converter是我自己定义的,是为了解决spring自带的StringHttpMessageConverter中文乱码问题的 -->
<bean class="org.mspring.platform.web.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
<!-- 这里可以根据自己的需要添加converter -->
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<!-- -->
</list>
</property>
<property name="customArgumentResolvers">
<list>
<bean class="org.mspring.platform.web.resolver.UrlVariableMethodArgumentResolver" />
</list>
</property> <property name="webBindingInitializer">
<bean id="webBindingInitializer"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService" />
</bean>
</property>
</bean> <!-- 1, 注册ConversionService -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="org.mspring.platform.web.converter.DateConverter">
<property name="pattern" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</list>
</property>
<property name="formatters">
<list>
<bean class="org.mspring.mlog.web.formatter.factory.TagFormatAnnotationFormatterFactory"></bean>
<bean class="org.mspring.mlog.web.formatter.factory.EncodingFormatAnnotationFormatterFactory"></bean>
</list>
</property>
</bean> </beans>
这样,我们就可以就成功的替换掉<mvc:annotation-driven />了。
闲言少叙,先说依赖配置,这里以Json+Spring为参考:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.2.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.8</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>compile</scope>
</dependency>
主要需要spring-webmvc、jackson-mapper-asl两个包,其余依赖包Maven会帮你完成。至于log4j,我还是需要看日志嘛。
包依赖图:
至于版本,看项目需要吧!
四、代码实现
域对象:
public class Person implements Serializable { private int id;
private String name;
private boolean status; public Person() {
// do nothing
}
}
这里需要一个空构造,由Spring转换对象时,进行初始化。
@ResponseBody,@RequestBody,@PathVariable
控制器:
@Controller
public class PersonController { /**
* 查询个人信息
*
* @param id
* @return
*/
@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)
public @ResponseBody
Person porfile(@PathVariable int id, @PathVariable String name,
@PathVariable boolean status) {
return new Person(id, name, status);
} /**
* 登录
*
* @param person
* @return
*/
@RequestMapping(value = "/person/login", method = RequestMethod.POST)
public @ResponseBody
Person login(@RequestBody Person person) {
return person;
}
}
备注:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}与@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。 这是restful式风格。
如果映射名称有所不一,可以参考如下方式:
@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)
public @ResponseBody
Person porfile(@PathVariable("id") int uid) {
return new Person(uid, name, status);
}
- GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。
- POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
- @ResponseBody可以标注任何对象,由Srping完成对象——协议的转换。
做个页面测试下:
$(document).ready(function() {
$("#profile").click(function() {
profile();
});
$("#login").click(function() {
login();
});
});
function profile() {
var url = 'http://localhost:8080/spring-json/json/person/profile/';
var query = $('#id').val() + '/' + $('#name').val() + '/'
+ $('#status').val();
url += query;
alert(url);
$.get(url, function(data) {
alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "
+ data.status);
});
}
function login() {
var mydata = '{"name":"' + $('#name').val() + '","id":"'
+ $('#id').val() + '","status":"' + $('#status').val() + '"}';
alert(mydata);
$.ajax({
type : 'POST',
contentType : 'application/json',
url : 'http://localhost:8080/spring-json/json/person/login',
processData : false,
dataType : 'json',
data : mydata,
success : function(data) {
alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "
+ data.status);
},
error : function() {
alert('Err...');
}
});
Table
<table>
<tr>
<td>id</td>
<td><input id="id" value="100" /></td>
</tr>
<tr>
<td>name</td>
<td><input id="name" value="snowolf" /></td>
</tr>
<tr>
<td>status</td>
<td><input id="status" value="true" /></td>
</tr>
<tr>
<td><input type="button" id="profile" value="Profile——GET" /></td>
<td><input type="button" id="login" value="Login——POST" /></td>
</tr>
</table>
四、简单测试
Get方式测试:
Post方式测试:
五、常见错误
POST操作时,我用$.post()方式,屡次失败,一直报各种异常:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
直接用$.post()直接请求会有点小问题,尽管我标识为json协议,但实际上提交的ContentType还是application/x-www-form-urlencoded。需要使用$.ajaxSetup()标示下ContentType。
效果是一样!
详见附件!
相关参考:
Spring 注解学习手札(一) 构建简单Web应用
Spring 注解学习手札(二) 控制层梳理
Spring 注解学习手札(三) 表单页面处理
Spring 注解学习手札(四) 持久层浅析
Spring 注解学习手札(五) 业务层事务处理
Spring 注解学习手札(六) 测试
Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable
Spring 注解学习手札(八) 补遗——@ExceptionHandler
- spring-json.zip (65.1 KB)
- 下载次数: 1468
Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable (转)的更多相关文章
- 转-Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable
转-http://snowolf.iteye.com/blog/1628861/ Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariab ...
- Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable(转)
最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服! 相关参考: Spring 注解学习手札(一 ...
- 【转】Spring 注解学习手札(超好的springmvc注解教程)
Spring 注解学习手札(一) 构建简单Web应用 Spring 注解学习手札(二) 控制层梳理 Spring 注解学习手札(三) 表单页面处理 Spring 注解学习手札(四) 持久层浅析 Spr ...
- Spring 注解学习笔记
声明Bean的注解: @Component : 组件,没有明确的角色 @Service : 在业务逻辑层(service层)使用 @Repository : 在数据访问层(dao层)使用. @Cont ...
- Spring 注解学习 详细代码示例
学习Sping注解,编写示例,最终整理成文章.如有错误,请指出. 该文章主要是针对新手的简单使用示例,讲述如何使用该注释,没有过多的原理解析. 已整理的注解请看右侧目录.写的示例代码也会在结尾附出. ...
- Spring Boot学习笔记(七)多数据源下的事务管理
DataBaseConfig中加入事务管理器 DataBaseConfig的详解以及多数据源的配置参见我的上一篇文章 @Configuration @MapperScan(basePackages={ ...
- Spring注解驱动开发(七)-----servlet3.0、springmvc
ServletContainerInitializer Shared libraries(共享库) / runtimes pluggability(运行时插件能力) 1.Servlet容器启动会扫描, ...
- spring框架学习(七)spring管理事务方式之xml配置
1.DAO AccountDao.java package cn.mf.dao; public interface AccountDao { //加钱 void increaseMoney(Integ ...
- Spring注解学习笔记一
一.Retention注解Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值: 1.RetentionPolicy.SOURCE —— 这种类型的Annotations只 ...
随机推荐
- POJ 2524 :Ubiquitous Religions
id=2524">Ubiquitous Religions Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 231 ...
- hadoop在实现kmeans算法——一个mapreduce实施
写mapreduce程序实现kmeans算法.我们的想法可能是 1. 次迭代后的质心 2. map里.计算每一个质心与样本之间的距离,得到与样本距离最短的质心,以这个质心作为key,样本作为value ...
- Oracle大数据量查询实际分析
Oracle数据库: 刚做一张5000万条数据的数据抽取,当前表同时还在继续insert操作,每分钟几百条数据. 该表按照时间,以月份为单位做的表分区,没有任何索引,当前共有14个字段,平均每个字段3 ...
- 《JavaScript设计模式与开发实践》读书笔记之观察者模式
1.观察者模式 观察者模式定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知. JavaScript中通常采用事件模型替代传统的观察者模式 1.1 逐步实现观 ...
- jQuery获取url参数值
$.extend({ getUrlVars: function () { var vars = [], hash; var hashes = window.location.href.slice(wi ...
- Windows phone 8 学习笔记(2) 数据文件操作
原文:Windows phone 8 学习笔记(2) 数据文件操作 Windows phone 8 应用用于数据文件存储访问的位置仅仅限于安装文件夹.本地文件夹(独立存储空间).媒体库和SD卡四个地方 ...
- OSGI学习总结
最近的一项研究了解了一下OSGI技术,感觉OSGI尽管有一定的学习难度.可是终于掌握和推广之后将是一项对系统开发比較实用的技术.在此和大家分享一下自己的感悟. 1.什么是OSGI OSGI直译为&qu ...
- 仿CSDN Blog返回页面顶部功能
只修改了2个地方: 1,返回的速度-->改成了慢慢回去.(原来是一闪而返回) 2,返回顶部图标出现的时机-->改成了只要不在顶部就显示出来.(原来是向下滚动500px后才显示) 注意:JS ...
- poj Optimal Milking
Optimal Milking 题目: 有K个机器.C仅仅牛.要求求出最全部牛到各个产奶机的最短距离.给出一个C+K的矩阵,表示各种标号间的距离. 而每一个地方最多有M仅仅牛. 算法分析: 二分+最短 ...
- RTF 格式 说明
摘要: 本文对RTF文件格式进行分析研究,对RTF文件结构及特性进行了阐述,并分别列举了几个有用性的样例进行具体分析, 终于通过VB程序代码实现了一个RTF书写器(不具有所见即所得特性).本文对软件开 ...