RESTful架构

REST全名为:Representational State Transfer。资源表现层状态转化。是目前最流行的一种互联网软件架构。

它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。

资源(Resources)

  网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的 URI 。要获取这个资源,访问它的URI就可以,因此 URI 即为每一个资源的独一无二的识别符。

表现层(Representation)

  把资源具体呈现出来的形式,叫做它的表现层(Representation)。比如,文本可以用 txt 格式表现,也可以用 HTML 格式、XML 格式、JSON 格式表现,甚至可以采用二进制格式。

状态转化(State Transfer)

  每发出一个请求,就代表了客户端和服务器的一次交互过程。HTTP协议,是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生“状态转化”(State Transfer)。而这种转化是建立在表现层之上的,所以就是 “表现层状态转化”。

特点:

1.url更加简洁,将参数通过url传到服务端。

普通的url:地址栏/queryUserById?id=1

REST的url风格:地址栏/queryUserById/1

2.有利于不同系统之间的资源共享,只需要遵守规范,不需要做其他的配置就能达到资源共享。

Restful具体来讲就是四种表现形式,分别对应四种基本操作:

GET:用来获取资源,

POST:用来新建资源,

PUT:用来修改资源,

DELETE:用来删除资源。

但是,form表单只支持 GET与 POST 请求,不支持DELETE、PUT,因此可以使用ajax的方式

<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$("#get").click(function(){
var id = $("#get_id").val();
$.ajax({
url:"httpGet/"+id,
type:"get",
dataType:"json",
success:function(data){
if(data == null){
alert("该用户不存在");
}else{
alert(data.id+"---"+data.name+"---"+data.age);
}
}
})
}); $("#post").click(function(){
var id = $("#post_id").val();
var name = $("#post_name").val();
var age = $("#post_age").val();
$.ajax({
url:"httpPost/"+id+"/"+name+"/"+age,
type:"post",
dataType:"json",
success:function(data){
alert(data.id+"---"+data.name+"---"+data.age);
}
})
}); $("#put").click(function(){
var id = $("#put_id").val();
var name = $("#put_name").val();
var age = $("#put_age").val();
$.ajax({
url:"httpPut/"+id+"/"+name+"/"+age,
type:"put",
dataType:"json",
success:function(data){
alert(data.id+"---"+data.name+"---"+data.age);
}
})
}); $("#delete").click(function(){
var id = $("#delete_id").val();
$.ajax({
url:"httpDelete/"+id,
type:"delete",
dataType:"text",
success:function(data){
alert(data);
}
})
});
})
</script>

Java层的代码

@Controller
public class RestfulHandler { private static Map<Integer,Student> students; static{
students = new HashMap<Integer,Student>();
students.put(1, new Student(1,"zhangsan",22));
} @RequestMapping(value="/httpGet/{id}",method=RequestMethod.GET)
@ResponseBody
public Student httpGet(@PathVariable(value="id")int id){
return students.get(id);
} @RequestMapping(value="/httpPost/{id}/{name}/{age}",method=RequestMethod.POST)
@ResponseBody
public Student httpPost(@PathVariable(value="id")int id,@PathVariable(value="name")String name,@PathVariable(value="age")int age){
Student student = new Student(id,name,age);
students.put(student.getId(), student);
return student;
} @RequestMapping(value="/httpDelete/{id}",method=RequestMethod.DELETE)
@ResponseBody
public String httpDelete(@PathVariable(value="id")int id){
students.remove(id);
return "delete-ok";
} @RequestMapping(value="/httpPut/{id}/{name}/{age}",method=RequestMethod.PUT)
@ResponseBody
public Student httpPut(@PathVariable(value="id")int id,@PathVariable(value="name")String name,@PathVariable(value="age")int age){
Student student = new Student(id,name,age);
students.put(student.getId(), student);
return student;
}
}

注意:后台返回json数据需要修改xml文件,增加Jackson的包。

文件上传/下载

Web项目中,文件上传功能几乎是必不可少的,实现的技术有很多,甚至在WEB层以及有封装好的。

单文件上传

1.底层还是Apache fileupload组件完成上传,SpringMVC只是进行了封装,需要引入fileupload的包。

2.springmvc.xml配置CommonsMultipartResolver。

    <!-- id必须是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 处理文件名中文乱码 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 设置多文件上传,总大小上限,不设置默认没有限制,单位为字节,1M=1*1024*1024 -->
<property name="maxUploadSize" value="1048576"/>
<!-- 设置每个上传文件的大小上限 -->
<property name="maxUploadSizePerFile" value="1048576"/>
</bean>

3.JSP页面的input的type设置为file。form表单的method设置为post,并且enctype设置为multipart/form-data。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="img">
<input type="submit" name="提交">
</form><br />
<c:if test="${filePath!=null }">
<h1>上传的图片</h1><br />
<img width="300px" src="<%=basePath %>${filePath}"/>
</c:if>
</body>
</html>

4.Java方法,使用MultipartFile对象作为参数,接收前端发送过来的文件,并完成上传操作。

   @RequestMapping(value="/upload", method = RequestMethod.POST)
public String upload(@RequestParam(value="img")MultipartFile img, HttpServletRequest request)
throws Exception {
//getSize()方法获取文件的大小来判断是否有上传文件
if (img.getSize() > 0) {
//获取保存上传文件的file文件夹绝对路径
String path = request.getSession().getServletContext().getRealPath("file");
//获取上传文件名
String fileName = img.getOriginalFilename();
File file = new File(path, fileName);
img.transferTo(file);
//保存上传之后的文件路径
request.setAttribute("filePath", "file/"+fileName);
return "upload";
}
return "error";
}

多文件上传

   //和单文件上传类似,input的name属性要一致,接收的参数需要是数组类型
