iT邦幫忙

2024 iThome 鐵人賽

DAY 28
0
Software Development

從Servlet到Spring MVC系列 第 28

Day27 Spring MVC - Request Handling (I)

  • 分享至 

  • xImage
  •  

Day27 Spring MVC - Request Handling (I)

前言

昨日完成Spring MVC的快速入門,我們複習一下整個過程

  1. 透過DispatcherServlet將Tomcat收到的請求導到Spring MVC框架中
  2. 透過HandlerMapping映射對應的處理方法(Controller)
  3. 透過HandlerAdapter封裝請求參數轉由對應Controller
  4. 透過ViewResolver處理响應的資訊與頁面

0.創建module

(1) 創建module day27

https://ithelp.ithome.com.tw/upload/images/20241012/20128084mAWkrOuL8N.png

(2) 創建java資料夾

https://ithelp.ithome.com.tw/upload/images/20241012/20128084l5A5DjHMEU.png
https://ithelp.ithome.com.tw/upload/images/20241012/20128084lZuEcBEQK7.png

(3) 設定maven

  <properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version> 6.1.13</version>
    </dependency>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>6.0.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

(4) web.xml設定DispatcherServlet

<display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

(5) springmvc.xml

https://ithelp.ithome.com.tw/upload/images/20241012/201280842894wXk6WF.png

(6) 設定component scan

在springmvc.xml中設定

<context:component-scan base-package="com.swj"></context:component-scan>

(7) 配置視圖解析器 (選配)

若需要使用jsp、thymeleaf 等再配置,接下來的日子不會提到這個部分

<!-- view resolver setting   -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

(8) 佈署至Tomcat

https://ithelp.ithome.com.tw/upload/images/20241012/20128084FvgrqbP02B.png
https://ithelp.ithome.com.tw/upload/images/20241012/201280845Sdgsuip5N.png
https://ithelp.ithome.com.tw/upload/images/20241012/20128084XQF7SstMLv.png

(9) 訪問localhost:8080

會看到initializing Servlet的字樣
https://ithelp.ithome.com.tw/upload/images/20241012/201280845tfgrqkwwm.png

一、Path Matching

Spring MVC中路徑匹配設置交給@RequetMapping

(1) 精確匹配

完整路徑匹配ex.\hello\world

(2) 模糊匹配

  • /*單層任意字串,ex.\haha\a\haha\abc
  • /** 任意層任意字串

demo

創建HelloController

@Controller
public class HelloController {
    //1.精確匹配
    @RequestMapping("/hello/world")
    @ResponseBody
    public String hello(){
        return "Hello World";
    }

    //2.模糊匹配
//    @RequestMapping("/world/*")
    @RequestMapping("/world/**")
    @ResponseBody
    public String world(){
        return "World Hello ";
    }
}

https://ithelp.ithome.com.tw/upload/images/20241012/20128084bCKmhbgaW2.png

(3) RequestMapping

class中的方法重複的路徑可以放置在Controller

  • 標記在方法上
//放置在方法中
@Controller
public class EmpController {

    @RequestMapping("/emp/create'")
    public String create(){
        return "Emp create";
    }
    @RequestMapping("/emp/insert'")
    public String insert(){
        return "Emp insert";
    }

}

  • 標記在class上
@RequestMapping("/emp")
@Controller
public class EmpController {

    @RequestMapping("/create")
    public String create(){
        return "Emp create";
    }
    @RequestMapping("/insert")
    public String insert(){
        return "Emp insert";
    }
}

(4) 請求方式設置

  • 註解內設置
@RequestMapping(value = "/create",method = RequestMethod.GET)
public String create(){
    return "Emp create";
}
  • 註解設置
@GetMapping("/insert'")
public String insert(){
    return "Emp insert";
}

二、Cookie Handling

Spring MVC在處理請求參數時已為我們封裝了Cookie,我們只需要透過@CookieValue就可以拿到Cookie,當然也可以透過傳入原生API HttpServletRequest,使用for迴圈遍歷取值

@Controller
@ResponseBody
public class CookieController {

    @RequestMapping("CreateCookie")
    public String CookieTest(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        return "CreateCookie:"+session.getId();
    }

    @RequestMapping("GetCookie")
    public String GetCookie(@CookieValue(name = "JSESSIONID",value = "",required = false) String sessionid){
        System.out.println(sessionid);
        return "GetCookie:"+sessionid;
    }
}

Demo

https://ithelp.ithome.com.tw/upload/images/20241012/20128084UkXX037tL2.png
https://ithelp.ithome.com.tw/upload/images/20241012/20128084lcT5uu0Bsx.png

三、Request Header Handling

如果是要取得Header裡面的資料,可以透過@RequestHeader取得

@ResponseBody
@Controller
public class HeaderController {
    
    @RequestMapping("GetHeader")
    @ResponseBody
    public String GetHeader(@RequestHeader(name = "host") String host){
        System.out.println("GetHeader:"+host);
        return "GetHeader:" + host;
    }
}

Dedmo

https://ithelp.ithome.com.tw/upload/images/20241012/20128084F25Nu6TxEE.png

Reference


上一篇
Day26 Spring MVC - Concept
下一篇
Day28 Spring MVC - Request Handling (II)
系列文
從Servlet到Spring MVC36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言