1.1 @RequestMapping映射请求
SpringMVC使用 @RequestMapping注解为控制器指定可以处理那些URL请求
@RequestMapping 可以定义在类和方法上
package com.ibigsea.springmvc.helloworld;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorld {
/**
* 配置@RequestMapping 拦截 localhost:8080/springmvc/hello 请求
* @return
*/
@RequestMapping("/hello")
public String helloWorld() {
System.out.println("hello world");
return "helloworld";
}
}
package com.ibigsea.springmvc.helloworld;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloWorld {
/**
* 配置@RequestMapping 拦截 localhost:8080/springmvc/hello/world 请求
* @return
*/
@RequestMapping("/world")
public String helloWorld(){
System.out.println("hello world");
return "helloworld";
}
}
@RequestMapping
–类定义处:提供初步的请求映射信息。相对于WEB应用的根目录
–方法处: 提供进一步的细分映射信息。相对于类定义处的URL。若类定义处未标注@RequestMapping,则方法处标记的URL相对于WEB应用的根目录
DispathcherServlet截获请求后,就通过控制器上@RequestMapping提供的映射信息确定请求所对应的处理方法
@RequestMapping除了可以使用请求URL映射请求外,还可以使用请求方法、请求参数及请求头映射请求
1.2@RequestMapping限定请求方法、请求参数、请求头
/**
* 接收GET请求
* @return
*/
@RequestMapping(value="/get",method = RequestMethod.GET)
public String get(){
System.out.println("get");
return "get";
}
/**
* 接收POST请求
* @return
*/
@RequestMapping(value="/post",method = RequestMethod.POST)
public String post(){
System.out.println("post");
return "post";
}
/**
* 只接收 name 参数
* @return
*/
@RequestMapping(value="/params",params="name")
public String params(String name){
System.out.println("hello "+name);
return "helloworld";
}
/**
* 只接收请求头中 Content-Type 为 text/html;charset=UTF-8的请求
* @return
*/
@RequestMapping(value="/headers",headers="Content-Type:text/html;charset=UTF-8")
public String headers(){
System.out.println("headers");
return "helloworld";
}
1.3@RequestMapping匹配符
– ?:匹配文件名中的一个字符
– *:匹配文件名中的任意字符
– : 匹配多层路径
实例:
URL : /user/*/create
– /user/bigsea/create 、 /user/sea/create 等URL
URL : /user/**/create
– /user/big/sea/create 、 /user/sea/big/create 等URL
URL : /user/create??
– /user/createaa 、/user/createbb
1.4 @RequestParam 绑定请求参数
在处理方法入参处使用@RequestParam可以把请求参数传递给请求方法
-value:参数名
-required:表示这个参数是否是必须的 默认为true,表示请求参数中必须包含对应的参数,若不存在,将抛出异常
/**
* 如果 required = true 则表示请求参数对应的 字段 必须存在.如果不存在则会抛出异常<br/>
* @param firstName 可以为null
* @param lastName 不能为null .为null报异常
* @param age age字段表示如果没有 age 参数 则默认值为 0
* @return
*/
@RequestMapping("/requestParam")
public String requestParam(@RequestParam(value="firstName",required=false)String firstName,
@RequestParam( value="lastName" ,required = true) String lastName,
@RequestParam(value="age",required = false ,defaultValue="0")int age) {
System.out.println("hello my name is " + (firstName == null ? "" : firstName)
+ lastName + "," + age +" years old this year");
return "helloworld";
}