您的位置:首页 > 编程语言 > Java开发

Spring Boot学习

2017-09-07 19:51 246 查看
Controller的使用

@Controller 处理http的请求

@RestController 原来返回json需要@ResponseBody配合@Controller

@RequestMapping 配置url映射

如果要使用@Controller (不推荐使用)

类上添加@Controller

并添加模板 spring-boot-starter-thymeleaf

在resources中创建templates 在templates中创建index.html

方法中返回 return “index”;

@RequestMappig()中

设置{value={“/hello”,”/hi”},method=ResquestMethod.GET} (设置两个Url)

@PathVariable 获取url中的数据

@RequestParam 获取请求参数值

@GetMapping 组合注解

直接向页面输出一串字符 在类上添加@SpringBootApplication

@RestController

如何获取参数
@RequestMapping(value="/say/{id}",method=ResquestMethod.GET)
public String say(@PathVariable("id") Integer id){
return "id:"+id;
}
(@RequestParam("id"))   @PathVariable("id")是获取主键

spring-boot-starter-data-jpa

向控制器中注入属性@value("cupSize")

@Component
@ConfigurationProperties(prefix = "girl")
public class GirlPropertise {
private  String cupSize;
private  Integer age;

public String getCupSize() {
return cupSize;
}

public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

yml中配置mysql
datasource:
driver-class-name:
url:
username:
password:
jpa:
hibernate:
ddl-auto:update
show-sql:true
直接建一个类来创建数据表
@Entity(注意,此注解是hibernate中的注解)
public class Girl{
@Id
@GeneratedValue
private Integer id;
private String cupSize;
private Integer age;
public Girl(){
}
创建get和set方法
}

新建一个接口继承jpa
public interface GirlRepository extends JpaRepository<Girl,Integer>{
//通过年龄来查询
public List<Girl> findByAge(Integer age);
}

创建一个GirlController的类,并在上面添加入注解@RestController
@RestController
public class GirlController{
@Autowired
private GirlRepository girlRepository;
@GetMapping(value="/girls")
public List<Girl> girlList(){
return girlRepository.findAll();
}
@PostMapping(value="/girls")
public Girl girlAdd(@RequestParam("cupSize") String cupSize,@RequestParam("age") Integer age){
Girl girl=new Girl();
girl.setCupSize(cupSize);
girl.setAge(age);
return  girlRepository.save(girl);
}
@GetMapping(value="/girls/{id}")
public Girl girlFindOne(@PathVariable("id") Integer id){
return girlRepository.findOne(id);
}
@PutMapping(value="/girls/{id}")
public Girl girlUpdate(@PathVariable("id") Integer id,
@RequestParam("cupSize") String cupSize,
@RequestParam("age") Integer age){
Girl girl=new Girl();
girl.setId(id);
girl.setCupSize(cupSize);
girl.setAge(age);
return girlRepository.save(girl);
}
@DeleteMapping(value="/girls/{id}")
public void girlDelete(@PathVariable("id") Integer id){
girlRepository.delete(id);
}
//通过年龄查询女生列表
@GetMapping(value="/girls/age/{age}")
public List<Girl> girlListByAge(@PathVariable("age") Integer age){
return girlRepository.findByAge(age);
}

}


注意:@RestController注解等价于@ResponseBody+@Controller结合在一起的作用

如果需要返回JSON格式,需要在方法上加上@ResponseBody注解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: