@PathVariable舉例:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.df.test.pojo.Customer;
import com.df.test.service.ICustomerService;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private ICustomerService customerService;
@RequestMapping("/showUser1/{useId}")
public String toIndex(@PathVariable String useId, Model model) {
Customer customer = this.customerService.getUserById(Integer.parseInt(useId));
model.addAttribute("customer", customer);
return "showUser";
}
}
假設本項目的名稱叫做demo,上述控制器對應請求則是:
http://localhost:8080/demo/user/showUser1/1
該注解可以很方便獲取請求URL中的動態(tài)參數(shù),@PathVariable只有一個屬性value,String類型,表示標定的名稱,默認不傳遞時,綁定為同名的形參。所以上面的核心代碼也可以改為:
@RequestMapping("/showUser1/{useId}")
public String toIndex(@PathVariable(value = "useId") String useId1, Model model) {
Customer customer = this.customerService.getUserById(Integer.parseInt(useId1));
model.addAttribute("customer", customer);
return "showUser";
}
@RequestHeader以及@CookieValue這兩個注解用法類似,屬性也相同。
- @RequestHeader注解主要是將請求頭的信息區(qū)數(shù)據(jù),映射到功能處理方法的參數(shù)上。
- @CookieValue注解主要是將請求的Cookie數(shù)據(jù),映射到功能處理方法的參數(shù)上。
屬性說明:
- value屬性,指定請求頭綁定的名稱。String類型。
- required屬性,參數(shù)是否必須。boolean類型。
- defaultValue屬性,如果沒有傳參而使用的默認值。String類型。
@RequestMapping("/showUser1/{useId}")
public String toIndex(@PathVariable(value = "useId") String useId1,
@RequestHeader("User-agent") String userAgent,
@RequestHeader(value = "Accept") String[] accepts,
@CookieValue(value="JSESSIONID",defaultValue = "") String sessionId , Model model) {
Customer customer = this.customerService.getUserById(Integer.parseInt(useId1));
model.addAttribute("customer", customer);
return "showUser";
}
好了,以上是三個注解的基本用法,相對比較簡單,就不贅述了。