天天看點

pringMVC教程6[Restful和攔截器]

文章目錄

   一、Restful風格

   二、攔截器

       1.簡介

       2.使用

           2.1定義攔截器

           2.2配置攔截條件

           2.3測試

       3.攔截器工作原理

一、Restful風格

 RESTful是一種軟體設計規範,是用戶端和服務端進行資料互動的一個規範。 早期使用JSP頁面開發網頁時,資料互動基本都是通過表單送出,然後通過内置對象傳遞。當HTML5興起,移動網際網路興起,網站後端服務,不僅要考慮PC端的網頁,也要考慮移動端資料的展示、小程式、HTML5頁面等。如果需要多個終端(Android、iOS、小程式、Pad、HTML5頁面)共用一個後端,一般來說主流方案就是使用JSON進行傳遞。RESTful則規範了請求的URL,注意RESTful隻是一個規範,不是一個技術。

在RESTful中:

   一個URL操作一個資源

   請求的URL中不能有動詞

   使用HTTP的請求方式來描述請求行為,例如:

送出方式 位址 說明

GET(查) http://localhost:8080/book/1 查詢id為1的書

POST(增) http://localhost:8080/book/1 添加一本書,書的id為1

DELETE(删) http://localhost:8080/book/1 删除id為1的書

PUT(改) http://localhost:8080/book/1 修改id為1的書

 在RESTful接口中,所有的方法都是傳回JSON,沒有傳回頁面的(ModelAndView),是以,所有的方法上都需要添加@ResponseBody注解。一個替代的簡化方案,是使用 @RestController 代替@Controller。@RestController實際上是一個組合注解,是@Controller和@ResponseBody的組合:

pringMVC教程6[Restful和攔截器]
案例代碼

/**
 * RestFul
 * @author dpb【波波烤鴨】
 *
 */
@RestController
public class UserController {
    @Autowired
    UserService userService;

    /** * 查詢所有、分頁查詢、條件查詢 * 一般都是直接使用資源的複數形式來做路徑 * * @return */
    @GetMapping("/users")
    public List<User> getAllUser(@RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "4") Integer count) {
        return userService.getAllUser(page, count);
    }

    /**
     * * 按照id查詢 例如 http://localhost:8080/user/1 表示查詢id為1的使用者 * * @param id
     * * @return
     */
    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.getUserById(id);
    }

    /** * 使用POST請求來完成添加功能 * * @param user * @return */
    @PostMapping("/user")
    public RespBean addUser(@RequestBody User user) {
        int result = userService.addUser(user);
        if (result == 1) {
            return RespBean.ok("添加成功!");
        }
        return RespBean.error("添加失敗!");
    }

    @DeleteMapping("/user/{id}")
    public RespBean deleteUserById(@PathVariable Integer id) {
        int result = userService.deleteUserById(id);
        if (result == 1) {
            return RespBean.ok("删除成功!");
        }
        return RespBean.error("删除失敗!");
    }

    @PutMapping("/user")
    public RespBean updateUserById(@RequestBody User user) {
        int result = userService.updateUserById(user);
        if (result == 1) {
            return RespBean.ok("修改成功!");
        }
        return RespBean.error("修改失敗!");
    }
}      

二、攔截器

1.簡介

 SpringMVC中的攔截器對應了Web基礎中的過濾器。

攔截器和過濾器的差別:

序号 差別

1 一般來說,如果使用了SpringMVC架構,然後有攔截器的需求,

建議使用攔截器而不是過濾器

2 過濾器依賴于Servlet容器,而攔截器是SpringMVC自帶的,不依賴容器

3 攔截器的功能更為強大,因為攔截器是一種AOP風格的過濾器

(實際上這個功能過濾器也能實作,隻是沒有攔截器這麼簡單明了)

2.使用

2.1定義攔截器

/**
 * 自定義攔截器
 * @author dpb【波波烤鴨】
 *
 */
public class FirstIntercepter implements HandlerInterceptor{

    /**
     * 進入Handler之前調用的方法
     * 處理:
     *    用于身份确認和授權
     *    比如确認目前請求是否登陸,如果登陸就方法,否則攔截跳回登陸界面
     * @return
     *    true 放過
     *    false 攔截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("preHandle 執行了...");
        return true;
    }

    /**
     * 進入Handler之後,傳回ModelAndView對象之前執行
     * 可以修改調整的視圖
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        
        System.out.println("ModelAndView之前執行...");
        modelAndView.setViewName("/error.jsp");
        modelAndView.addObject("msg", "傳遞的資訊...");
    }

    /**
     * 執行完成Handler之後執行此方法,
     * 應用場景:
     *    統一異常處理,統一日志處理,資源釋放
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("執行完Handler到傳回用戶端之前執行...");
        
    }
}      

2.2配置攔截條件

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan base-package="com.dpb.*"></context:component-scan>
    
    <!-- 攔截器的配置 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- ** 表示目前目錄及其子目錄路徑 -->
            <mvc:mapping path="/**"/>
            <bean class="com.dpb.interceptor.FirstIntercepter"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>      

2.3測試

pringMVC教程6[Restful和攔截器]
pringMVC教程6[Restful和攔截器]
pringMVC教程6[Restful和攔截器]

3.攔截器工作原理

pringMVC教程6[Restful和攔截器]