Spring MVC 学习笔记 第二章 Spring MVC注解
常用注解:
注解 | 说明 |
---|---|
@RequestMapping | Spring MVC通过@RequestMapping注解将URL请求与业务方法进行映射,在Handle的类定义处以及方法定义处都可以添加 |
@RequestMapping | 在类定义处添加,相当于客户端多了一层访问路径。 |
@Controller | 在类的定义处添加,将该类交给IoC容器管理,同时使其成为一个控制器,可以接受客户端请求。 |
代码实例:
package com.fw.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloHandler {
@RequestMapping("/index")
public String index(){
System.out.println("执行了index。。。");
return "index";
}
}
访问时需要通过以下URL:
http://localhost:8080/hello/index
一. @RequestMapping相关参数
1.value:指定URL请求的实际地址,是@RequestMapping的默认值。
注:以下两种方式是相同的。
@RequestMapping("/index")
@RequestMapping(value="/index")
2.method:指定请求的method类型,GET,POST,PUT,DELETE
@RequestMapping(value = "/index",method = RequestMethod.GET)
表示只能接受GET请求。
不添加的情况下,表示没有限制。
3.params:指定请求中必须包含默认参数,否则无法调用该方法。
@RequestMapping(value = "/index",method = RequestMethod.GET,params = {
"id","name"})
public String index(){
System.out.println("执行了index。。。");
return "index";
}
上述代码表示请求中必须包含指定参数id和name。
通过以下URL访问时会出现错误:
http://localhost:8080/hello/index
错误信息如下:
HTTP Status 400 – 错误的请求
Type Status Report
消息 Parameter conditions