@RequestMapping(value="/uploads", method = RequestMethod.POST)
public String uploads(@RequestParam MultipartFile[] imgs, HttpServletRequest request)
throws Exception {
//创建集合,保存上传后的文件路径
List<String> filePaths = new ArrayList<String>();
for (MultipartFile img : imgs) {
if (img.getSize() > 0) {
String path = request.getSession().getServletContext().getRealPath("file");
String fileName = img.getOriginalFilename();
File file = new File(path, fileName);
filePaths.add("file/"+fileName);
img.transferTo(file);
}
}
request.setAttribute("filePaths", filePaths);
return "uploads";
}

文件下载

1.在JSP使用超链接的方式进行文件下载,也可以使用按钮方式。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="download?fileName=aaa.jpg">下载图片</a>
</body>
</html>

2.JAVA方法。

  @RequestMapping("/download")
public void downloadFile(String fileName,HttpServletRequest request,
HttpServletResponse response){
if(fileName!=null){
//获取file绝对路径
String realPath = request.getServletContext().getRealPath("file/");
File file = new File(realPath,fileName);
OutputStream out = null;
if(file.exists()){
//设置下载类型,具体百度
response.setContentType("application/force-download");
//设置文件名
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
try {
out = response.getOutputStream();
//写入前台页面
out.write(FileUtils.readFileToByteArray(file));
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(out != null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}

SpringMVC(三) RESTful架构和文件上传下载的更多相关文章

  1. SpringMVC整合fastdfs-client-java实现web文件上传下载

    原文:http://blog.csdn.net/wlwlwlwl015/article/details/52682153 本篇blog主要记录一下SpringMVC整合FastDFS的Java客户端实 ...

  2. SpringMVC ajax技术无刷新文件上传下载删除示例

    参考 Spring MVC中上传文件实例 SpringMVC结合ajaxfileupload.js实现ajax无刷新文件上传 Spring MVC 文件上传下载 (FileOperateUtil.ja ...

  3. SpringMVC学习笔记八:文件上传下载(转)

    转自:http://www.cnblogs.com/WJ-163/p/6269409.html 一.关键步骤 ①引入核心JAR文件 SpringMVC实现文件上传,需要再添加两个jar包.一个是文件上 ...

  4. SpringMVC中使用 MultipartFile 进行文件上传下载及删除

    一:引入必要的包 <!--文件上传--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fil ...

  5. SpringMVC文件上传下载

    在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...

  6. SpringMVC文件上传下载(单文件、多文件)

    前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...

  7. SpringMVC(四)-- springmvc的系统学习之文件上传、ajax&json处理

    资源:尚学堂 邹波 springmvc框架视频 一.文件上传 1.步骤: (1)导入jar包 commons-fileupload,commons-io (2)在springmvc的配置文件中配置解析 ...

  8. springmvc文件上传下载简单实现案例(ssm框架使用)

    springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...

  9. 分享知识-快乐自己:SpringMvc中的单多文件上传及文件下载

    摘要:SpringMvc中的单多文件上传及文件下载:(以下是核心代码(拿过去直接能用)不谢) <!--设置文件上传需要的jar--> <dependency> <grou ...

随机推荐

  1. oracle RAC 11g sqlload 生产表导入数据(ORA-12899)

    背景:由于即将来临的双十一,业务部门(我司是做京东,天猫的短信服务),短信入库慢,需要DBA把数据库sqlload进数据库. 表结构如下: MRS VARCHAR2(100), STATUS VARC ...

  2. Spring《二》 Bean的生命周期

    Bean初始化 1.bean中实现public void init():方法,config.xml中增加init-method="init" 属性. 2.bean实现接口Initi ...

  3. Scrapy Architecture overview--官方文档

    原文地址:https://doc.scrapy.org/en/latest/topics/architecture.html This document describes the architect ...

  4. C#6.0新增功能

    C# 6.0 版本包含许多可提高开发人员工作效率的功能. 此版本中的功能包括: 只读自动属性: 可以创建只能在构造函数中设置的只读自动属性. 自动属性初始值设定项: 可以编写初始化表达式来设置自动属性 ...

  5. [转]SQL Server 批量完整备份

    最近我们的服务器需要迁移,服务器上有很多数据库,有很多都不知道干什么的了,但是为了保险起见,我决定都备份下,起初我是右键一个一个备份的,备份三四个还好,可是数据库太多了,而且手动一步一步操作,还得修改 ...

  6. Codeforces 993A. Two Squares(暴力求解)

    解题思路(暴力解法) 平行于x轴的正方形和与x轴成45度倾斜的正方形相交的点中必定有整数点.即若两正方形相交,必定存在整数i,j,使(i,j)同时属于两个正方形. 我们把两个正方形中的整数点都找出来, ...

  7. Pyhton学习——Day27

    # hasattr(obj,'name')-->obj.name# getattr(obj,'name',default = 'xxx')--->obj.name# setattr(obj ...

  8. [置顶] openHAB 体系结构与编程模型 (1) --- 术语

    openHAB 术语 Item : 对硬件设备属性的抽象 ( Items are objects that can be read from or written to in order to int ...

  9. ZOJ 3203 Light Bulb( 三分求极值 )

    链接:传送门 题意: 求影子长度 L 的最大值 思路:如果 x = 0 ,即影子到达右下角时,如果人继续向后走,那么影子一定是缩短的,所以不考虑这种情况.根据图中的辅助线外加相似三角形定理可以得到 L ...

  10. [Codeforces 115E]Linear Kingdom Races

    题目大意: 有n块地,初始是荒地.你可以把某些荒地开垦(需要花费相应的价值\(a_i\)(正整数)),然后这些荒地就可以种田. 现在有m年,每年要在l到r区间内种田,获得p(正整数)的价值(必须保证l ...