SpringMVC(二)---注解配置

本文详细介绍了SpringMVC框架中常用的注解及其用法,包括@Controller、@RequestMapping、@RequestParam、@PathVariable和@ResponseBody等。并通过示例展示了如何进行请求映射及参数处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringMVC使用< mvc:annotation-driven/>配置标签全面开启MVC相关注解功能。

请求映射与参数注解

@RequestMapping
//localhost:8080/SpringMVC_war/anno-demo/hello
@Controller //控制器注解
@RequestMapping("/anno-demo") //类中请求映射注解
//@RequestMapping(value="/anno-demo") //使用value属性指定映射
public class AnnoDemoController {
    @RequestMapping("/hello")  //方法层级的请求注解
    public ModelAndView hello(){
        ModelAndView modelAndView = new ModelAndView();
        return modelAndView;
    }
}

@RequestMapping 是一个通用的请求映射,可以通过method属性指定不同的请求。

//等同于@GetMapping(value="hello")
@RequestMapping(value="/hello",method=RequestMethod.GET)

同时,还可以通过consumes和produces属性指定请求和返回的媒体格式。

  • consumes处理请求的提交内容(Content-Type),例如application/json,text/html。
  • produces返回的内容类型。
@RequestMapping(value="/users",method=RequestMethod.POST,
		consumes="application/json",produces="application/json;charset=UTF-8")
@ResponseBody
public List<User> addUser(@RequestBody User user1){
	return null;
}

设置headers属性可以限定包含此请求头参数的请求。

@RequestMapping(path="/request",headers="type=withHeaderAttr")

设置请求的URL包含参数,/request?name=value1

@RequestMapping(path="request",params="type=withParams")

@RequestParam使用在映射方法的形参中,用来匹配一些简单的类型,默认情况下,请求参数与映射方法参数需要同名。可以设置required属性为false来取消限制,还可以使用value属性设置映射到前端请求的参数名。

@RequestMapping("/hello")
public ModelAndView hello(@RequsetParam(value="userName",required=true) String userName){
}

@RequestParam也可以不使用,容器会根据参数名称自动匹配。如果方法的形参是一个对象类型的话,容器还会将请求中的参数自动装箱,也就是创建该类的对象。

//localhost:8080/hello?name=Oscar
@Controller
@RequestMapping("/hello")
public MOdelAndView hello(User user){//将会创建User对象,并将name传给user
}

@PathVariable注解使用在映射方法参数中,用来绑定映射注解中的URL占位符的值,并赋给该参数。

@RequestMapping(value="/hello/{username}")
public ModelAndView hello(@PathVariable String username){
}

当使用/hello/ZhangSan 时,会将路径中的ZhangSan绑定给username。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值