SpringMVC注解

一,@RequestMapping

可以用在类和方法上

1.1 作用:

将客户端请求映射到可匹配的类和方法中

1.2 属性:

name

给映射指定一个名字

path(同value相同)

请求的url,path={"/mixedAttribute1","/mixedAttribute2"}

method

请求的方法,method={RequestMethod.GET,RequestMethod.POST}

params

请求参数,params={"id=1","name=cc"}

headers

请求头,headers={"header1=1","header2=2"}

consumes

通过查看源码我们知道请求头的Content-Type如果跟consumes设置类型之一匹配的话,那么请求将映射到这里

produces

通过查看源码我们知道请求头的Accept如果跟produces设置类型之一匹配的话,那么请求将映射到这里

二,@Controller

标注一个类是SpringMVC Controller对象,前端控制器会扫描这个类的方法,并判断这些方法是否使用了@RequestMapping方法

三,@Resource和@Autowired

3.1 相同点

都是用于bean的自动注入,都可以用在属性或者属性的setter方法上面,下面根据@Autowired举个例子

public class HelloWorld{
    // 下面两种@Autowired只要使用一种即可
    @Autowired
    private UserDao userDao; // 用于字段上
    
    @Autowired
    public void setUserDao(UserDao userDao) { // 用于属性的方法上
        this.userDao = userDao;
    }
}

 

3.2 不同点

@Resource默认byName,javax.annotation.Resource,有两个重要属性name和type

@Autowired默认byType,Spring提供的注解,如果想byName,可以结合@Qualifier使用

四.@PathVariable

4.1 作用

将url中的模板变量注入到处理方法的参数上

4.2 栗子

	
	private HttpServletRequest request;
	
	@ModelAttribute
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	@ResponseBody
	@RequestMapping(path="/pathVariableMethod1/{name}")
	public String pathVariableMethod1(@PathVariable("name") String str){
		return "url:"+request.getRequestURI()+",name:"+str;
	}

	@ResponseBody
	@RequestMapping(path="/pathVariableMethod2/{name}/{name1}")
	public String pathVariableMethod2(@PathVariable("name") String str,@PathVariable("name1") String str1){
		System.out.println("==================name=============="+str);
		return "url:"+request.getRequestURI()+",name:"+str+",name1:"+str1;
	}
	
	@ResponseBody
	@RequestMapping(path="/pathVariableMethod3/{regexp1:[a-z]+}")
	public String pathVariableMethod3(@PathVariable("regexp1") String str){
		return "url:"+request.getRequestURI()+",name:"+str;
	}

五.@RequestParam

5.1 作用

将请求的参数区数据注入到功能处理方法的参数上

5.2 栗子

	@ResponseBody
	@RequestMapping(path="/requestParamTest/method1")
	public String method1(@RequestParam("id") String id){
		return id;
	}

六、@ModelAttribute

可以用在方法和参数上,放在方法上面表示该Controller对象的每个方法执行前都会执行该方法,放在参数上面表示引用Model中的数据

@ModelAttribute的用法参考https://blog.csdn.net/abc997995674/article/details/80464023

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值