Spring Framework 6 教學 (十一) MVC 進化

  • Post category:MVC / Spring 6

Spring Framework 6 MVC 若要啟用 @GetMapping @PostMapping 要再設定檔中,增加設定如下:

http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
 <mvc:annotation-driven />   

完整內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
         http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


   
   
 <mvc:annotation-driven />   
 <context:component-scan base-package="com.tcg.action" />


  <bean name="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Spring Framework 6 MVC 在 Controller 中使用 @GetMapping @PostMapping

@GetMapping 等同 @RequestMapping (method = RequestMethod.GET)

@PostMapping 等同 @RequestMapping (method = RequestMethod.POST)

Spring Framework 6 MVC 在 Controller 中使用 @RequestParam

@RequestMapping("/login")
    public String login(
    @RequestParam(value="id", required=true) String id,
    @RequestParam(value="paswd", required=false) String paswd){
.......
}

Spring Framework 6 MVC 在 Controller 中使用 @PathVariable

@RequestMapping("/student/{id}")
    public String getDetails(@PathVariable(value="id") String id){
.......
}

Spring Framework 6 MVC 在 Controller 中使用 @ModelAttribute

@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") Employee employee) {
    

    return "employeeView";
}

Spring Framework 6 MVC 在 Controller 中使用 @SessionAttributes

package com.tcg.action;

@Controller
@SessionAttributes("carmemberid")
public class LoginAction {
@RequestMapping("login")
 public String hello(@RequestParam(value = "carmemberid" ) String carmemberid , 
 @RequestParam(value = "paswd", required = false ) String paswd
 , Model m) {
   
   
 String nextPage ="login";
 if(paswd!= null){
    m.addAttribute("paswd", paswd);//使用範圍 request
    m.addAttribute("carmemberid", carmemberid); //使用範圍 session
 }else{//使用者不存在
 nextPage ="reLogin";
 }
 return nextPage;
 }
  
  
}