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. TCP和UDP的具体区别

    TCP和UDP的最完整的区别 TCP UDP TCP与UDP基本区别: 1.基于连接与无连接 2.TCP要求系统资源较多,UDP较少: 3.UDP程序结构较简单 4.流模式(TCP)与数据报模式(UD ...

  2. 转:Eclipse上安装GIT插件EGit及使用

    一.Eclipse上安装GIT插件EGit Eclipse的版本eclipse-java-helios-SR2-win32.zip(在Eclipse3.3版本找不到对应的 EGit插件,无法安装) E ...

  3. c# TextBox

    1. text内容全选事件 textBox1.selectAll(); 2.失去与获取焦点事件 textox1.LostFocus += new EventHandler(txt_LostFocus) ...

  4. Oprofile分析(android oprofile性能分析)

    一.内核支持: make menuconfig 1.评测菜单中启用 Oprofile ,在 .config 文件中设置?CONFIG_PROFILING=y?和?CONFIG_OPROFILE=y 2 ...

  5. const,var,let 区别

    js中const,var,let区别 1.const定义的变量不可以修改,而且必须初始化. 声明的是常量 1 const b = 2;//正确 2 // const b;//错误,必须初始化 3 co ...

  6. C语言中以文本方式读写文件时换行符转换的注意事项

    我们知道在UNIX下是没有回车符(\r)的,只有换行符(\n),而C语言诞生于UNIX(Linux即面向开源的UNIX,Mac OS也是UNIX发展而来的,而Windows是从MS-DOS发展而来,与 ...

  7. 一个关于传参数js数组的封装方法(寄生模式)

    function createArr(){ var arr = new Array(); arr.push.apply(arr,arguments); arr.toJoin = function(){ ...

  8. APUE学习笔记6——线程和线程同步

    1 概念 线程是程序执行流的最小单元.线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的 ...

  9. Dynamic dispatch mechanisms

    Normally, in a typed language, the dispatch mechanism will be performed based on the type of the arg ...

  10. 脚本_使用expect自动交互远程主机安装软件

    #!bin/bash#功能:使用expect工具自动交互密码,远程到其它主机,安装httpd软件#作者:liusingbon#删除~/.ssh/known-hosts后,ssh远程任何主机,系统都会询 ...