SpringMVC(三) RESTful架構和文件上傳下載


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();
                 }
             }
          }                    
       }           
    }           
 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM