【Spring】(14)Spring MVC 使用註解 + RESTful風格

一、簡單使用註解版

使用註解,減少了很多代碼,以後開發會經常用到。

項目結構

在這裏插入圖片描述

web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--配置DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--關聯一個SpringMVC的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--服務器啓動的時候就啓動-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <!--  "/"匹配所有的請求不包括.jsp。"/*"匹配所有的請求包括.jsp -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

配置文件springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 掃描包,讓指定包下的註解生效,有IoC容器統一管理 -->
    <context:component-scan base-package="com.shengjava.web"/>
    <!--開啓註解掃描-->
    <mvc:annotation-driven/>
    <!--在web開發中,我們一般存在靜態資源css,js,img。。。-->
    <mvc:default-servlet-handler/>

    <!--視圖解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前綴-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--後綴-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

JSP頁面test.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test.jsp</title>
</head>
<body>
${msg}
${m}
</body>
</html>

HelloController類

@GetMapping("/hello")註解,代表的是get請求的路徑。還有@PostMapping代表post請求的路徑。如果是@RequestMapping,則get和post都可以訪問到。

使用的是Model和ModelMap,可以進行模型數據的綁定,然後直接return需要跳轉的頁面(該頁面位置是由,springmvc-servlet.xml中的視圖解析器下配置的前綴和後綴拼接而成的)。此時可以使用el表達式直接顯示出綁定在Model和ModelMap中的數據。

這裏因爲return時就是直接到頁面了,所以不需要用ModelAndView。常用的是Model。

對比:

  • Model:只有幾個方法只適合用於儲存數據,簡化了新手對它操作和理解。
  • ModelMap:繼承了LinkedMap,除了實現了自身的一些方法,同樣的繼承L inkedMap的方法和特性;
  • ModelAndView:可以在儲存數據的同時,可以進行設置返回的邏輯視圖,進行控制展示層的跳轉。
@Controller
public class HelloController {
    @GetMapping("/hello")
    public String hello(Model m, ModelMap mp) {
        // 模型數據(可以使用這兩個,ModelAndView不能使用了)
        m.addAttribute("m", "hello Spring MVC");
        mp.put("msg", "hello Spring MVC");
        // 視圖數據
        return "test";
    }
}

部署tomcat運行,頁面中會輸出:

hello Spring MVC hello Spring MVC

二、RESTful風格

1.概念

RestFul就是一個資源定位及資源操作的風格,不是標準也不是協議,只是一種風格,基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。

2.功能

資源:互聯網所有的事物都可以被抽象爲資源

資源操作:使用POST、DELETE、PUT、GET使用不同方法對資源進行操作。分別對應:添加、刪除、修改、查詢

傳統操作資源:通過不同的參數來實現不同的效果

http://127.0.0.1/item/query.action?page=1&count=10 查詢 GET(查詢第1頁的10條數據)

使用RestFul風格

http://127.0.0.1/item/1/10 查詢 GET(使用RestFul風格)

3.使用

在Spring MVC中可以使用@PatnVariable註解,讓方法參數的值對應綁定到一個URL模板變量上。

在上面案例的controller包下新增一個類RestfulController。

當用get方式訪問/restful01/aaa/bbb則會返回aaabbb。如果get訪問/restful02/1/2則返回3.

@Controller
public class RestfulController {
    /** 註解@ResponseBody將返回的數據轉換成json格式 */
    @ResponseBody
    @GetMapping("/restful01/{s1}/{s2}")
    public String restful01(@PathVariable String s1, @PathVariable String s2) {
        return s1+s2;
    }

    @ResponseBody
    @GetMapping("/restful02/{n1}/{n2}")
    public String restful02(@PathVariable int n1, @PathVariable int n2) {
        return "" + (n1 + n2);
    }
}

4.註解

Spring MVC的@RequestMapping註解能夠處理HTTP請求的方法,比如GET,PUT,POST,DELETE以及PATCH。這個註解可以設置http請求的方法,例如,@RequestMapping(method = RequestMethod.XXX)

所有的地址請求默認都會是HTTP GET類型的。

方法級別的註解有如下幾個:組合註解

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

@XXXMapping是一個組合註解

相當於@RequestMapping(method = RequestMethod.XXX)的一個快捷方式,通常使用這個!

三、請求轉發與重定向

1.請求轉發

Spring MVC在配置了視圖解析器後,默認情況下controller的方法return就是請求轉發。

如下代碼:代表訪問/hello,然後是轉發到test。

@GetMapping("/hello")
    public String hello(Model m, ModelMap mp) {
        return "test";
    }

2.重定向

如果return時,前面加上"redirect:"則時重定向。

如下代碼:代表訪問/hello,然後重定向到了test路徑

    @GetMapping("/hello")
    public String hello(Model m, ModelMap mp) {
        return "redirect:test";
    }

四、其他常用註解

1.接受請求參數

我們接受html頁面傳來的請求信息。可以直接在方法的參數中設置(參數名要和html傳來的參數名一致),Spring MVC會幫我們注入值。

例如,訪問/addUser?username=zhangsan&password=123456

如下代碼:後臺可以獲取到用戶的請求信息,並且可以打印出傳入的參數。返回到頁面顯示的值爲"{msg=success}"。

推薦前端接受的參數前面加上@RequestParam註解,@RequestParam註解如果什麼都不加,那麼參數名默認就是變量名。如果設置爲@RequestParam(“password”),那麼參數password從前端獲取的屬性值則爲註解括號中的值。

    @ResponseBody
    @GetMapping("/addUser")
    public String addUser(@RequestParam String username, @RequestParam("password") String password) {
        System.out.println("前端輸入的參數:username:" + username + " password:" + password);
        return "add success";
    }

如果前臺傳來的是一個對象。例如,用戶註冊有很多個字段,那麼我們的參數中可以頁設置爲一個對象,如下形式例如:

    @ResponseBody
    @GetMapping("/addUser")
    public String addUser(User u) {
        return "add success";
    }

相關

我的該分類的其他相關文章,請點擊:【Spring + Spring MVC + MyBatis】文章目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章