Spring+SpringMVC+MyBatis深入學習及搭建(十六)——SpringMVC注解開發(高級篇)


轉載請注明出處:http://www.cnblogs.com/Joanna-Yan/p/7085268.html 

前面講到:Spring+SpringMVC+MyBatis深入學習及搭建(十五)——SpringMVC注解開發(基礎篇)

本文主要內容:

(1)SpringMVC校驗

(2)數據回顯

(3)異常處理器

(4)圖片上傳

(5)Json數據交互

(6)支持RESTful

1.SpringMVC校驗

1.1校驗理解

項目中,通常使用較多的是前端的校驗,比如頁面中js校驗。對於安全要求較高的建議在服務器進行校驗。

服務器校驗:

控制層controller:校驗頁面請求的參數的合法性。在服務端控制層controller校驗,不區分客戶端類型(瀏覽器、手機客戶端、遠程調用)

業務層service(使用較多):主要校驗關鍵業務參數,僅限於service接口中使用的參數。

持久層dao:一般是不校驗的。

1.2springmvc校驗需求

springmvc使用hibernate的校驗框架validation(和hibernate沒有任何關系)。

校驗思路:

頁面提交請求的參數,請求到controller方法中,使用validation進行校驗。如果校驗出錯,將錯誤信息展示Dao頁面。

具體需求:

商品修改,添加校驗(校驗商品名稱長度、生成日期的非空校驗),如果校驗出錯,在商品修改頁面顯示錯誤信息。

1.3環境准備

hibernate的校驗框架validation所需要jar包:

1.4配置校驗器

 在classpath下springmvc.xml中配置:

    <!-- 校驗器 -->
    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- Hibernate校驗器-->
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
        <!-- 指定校驗使用的資源文件,在文件中配置校驗錯誤信息,如果不指定則默認使用classpath下的ValidationMessages.properties -->
        <property name="validationMessageSource" ref="messageSource" />
    </bean>
    <!-- 校驗錯誤信息配置文件 -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <!-- 資源文件名-->
        <property name="basenames">   
            <list>    
            <value>classpath:CustomValidationMessages</value> 
            </list>   
        </property>
        <!-- 資源文件編碼格式 -->
        <property name="fileEncodings" value="utf-8" />
        <!-- 對資源文件內容緩存時間,單位秒 -->
        <property name="cacheSeconds" value="120" />
    </bean>

1.5將validator注入到處理器適配器中

 在classpath下springmvc.xml中配置:

1.5.1配置方式1

1.5.2配置方式2

<!-- 自定義webBinder -->
    <bean id="customBinder"
        class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <property name="validator" ref="validator" />
    </bean>

<!-- 注解適配器 -->
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="webBindingInitializer" ref="customBinder"></property>
    </bean>

1.6在pojo中添加校驗規則

在ItemsCustom.java中添加校驗規則:

/**
 * 商品信息的擴展類
 * @author Joanna.Yan
 *
 */
public class ItemsCustom extends Items{
    //添加商品信息的擴展屬性
}

這里ItemsCustom直接繼承的是Items,所以我們在Items中添加:

1.7CustomValidationMessages.properties

在classpath下新建CustomValidationMessages.properties文件,配置校驗錯誤信息:

1.8捕獲校驗錯誤信息

一個BindingResult對應一個pojo。

1.9在頁面顯示校驗錯誤信息

1.9.1方式一

在controller中將錯誤信息傳到頁面即可。

    //商品信息修改提交
    //在需要校驗的pojo前添加@Validated,在需要校驗的pojo后邊添加BindingResult bindingResult接收校驗出錯信息
    //注意:@Validated和BindingResult bindingResult是配對出現,並且形參順序是固定的(一前一后)。
    @RequestMapping("/editItemsSubmit")
    public String editItemsSubmit(Model model,HttpServletRequest request,Integer id,
            @Validated ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{
        
        //獲取校驗錯誤信息
        if(bindingResult.hasErrors()){
            List<ObjectError> allErrors=bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                System.out.println(objectError.getDefaultMessage());
            }
            //將錯誤信息傳到頁面
            model.addAttribute("allErrors", allErrors);
            //出錯,重新到商品頁面
            return "items/editItems";
        }
        //調用service更新商品信息,頁面需要將商品信息傳到此方法
        itemsService.updateItems(id, itemsCustom);
        
        //重定向到商品的查詢列表
//        return "redirect:queryItems.action";
        //頁面轉發
//        return "forward:queryItems.action";
        return "success";
    }

頁面顯示錯誤信息:

