文章目录
- 1 dao层(mapper):接口
- 2 controller层
- 3. bean层(entity):用户实现类
- 4.service
- SpringMVC 相关注解
- @RequestMapping
- @Repository
- @Controller、@ResponseBody、@RestController(@ResponseBody + @Controller)
- 3 @RequestParam(获取url ?后的参数)
- 4 @RequestBody(接受json)
- 5 @PathVariable
- 其他注解
- 1、@Autowired 和@Resource
注解 | 说明 |
@Repository | 持久层(dao)注入spring容器 |
@Service | 业务逻辑层(server)注入spring容器 |
@Controller | 控制层(controller)注入spring容器 |
@Component | 普通pojo注入spring容器 |
@ResponseBody | @ResponseBody的作用其实是将java对象转为json格式的数据。 |
@RestController | 控制层(controller)应用:@ResponseBody + @Controller |
@Resource | |
1 dao层(mapper):接口
//@Repository的作用在持久层接口,是将接口的一个实现类交给spring管理
@Repository
public interface MenuDao {
//获取菜单
// public List<MainMenu> getMenus();
public List<MainMenu> getMainMenus();
}
2 controller层
注解 | 说明 |
@RequestMapping的的method | |
@PostMapping(value = “/user/login”) | @RequestMapping(value = “/user/login”,method = RequestMethod.POST):与前面等价 |
@GetMapping | 处理get请求的映射 |
@PostMapping | 处理post请求的映射(测试指定映射请求的方式为POST) |
@PutMapping | 用于处理HTTP PUT请求,并将请求映射到具体的处理方法中 |
@DeleteMapping | 处理delete请求的映射,并将请求映射到删除方法中。 |
注解 | 说明 |
@Controller | 控制层(controller)注入spring容器 |
@ResponseBody | @ResponseBody的作用其实是将java对象转为json格式的数据。 |
@RestController | 控制层(controller)应用:@ResponseBody + @Controller |
@RequestMapping | 将请求和处理请求的控制器方法关联起来,建立映射关系。 |
@RequestParam | 接受url中的参数,获取前端传参 |
@RequestBody | 用来接收前端传递给后端的 |
@PathVariable | 映射 URL 绑定的占位符 |
@Resource | 用来装配bean,默认按照名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性, |
@Autowired | 用来装配bean,默认按类型装配 |
@CrossOrigin | 实现跨域 |
@RestController
@RequestMapping("/echarts")
public class EchartsController {
//默认通过类型注入,如存在多个类型
@Autowired
private IUserService userService;
//默认通过名称注入,如名称无法找到,则通过类型注入
@Resource
private FileMapper fileMapper;
@Autowired
private StringRedisTemplate stringRedisTemplate;
}
@RestController
@RequestMapping("/role")
public class RoleController {
@Resource
private IRoleService roleService;
// 新增或者更新
@PostMapping
public Result save(@RequestBody Role role) {
roleService.saveOrUpdate(role);
return Result.success();
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
roleService.removeById(id);
return Result.success();
}
@PostMapping("/del/batch")
public Result deleteBatch(@RequestBody List<Integer> ids) {
roleService.removeByIds(ids);
return Result.success();
}
@GetMapping
public Result findAll() {
return Result.success(roleService.list());
}
@GetMapping("/page")
public Result findPage(@RequestParam String name,@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name", name);
queryWrapper.orderByDesc("id");
return Result.success(roleService.page(new Page<>(pageNum, pageSize), queryWrapper));
}
@PostMapping("/roleMenu/{roleId}")
public Result roleMenu(@PathVariable Integer roleId, @RequestBody List<Integer> menuIds) {
roleService.setRoleMenu(roleId, menuIds);
return Result.success();
}
}
3. bean层(entity):用户实现类
注解 | 说明 |
使用lombok插件 | |
@Data | 它结合了@ToString,@EqualsAndHashCode, @Getter和@Setter |
@Getter/@Setter | 注解会生成对应的getter和setter方法 |
@NoArgsConstructor | 注解会生成对应的无参构造方法 |
@AllArgsConstructor | 注解会生成对应的有参构造方法 |
MyBatisPlus常用注解 | |
@TableName(" ") | 该注解主要是现实实体类型和数据库中的表实现映射。 |
@ApiModel | |
@TableId |
@Getter
@Setter
@TableName("sys_menu") //是在类名和数据库中的表名不一致时确定某个实体类对应数据库中哪个表。
@ApiModel(value = "Menu对象", description = "") //value:为模型提供备用名称;description提供详细的类描述
public class Menu implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("id")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("路径")
private String path;
@ApiModelProperty("图标")
private String icon;
@ApiModelProperty("描述")
private String description;
@TableField(exist = false)
private List<Menu> children;
private Integer pid;
private String pagePath;
private String sortNum;
}
4.service
注解 | 说明 |
@Service | 标记当前类是一个service类,加上该注解会将当前类自动注入到spring容器中 |
@Resource | |
@Transactional | 注解应该只被应用到 public 方法上,表示这个方法开启事务,一般都放在service层里 |
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
@Resource
private CourseMapper courseMapper;
@Override
public Page<Course> findPage(Page<Course> page, String name) {
return courseMapper.findPage(page, name);
}
@Transactional
@Override
public void setStudentCourse(Integer courseId, Integer studentId) {
courseMapper.deleteStudentCourse(courseId, studentId);
courseMapper.setStudentCourse(courseId, studentId);
}
}
SpringMVC 相关注解
@RequestMapping
@RequestMapping注解:作用就是将请求和处理请求的控制器方法关联起来,建立映射关系。
@RequestMapping注解的位置:
- @RequestMapping标识一个类:设置映射请求的请求路径的初始信息
- @RequestMapping标识一个方法:设置映射请求请求路径的具体信息
@RestController
@RequestMapping("/test")
public class RequestMappingController {
//此时请求映射所映射的请求的请求路径为:localhost:8080/test/testRequestMapping
@RequestMapping("/testRequestMapping")
public String testRequestMapping(){
return "success";
}
@RequestMapping("/view/{id}")
public ModelAndView view(@PathVariable("id") Integer id)
}
@RequestMapping注解的method属性
@RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射
@Repository
@Repository的作用在持久层接口,是将接口的一个实现类交给spring管理
@Controller、@ResponseBody、@RestController(@ResponseBody + @Controller)
@ResponseBody的作用其实是将java对象转为json格式的数据。
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
/*
等同
*/
@Controller
@ResponseBody
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
3 @RequestParam(获取url ?后的参数)
@RequestParam:接受url的参数,或者表单里面的参数
@RequestParam 有三个属性:
(1)value:请求参数名(必须配置)
(2)required:是否必需,默认为 true。表示请求中一定要有相应的参数,如果没有包含,将会抛出异常(可选配置),required=false ,尽管没对应上然而不会报错,而是获取值为 null。
(3) defaultValue设置默认值
//不加@RequestParam前端的参数名需要和后端控制器的变量名保持一致才能生效
@RequestMapping("/list1")
public String test1(int userId) {
return "list";
}
//@RequestParam可以解决前后端定义的参数名不一致的问题
//例如前端传入的参数名是name,后端方法接收的参数名是userName,这时可以通过@RequestParam指定value的值为name,实现name与userName的映射。
@RequestMapping(method = RequestMethod.GET, value = "selectCourseAndTeacherByStudent")
public Course selectCourseAndCourseByStudent(@RequestParam(value = "name") String userName) {
Course course = studentService.selectCourseAndTeacherByStudent(userName);
return course;
}
//如果后端使用的是基本数据类型来接收参数,那么一定要设置required=false,并且要设置一个默认值
// @RequestParam 注解加上 required=false ,尽管没对应上然而不会报错,而是获取值为 null
@RequestMapping(method = RequestMethod.GET,value = "selectStudentById")
public Student selectStudentById(@RequestParam(value = "id",required = false,defaultValue = "01") int id){
return studentService.selectStudentById(id);
}
// 如果后端使用的是引用数据类型,则无需设置required=false和defaultValue
//因为即使前端没有传入参数值,引用数据类型是可以接收null的。
@RequestMapping(method = RequestMethod.GET,value = "selectStudentById")
public Student selectStudentById(@RequestParam(value = "id") Integer id){
return studentService.selectStudentById(id);
}
@RequestMapping(value = "/testAnno", produces = "application/json;charset=UTF-8")
@ResponseBody
//value = "name"与前端的名称应该一致
public String testAnno(@RequestParam(value = "name", required = false, defaultValue = "测试默认值") String username) {
System.out.println(username);
return username;
}
4 @RequestBody(接受json)
@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);
而最常用的使用请求体传参的无疑是POST请求了,所以使用@RequestBody接收数据时,一般都用POST方式进行提交。
在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个
//@RequestBody 把数据写入请求的body中,绑定到 controller中方法的参数上
@RequestMapping("/addUser")
public String addUser(@RequestBody User user){
System.out.println(user);
user.setRole("普通用户");
user.setState(false);
int i = userDao.addUser(user);
String str = i >0?"success":"error";
return str;
}
5 @PathVariable
@PathVariable 映射 URL 绑定的占位符
//1、若方法参数名称和需要绑定的url中变量名称一致时,可以简写:
@RequestMapping("/getUser/{name}")
public User getUser(@PathVariable String name){
return userService.selectUser(name);
}
//若方法参数名称和需要绑定的url中变量名称不一致时,写成:
@RequestMapping("/getUserById/{name}")
public User getUser(@PathVariable("name") String userName){
return userService.selectUser(userName);
}
其他注解
1、@Autowired 和@Resource
@Autowired是默认按照类型装配Bean,当需要用名称装配时,可以在@Autowired后面使用@Qualifier注解指定name属性,来告知容器加载哪个bean
@Resource默认按照名字装配Bean,即会按照name属性的值来找到具有相同id的Bean Definition 并注入。如果@Resource没有指定name属性,则会根据这个将要被注入的属性的名字来进行Bean装配。
//这样Spring会找到id为userServiceImpl和userDao的bean进行装配。
@Autowired
@Qualifier("userServiceImpl")
public IUserService userService;
@Resource (name= "baseDao" )
private BaseDao baseDao;
//Myservice是一个接口 MyserviceImpl01,MyserviceImpl02,同时继承Myservice
//默认通过名称注入,如名称无法找到,则通过类型注入
@Resource
//private Myservice myservice; //因为有两个名称01,和02所以这个无法继承;如果只有一个就可以直接这么用
private Myservice myserviceImpl01; //这样可以找到,这是名称注入
//默认通过类型注入,如存在多个类型,则通过名称注入
@Autowired
//private Myservice myservice; //会报错
private Myservice myserviceImpl01; //这样可以找到,这是名称注入
@Autowired
@Qualifier("myserviceImpl01") //如果不同这个的话可以在bean那加注解 @Primary 就这可以优先使用了。
private Myservice myservice;