這篇文章對Spring 的MVC @RequestMapping講解的很清楚,摘記備忘.
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
@Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
@RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
@RequestMapping(value="/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}
@RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
}
@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}
DispatcherServle < servlet >
< servlet - name > dispatcher </ servlet - name >
< servlet - class > org.springframework.web.servlet.DispatcherServlet </ servlet - class >
< load - on - startup > 1 </ load - on - startup >
</ servlet >
< servlet - mapping >
< servlet - name > dispatcher </ servlet - name >
< url - pattern >* . do </ url - pattern >
</ servlet - mapping >
/appointments /new.do
映射方法是 getNewForm()
/appointments.do
GET請求映射方法是 get()
POST請求映射方法是 add(@Valid AppointmentForm appointment, BindingResult result)
通過參數條件縮小路徑映射
@RequestMapping(value = "/path", params="myParam=myValue")public void add(){...} http://localhost:8080/DynamicWebProject/hao/hello.do?myParam=myValue
URL中只有存在myParam=myValue參數時才被允許訪問路徑映射的方法
@RequestMapping(value = "/path", method = RequestMethod.POST, headers="content-type=text/*")public void add(){...} 只有在URL的頭資訊中包含有content-type=text/*(content-type=text/xml)的POST請求才能訪問add()方法
配合@RequestMapping使用的方法或註解
org.springframework.web.context.request.WebRequest或org.springframework.web.context.request.NativeWebRequest。通用請求參數允許訪問 request/session屬性,到原生Servlet / Portlet API的。
java.util.Locale 當前請求的地區設定,由解析器提供最具體的語言環境。
java.io.InputStream /java.io.Reader訪問請求的內容。這個值是原始的InputStream /Reader ,由Servlet API公開。
java.io.OutputStream /java.io.Writer產生響應的內容。這個值是原始的OutputStream /Writer,由Servlet API公開。
@ PathVariable註明擷取URI模板變數的參數。
@ RequestParam註明為擷取特定的servlet請求參數的參數。
@ RequestHeader 訪問特定的servlet請求的HTTP頭的參數。參數值轉換為聲明的方法的參數類型。
@ RequestBody 訪問HTTP請求體參數。參數值轉換為所聲明的方法的參數類型使用HttpMessageConverters。
HttpEntity <。>訪問servlet請求的HTTP頭和內容。請求流將被轉換為實體採用HttpMessageConverters。
java.util.Map/ org.springframework.ui.Model /org.springframework.ui.ModelMap為豐富的隱含模型,暴露在Web視圖
org.springframework.validation.Errors / org.springframework.validation.BindingResult
org.springframework.web.bind.support.SessionStatus
轉自http://www.blogjava.net/wmcoo/articles/333428.html