<c:if test="${allErrors!=null }">
    <c:forEach items="${allErrors }" var="error">
        ${error.defaultMessage }<br/>
    </c:forEach>
</c:if>

1.9.2方式二

修改Controller方法:

    //商品信息修改提交
    //在需要校驗的pojo前添加@Validated,在需要校驗的pojo后邊添加BindingResult bindingResult接收校驗出錯信息
    //注意:@Validated和BindingResult bindingResult是配對出現,並且形參順序是固定的(一前一后)。
    @RequestMapping("/editItemsSubmit")
    public String editItemsSubmit(Model model,HttpServletRequest request,Integer id,
            @Validated ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{
        
        //獲取校驗錯誤信息
        if(bindingResult.hasErrors()){
            List<ObjectError> allErrors=bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                System.out.println(objectError.getDefaultMessage());
            }//出錯,重新到商品頁面
            return "items/editItems";
        }
        //調用service更新商品信息,頁面需要將商品信息傳到此方法
        itemsService.updateItems(id, itemsCustom);
        
        //重定向到商品的查詢列表
//        return "redirect:queryItems.action";
        //頁面轉發
//        return "forward:queryItems.action";
        return "success";
    }

商品修改頁面顯示錯誤信息:

頁頭:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

在需要顯示錯誤信息地方:

<spring:hasBindErrors name="item">
<c:forEach items="${errors.allErrors}" var="error">
    ${error.defaultMessage }<br/>
</c:forEach>
</spring:hasBindErrors>

<spring:hasBindErrors name="item">表示如果item參數綁定校驗錯誤下邊顯示錯誤信息。

1.10分組校驗

1.10.1需求

在pojo中定義校驗規則,而pojo是被多個controller所共用,當不同的controller方法對同一個pojo進行校驗,但是每個controller方法需要不同的校驗。

解決方法:

定義多個校驗分組(其實是一個java接口),分組中定義有哪些規則。

每個controller方法使用不同的校驗分組。

1.10.2校驗分組

/**
 * 校驗分組
 * @author Joanna.Yan
 *
 */
public interface ValidGroup1 {
    //接口中不需要定義任何方法,僅是對不同的校驗規則進行分組
    //此分組只校驗商品名稱長度
}
/**
 * 校驗分組
 * @author Joanna.Yan
 *
 */
public interface ValidGroup2 {
    //接口中不需要定義任何方法,僅是對不同的校驗規則進行分組
}

1.10.3在校驗規則中添加分組

1.10.4在controller方法中使用指定分組的校驗

1.10.4校驗注解

@Null   被注釋的元素必須為 null  

@NotNull    被注釋的元素必須不為 null  

@AssertTrue     被注釋的元素必須為 true  

@AssertFalse    被注釋的元素必須為 false  

@Min(value)     被注釋的元素必須是一個數字,其值必須大於等於指定的最小值  

@Max(value)     被注釋的元素必須是一個數字,其值必須小於等於指定的最大值  

@DecimalMin(value)  被注釋的元素必須是一個數字,其值必須大於等於指定的最小值  

@DecimalMax(value)  被注釋的元素必須是一個數字,其值必須小於等於指定的最大值  

@Size(max=, min=)   被注釋的元素的大小必須在指定的范圍內  

@Digits (integer, fraction)     被注釋的元素必須是一個數字,其值必須在可接受的范圍內  

@Past   被注釋的元素必須是一個過去的日期  

@Future     被注釋的元素必須是一個將來的日期  

@Pattern(regex=,flag=)  被注釋的元素必須符合指定的正則表達式  

Hibernate Validator 附加的 constraint  

@NotBlank(message =)   驗證字符串非null,且長度必須大於0  

@Email  被注釋的元素必須是電子郵箱地址  

@Length(min=,max=)  被注釋的字符串的大小必須在指定的范圍內  

@NotEmpty   被注釋的字符串的必須非空  

@Range(min=,max=,message=)  被注釋的元素必須在合適的范圍內

2.數據回顯

2.1什么是數據回顯

提交后,如果出現錯誤,將剛才提交的數據回顯到剛才的提交頁面。

2.2pojo數據回顯方法

springmvc默認對pojo數據進行回顯,springmvc自動將形參中的pojo重新放回request域中,request的key為pojo的類名(首字母小寫),如下:

