1、注解@Component,它具有三个衍生注解:
①@Controller用于标注控制层
②@Service用于标注服务层
③@Repository用于标注数据访问层
当一个类不属于①②③类的时候就可以用@Component来标注这个类。
2、注解@Controller,用于标注一个控制器类。
3、注解@RequestMapping,常与@Controller注解连用。
标注在类上,表示请求访问的父路径;标注在方法上,表示请求访问的子路径
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/index")
public String index(){
return "user/index";
}
}
注解 @RequestMapping具有两个属性
①value,用来规定访问请求的地址
②method,用来规定访问请求的方法
4、注解@ResponseBody
当使用注解@RequestMapping时一般返回的是地址路径,加入注解@ResponseBody则可以返回值到页面中。
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/index")
public String index(){
return "user/index";
}
@RequestMapping("/add")
@ResponseBody
public String add(User user){
return user.toString();
}
}
5、注解PathVariable可以映射URL绑定的占位符{xxx},刚学,更多的讲不出来了。
@RequestMapping("/urlget/{xx1}/{xx2}/{xx3}")
@ResponseBody
public String urlget(
@PathVariable Integer xx1,
@PathVariable String xx2,
@PathVariable String xx3
){
return xx1+xx2+xx3;
}
6、注解@ExceptionHandler用于自定义异常,只对所在的控制器类有效
@ExceptionHandler(value = {java.lang.NullPointerException.class})
public ModelAndView ex1(Exception e){
//定义模型视图对象
ModelAndView mv = new ModelAndView();
//加入异常信息
mv.addObject("err",e.toString());
mv.addObject("msg","页面错误啦");
//设置显示异常信息的页面
mv.setViewName("ex/error");
return mv;
}
ex1方法获取错误信息并返回模型和视图,addObject方法定义错误名和错误内容,setViewName方法设置显示异常信息的静态页面。