[技术博客] Springboot的Controller类使用

Springboot的Controller类使用

@Controller:处理http请求。
代码:spring

@Controller
public class QuestionController {
......
}

@AutoWired:byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它能够对类成员变量、方法及构造函数进行标注,完成自动装配的工做。当加上(required=false)时,就算找不到bean也不报错。
代码:数据库

@Autowired
private QuestionMapper questionMapper;

@GetMapping:是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写,用于将HTTP GET请求映射到特定处理程序方法的注释。
代码:springboot

@GetMapping("/question")
public String getQuestion(Model model) {
......
model.addAttribute("questionList", questionList);
......
return "questionAll";
}

以上代码响应到页面questionAll(能够直接使用Model封装内容,直接返回页面字符串)app

@PostMapping:是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写,用于将HTTP POST请求映射到特定处理程序方法的注释。
代码:框架

@PostMapping("/comment")
public String insertComment(@RequestParam(name = "comment") String  comment, @RequestParam(name = "id") int id , Model model) {
......
return "questionDetail";
}

@RequestMapping:对于并未用到的@RequestMapping(method=RequestMethod.),由以上可知,@RequestMapping能够直接替代以上@GetMapping和@PostMapping两个注解,可是,以上两个注解并不能替代@RequestMapping,@RequestMapping至关于以上两个注解的父类。函数

@RequestParam:获取请求参数的值。在SpringMVC框架中,能够经过定义@RequestMapping来处理URL请求。和@PathVariable同样,在处理URL的函数中,去获取URL中的参数。经过注解@RequestParam能够轻松的将URL中的参数绑定处处理函数方法的变量中。
语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)value:参数名;required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,若是不包含就报错;defaultValue:默认参数值,若是设置了该值,required=true将失效,自动为false,若是没有传该参数,就使用默认值。
代码:ui

@GetMapping("/questionDetail")
public String getQuestionDetail(@RequestParam(name = "id") int id, Model    model) {
}

代码将Request参数名为"id"的值绑定到了处理函数的参数id上。code

Springboot的Mapper类使用

@Mapper:这个用于数据库,须要扫描到对应的注解文件。
代码:对象

@Mapper
public interface QuestionMapper {
}

@Select 是查询类的注解,全部的查询均使用这个
@Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,若是实体类属性和数据库属性名保持一致,就不须要这个属性来修饰。
@Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
@Update 负责修改,也能够直接传入对象
@Delete 负责删除
代码:字符串

@Select("select * from questions where id = #{id}")
Question findById(int id);

@Select("select * from questions")
List<Question> findAll();
相关文章
相关标签/搜索