controller方法:

    @RequestMapping("/editItemSubmit")
    public String editItemSubmit(Integer id,ItemsCustom itemsCustom)throws Exception{

springmvc自動將itemsCustom放回request,相當於調用下邊的代碼:

model.addAttribute("itemsCustom", itemsCustom);

jsp頁面:

頁面中的從“itemsCustom”中取數據。

如果key不是pojo的類名(首字母小寫),可以使用@ModelAttribute完成數據回顯。

@ModelAttribute作用如下:

(1)綁定請求參數到pojo並且暴露為模型數據傳到視圖頁面。

此方法可實現數據回顯效果。

// 商品修改提交
    @RequestMapping("/editItemSubmit")
    public String editItemSubmit(Model model,@ModelAttribute("item") ItemsCustom itemsCustom)

頁面:

<tr>
    <td>商品名稱</td>
    <td><input type="text" name="name" value="${item.name }"/></td>
</tr>
<tr>
    <td>商品價格</td>
    <td><input type="text" name="price" value="${item.price }"/></td>
</tr>

如果不用@ModelAttribute也可以使用model.addAttribute("item", itemsCustom)完成數據回顯。

(2)將方法返回值暴露為模型數據傳到視圖頁面

//商品分類
    @ModelAttribute("itemtypes")
    public Map<String, String> getItemTypes(){
        
        Map<String, String> itemTypes = new HashMap<String,String>();
        itemTypes.put("101", "數碼");
        itemTypes.put("102", "母嬰");
        
        return itemTypes;
    }

頁面:

商品類型:
<select name="itemtype">
    <c:forEach items="${itemtypes }" var="itemtype">
        <option value="${itemtype.key }">${itemtype.value }</option>        
    </c:forEach>
</select>

 

2.3簡單類型數據回顯

最簡單方法使用model。

//簡單數據類型回顯
 model.addAttribute("id", id);

3.異常處理器

3.1異常處理思路

系統中異常包括兩類:預期異常和運行時異常RuntimeException,前者通過捕獲異常從而獲取異常信息,后者主要通過規范代碼開發、通過測試手段減少運行時異常的發生。

系統的dao、service、controller出現異常都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進行異常處理,如下圖:

springmvc提供全局異常處理器(一個系統只有一個異常處理器)進行統一異常處理。

3.2自定義異常類

對不同的異常類型定義異常類,繼承Exception。

package joanna.yan.ssm.exception;
/**
 * 系統自定義異常類,針對預期的異常。需要在程序中拋出此類異常。
 * @author Joanna.Yan
 *
 */
public class CustomException extends Exception{
    //異常信息
    public String message;

    public CustomException(String message) {
        super();
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
}

3.3全局異常處理器

思路:

系統遇到異常,在程序中手動拋出,dao拋給service、service拋給controller、controller拋給前端控制器,前端控制器調用全局異常處理器。

全局異常處理器處理思路:

解析出異常類型

如果該異常類型是系統自定義的異常,直接取出異常信息,在錯誤頁面展示

如果該異常類型不是系統自定義的異常,構造一個自定義的異常類型(信息為“未知錯誤”)

springmvc提供一個HandlerExceptionResolver接口。

package joanna.yan.ssm.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class CustomExceptionResolver implements HandlerExceptionResolver{
    /*
     * ex:系統拋出的異常
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse repsonse, Object handler, Exception ex) {
        //handler就是處理器適配器要執行的Handler對象(只有一個method)
        //1.解析出異常類型
        //2.如果該異常類型是系統自定義的異常,直接取出異常信息,在錯誤頁面展示
        //3.如果該異常類型不是系統自定義的異常,構造一個自定義的異常類型(信息為“未知錯誤”)
        CustomException customException=null;
        if(ex instanceof CustomException){
            customException=(CustomException)ex;
        }else{
            customException=new CustomException("未知錯誤");
        }
        //錯誤信息
        String message=customException.getMessage();
        ModelAndView modelAndView=new ModelAndView();
        //將錯誤信息傳到頁面
        modelAndView.addObject("message", message);
        //指向錯誤頁面
        modelAndView.setViewName("error");
        return modelAndView;
    }

}

3.4錯誤頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>錯誤提示</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

3.5在springmvc.xml配置全局異常處理器

    <!-- 全局異常處理器 
         只要實現HandlerExceptionResolver接口就是全局異常處理器
    -->
    <bean class="joanna.yan.ssm.exception.CustomExceptionResolver"></bean>

3.6異常測試

在controller、service、dao中任意一處需要手動拋出異常。

如果是程序中手動拋出的異常,在錯誤頁面中顯示自定義的異常信息,如果不是手動拋出異常說明是一個運行時異常,在錯誤頁面只顯示“未知錯誤”。

在商品修改的controller方法中拋出異常。

在service接口中拋出異常:

如果與業功能相關的異常,建議在service中拋出異常。

與業務功能沒有關系的異常(比如形參校驗),建議在controller中拋出。

上邊的功能,建議在service中拋出異常。

 4.圖片上傳

4.1配置虛擬目錄

在Tomcat上配置圖片虛擬目錄,在tomcat下conf/server.xml中添加:

<Context docBase="F:\develop\upload\temp" path="/pic" reloadable="false"/>

訪問http://localhost:8080/pic即可訪問F:\develop\upload\temp下的圖片。

注意:在圖片虛擬目錄中,一定要將圖片目錄分級創建(提高I/O性能),一般我們采用按日期(年、月、日)進行分級創建。

4.2配置解析器

springmvc中對多部件類型解析。

 

在頁面form中提交enctype="multipart/form-data"的數據時,需要springmvc對multipart類型的數據進行解析。

在springmvc.xml中配置multipart類型解析器。

    <!-- 文件上傳 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設置上傳文件的最大尺寸為5MB -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>

4.3加入上傳圖片的jar

上邊的解析器內部使用下邊的jar進行圖片上傳。

4.4上傳圖片

controller:

    @RequestMapping("/editItemsSubmit")
    public String editItemsSubmit(
            Model model,
            HttpServletRequest request,
            Integer id,
            @ModelAttribute("items") @Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom,
            BindingResult bindingResult,
            MultipartFile items_pic//接收商品圖片
            ) throws Exception{
        
        //獲取校驗錯誤信息
        if(bindingResult.hasErrors()){
            List<ObjectError> allErrors=bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                System.out.println(objectError.getDefaultMessage());
            }
            //將錯誤信息傳到頁面
            model.addAttribute("allErrors", allErrors);
            //可以直接使用model將提交的pojo回顯到頁面
            model.addAttribute("items", itemsCustom);
            //簡單數據類型回顯
            model.addAttribute("id", id);
            //出錯,重新到商品頁面
            return "items/editItems";
        }
        
        //上傳圖片
        String originalFilename=items_pic.getOriginalFilename();
        if(items_pic!=null&&originalFilename!=null&&originalFilename.length()>0){
            //存儲圖片的物理路徑
            String pic_path="F:\\develop\\upload\\temp\\";
            //新的圖片名稱
            String newFileName=UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
            //新圖片
            File newFile=new File(pic_path+newFileName);
            //將內存中的數據寫入磁盤
            items_pic.transferTo(newFile);
            //將新圖片名稱寫到itemsCustom中
            itemsCustom.setPic(newFileName);
        }
        
        //調用service更新商品信息,頁面需要將商品信息傳到此方法
        itemsService.updateItems(id, itemsCustom);
        
        //重定向到商品的查詢列表
//        return "redirect:queryItems.action";
        //頁面轉發
//        return "forward:queryItems.action";
        return "success";
    }

頁面:

form添加enctype="multipart/form-data",file的name與controller形參一致:

<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${items.id }"/>
修改商品信息:
<table width="100%" border=1>
<tr>
    <td>商品名稱</td>
    <td><input type="text" name="name" value="${items.name }"/></td>
</tr>
<tr>
    <td>商品價格</td>
    <td><input type="text" name="price" value="${items.price }"/></td>
</tr>
<tr>
    <td>商品生產日期</td>
    <td><input type="text" name="createtime" value="<fmt:formatDate value="${items.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
</tr>
<tr>
    <td>商品圖片</td>
    <td>
        <c:if test="${items.pic !=null}">
            <img src="/pic/${items.pic}" width=100 height=100/>
            <br/>
        </c:if>
        <input type="file"  name="items_pic"/> 
    </td>
</tr>
<tr>
    <td>商品簡介</td>
    <td>
    <textarea rows="3" cols="30" name="detail">${items.detail }</textarea>
    </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>

</form>

5.Json數據交互

5.1為什么要進行json數據交互

json數據格式在接口調用中、html頁面中較常用,json格式比較簡單,解析還比較方便。

比如:webserivce接口,傳輸json數據。

5.2springmvc進行json交互

(1)請求json、輸出json,要求請求的是json串,所以在前端頁面中需要將請求的內容轉成json,不太方便。

(2)請求key/value、輸出json。次方法比較常用。

5.3環境准備 

5.3.1加載json轉換的jar包

springmvc中使用jackson的包進行json轉換(@requestBody和@responseBody使用下邊的包進行json轉換),如下:

5.3.2配置json轉換器

在classpath/springmvc.xml,注解適配器中加入messageConverters

!--注解適配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
        <list>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
        </list>
        </property>
    </bean>

注意:如果使用<mvc:annotation-driven/>則不用定義上邊的內容。

5.4json交互測試

這里分輸入json串輸出json串和輸入key/value輸出json兩種情況進行測試。

新建jsonTest.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>json交互測試</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
      <script type="text/javascript">
      //請求json,輸出的是json
      function requestJson(){
          $.ajax({
              type:'post',
              url:'${pageContext.request.contextPath }/requestJson.action',
              contentType:'application/json;charset=utf-8',
              //數據格式是json串,商品信息
              data:'{"name":"手機","price":999}',
              success:function(data){//返回json結果
                  alert(data);
              }
          });
      }
      
      //請求key/value,輸出的是json
      function responseJson(){
          $.ajax({
              type:'post',
              url:'${pageContext.request.contextPath }/responseJson.action',
              //請求是key/value這里不需要指定contentType,因為默認就是key/value類型
              //contentType:'application/json;charset=utf-8',
              //數據格式是json串,商品信息
              data:'name=手機&price=999',
              success:function(data){//返回json結果
                  alert(data);
              }
          });
      }
      </script>
  </head>
  
  <body>
    <input type="button" onclick="requestJson()" value="請求json,輸出的是json"/>
     <input type="button" onclick="responseJson()" value="請求key/value,輸出的是json"/>
  </body>
</html>

新建Controller:

package joanna.yan.ssm.controller;

import joanna.yan.ssm.po.ItemsCustom;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class JsonTest {
    //請求json串(商品信息),輸出的豎json(商品信息)
    //@RequestBody將請求的商品信息的json串轉成itemsCustom對象
    //@ResponseBody將itemsCustom轉成json輸出
    @RequestMapping("/requestJson")
    public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){
        
        return itemsCustom;
    }
    
    //請求key/value,輸出的豎json
    @RequestMapping("/responseJson")
    public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){
        
        return itemsCustom;
    }
}

(1)測試輸入json串輸出是json串

(2)測試輸入key/value輸出是json串

6.RESTful支持

6.1什么是RESTful

RESTful架構,是目前最流行的一種互聯網軟件架構。它結構清晰、符合標准、易於理解、擴展方便,所以得到越來越多網站的采用。

RESTful(即Representational State Transfer的縮寫)其實是一個開發理念,是對http的很好的詮釋。

(1)對url進行規范,寫RESTful格式的url

非REST的url:http://...../queryItems.action?id=001&type=T01

REST的url風格:http://..../items/001

  特點:url簡潔,將參數通過url傳到服務端

(2)對http的方法規范

不管是刪除、添加、更新...使用url是一致的,如果進行刪除,需要設置http的方法為delete,同理添加...

后台controller方法:判斷http方法,如果是delete執行刪除,如果是post執行添加。

(3)對http的contentType規范

請求時指定contentType,要json數據,設置成json格式的type...

目前完全實現RESTful的系統很少,一般只實現(1)、(3),對於(2)我們一個方法經常會同時存在增刪改查,實現起來太費勁了。

下面舉例實現(1)、(2)。

6.2REST的例子

6.2.1需求

查詢商品信息,返回json數據。

6.2.2controller

定義方法,進行url映射使用REST風格的url,將查詢商品信息的id傳入controller。

輸出json使用@ResponseBody將java對象輸出json。

    //查詢商品信息,輸出json
    ///itemsView/{id}里面的{id}表示占位符,通過@PathVariable獲取占位符中的參數
    //如果占位符中的名稱和形參名一致,在@PathVariable可以不指定名稱
    @RequestMapping("/itemsView/{id}")
    public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id) throws Exception{
        ItemsCustom itemsCustom=itemsService.findItemsById(id);
        return itemsCustom;
    }

6.2.3REST方法的前端控制器配置

在web.xml增加配置:

  <!-- springmvc前端控制器,rest配置  -->
  <servlet>
      <servlet-name>springmvc_rest</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring/springmvc.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>springmvc_rest</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>

6.3對靜態資源的解析

配置前端控制器的url-parttern中指定/,對靜態資源的解析出現問題:

在springmvc.xml中添加靜態資源解析方法。

    <!-- 靜態資源的解析 
         包括:js、css、img...
    -->
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/img/" mapping="/img/**"/>

如果此文對您有幫助,微信打賞我一下吧~ 

 


免責聲明!

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



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