請參考Day27 module
Spring MVC封裝了Servlet request parameter,可以處理query string的請求參數,也可以處理post傳來的form data
@Controller
public class RequestParamController {
@GetMapping("RequestParamDemo")
public String RequestParamPage(){
return "RequestParamDemo";
}
@PostMapping("RequestParamDemoPost")
@ResponseBody
public String RequestParamDemoPost(@RequestParam Map<String, String> params){
System.out.println("====RequestParamDemoPost====");
for (String key : params.keySet()) {
System.out.println(key + ":" + params.get(key));
}
System.out.println("====RequestParamDemoPost====");
return "get POST data";
}
@GetMapping("RequestParamDemoGet")
@ResponseBody
public String RequestParamDemoGet(@RequestParam("account") String account,@RequestParam("password`") String password){
System.out.println("====RequestParamDemoGet====");
System.out.println("account:" + account);
System.out.println("password:" + password);
System.out.println("====RequestParamDemoGet====");
return "get GET data";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>RequestParamDemo</title>
</head>
<body>
<h3>POST method</h3>
<form action="RequestParamDemoPost" method="post">
帳號:<input name="account" type="text"><br>
密碼:<input name="password" type="password"><br>
<input type="submit" value="submit">
</form>
<br>
<h3>GET method</h3>
<form action="RequestParamDemoGet" method="get">
帳號:<input name="account" type="text"><br>
密碼:<input name="password" type="password"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
先訪問RequestParamDemo,再依次執行POST與GET
case1
case2
在RESTful的web應用中會透過URL請求路徑的內容當作參數取出來應用,Spring MVC 提供@PathVariable讓我們可以方便從URL中取出對應的參數。
@Controller
public class PathVariableController {
@GetMapping(path = "/emp/{id}/{name}")
@ResponseBody
public String pathVariableDemo(@PathVariable("id") int id, @PathVariable("name") String name){
return "pathVariableDemo:id"+id+":name"+name;
}
}
在前後端分離的專案中,最重要的莫過於JSON的處理。Spring MVC透過@RequestBody幫我們處理JSON直接轉成物件方便後續操作。支援JSON需要在Spring設定檔中設定處理JSON,否則會收到HTTP Status 415 – Unsupported Media Type的訊息。官網設定請點我
maven pom 引入相關JSON套件
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names -->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.17.1</version>
</dependency>
spring設定檔配置
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true"
p:simpleDateFormat="yyyy-MM-dd"
p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule"/>
Employee
public class Employee {
private String empId;
private String empName;
//getter setter toString略
}
JsonController
@Controller
public class JsonController {
@PostMapping(path = "JsonDemo")
@ResponseBody
public String JsonDemo(@RequestBody Employee emp){
System.out.println(emp);
return "JsonDemo";
}
}
這邊使用Postman進行後端API測試
Spring MVC提供Method Arguments,讓我們可以方便調用原生的Servlet API
@Controller
public class NativeController {
@ResponseBody
@RequestMapping("NativeApi")
public String NativeApi(HttpServletRequest request, HttpServletResponse response){
String method = request.getMethod();
System.out.println(method);
Cookie cookie = new Cookie("NativeApi", "haha");
response.addCookie(cookie);
return "DemoNativeApi";
}
}
在使用傳統的jsp、themleaf等server side render頁面的技術就必須透過shared object來幫助我們數據傳遞到頁面中
Spring MVC提供了Model、ModelMap、ModelAndView的方式作為傳遞數據物件的封裝,看完下面範例就知道如何使用了
@Controller
public class SharedObjectController {
@GetMapping("ModelDemo")
public String RequestDemo(Model model){
model.addAttribute("msg", "Hello World");
return "RequestDemo";
}
@GetMapping("ModelMapDemo")
public String RequestDemo(ModelMap map){
map.put("msg", "ModelMapDemo");
return "RequestDemo";
}
@GetMapping("ModelAndViewDemo")
public ModelAndView RequestDemo(ModelAndView modelAndView){
modelAndView.addObject("msg", "ModelAndViewDemo");
modelAndView.setViewName("RequestDemo");
return modelAndView;
}
}
可以透過傳入HttpSession來調用session物件,在頁面可以透過sessionScope來調用設置參數
@GetMapping("SessionDemo")
public String SessionDemo(HttpSession session){
session.setAttribute("msg", "SessionDemo");
return "SessionDemo";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SessionDemo</title>
</head>
<body>
${sessionScope.msg}
</body>
</html>
Spring MVC初始化容器時已將ServletContext註冊到容器當中,可以直接注入調用,在頁面中可以透過applicationScope調用設置參數
@Autowired
private ServletContext servletContext;
@GetMapping("ServletContextDemo")
public String ServletContextDemo(){
servletContext.setAttribute("msg", "ServletContextDemo");
return "ServletContextDemo";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SessionDemo</title>
</head>
<body>
${applicationScope.msg}
</body>
</html>