2小时学会spring boot 以及spring boot进阶之web进阶(已完成)
1:更换Maven默认中心仓库的方法
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
2:相关代码
如果要用到view页面需要引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> 用数据库和jpa需要引入以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
@RestController//返回json,@Controller返回view @RestController等同于@Controller和@ResponseBody
@RequestMapping("/hello") // 可以省略
public class HelloController {
@value("${mytest}")
private string test;
//上面同下面两种方式注入配置
@Autowired
private GirlProperties girlProperties;
@RequestMapping(value="say",method = RequestMethod.GET)
public String say(){
return girlProperties.getCupSize();
// return "index";//配合@Controller使用返回view
}
// @RequestMapping(value={"/sayy","sayy2"},method = RequestMethod.GET)
@GetMapping(value="/sayy")
public String sayy(@RequestParam(value="id",required = false,defaultValue = "0") Integer myId){
return "id:"+myId;
}
@GetMapping(value="/girls/{id}")
public Girl getGirlById(@PathVariable("id") Integer id){
return girlRepository.findOne(id);
}
}
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
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;
}
}
配置文件如下
girl:
cupSize: B
age: 18
mytest:ccctest
content:"zhangsansan ${name}+${age}"
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/boot
username: root
password: root5770
jpa:
hibernate:
ddl-auto: update
show-sql: true
3: springboot 启动方式
1:右键启动MyspringbootApplication
2:命令行启动mvn spring-boot:run
3:先mvn install 然后 java -jar xxx.jar --spring.profiles.active=prod
4:server.context-path=/girl 设置通用路径
5:设置不同的配置环境文件
spring:
profiles:
active: dev
6:jpa相关代码
@Entity
public class Girl {
@Id
@GeneratedValue
private Integer id;
private String cupSize;
private Integer age;
}
public interface GirlRepository extends JpaRepository<Girl,Integer>{
public List<Girl> findByAge(Integer age);
}
7: spring aop 是一种编程范式与语言无关
需要引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@Aspect
@Component
public class HttpAspect {
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.imooc.controller.GirlController.*(..))")
public void log() {
}
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
logger.info("url={}", request.getRequestURL());
//method
logger.info("method={}", request.getMethod());
//ip
logger.info("ip={}", request.getRemoteAddr());
//类方法
logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//参数
logger.info("args={}", joinPoint.getArgs());
}
@After("log()")
public void doAfter() {
logger.info("222222222222");
}
@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object) {
logger.info("response={}", object.toString());
}
}
也可以用一下方式代替不用设置pointcut
@After("execution(public * com.imooc.controller.GirlController.*(..))")
public void doAfter() {
logger.info("222222222222");
}
8:@Valid注解用于校验,所属包为:javax.validation.Valid。
① 首先需要在实体类的相应字段上添加用于充当校验条件的注解,如:@Min,如下代码(age属于Girl类中的属性):
@Min(value = 18,message = "未成年禁止入内")
private Integer age;
② 其次在controller层的方法的要校验的参数上添加@Valid注解,并且需要传入BindingResult对象,用于获取校验失败情况下的反馈信息,如下代码:
@PostMapping("/girls")
public Girl addGirl(@Valid Girl girl, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return null;
}
return girlResposity.save(girl);
}
bindingResult.getFieldError.getDefaultMessage()用于获取相应字段上添加的message中的内容,如:@Min注解中message属性的内容
9:全局异常捕获
@ControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if (e instanceof GirlException) {
GirlException girlException = (GirlException) e;
return ResultUtil.error(girlException.getCode(), girlException.getMessage());
}else {
logger.error("【系统异常】{}", e);
return ResultUtil.error(-1, "未知错误");
}
}
}
10:异常类
public class GirlException extends RuntimeException{
private Integer code;
public GirlException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
调用方法
public void getAge(Integer id) throws Exception{
Girl girl = girlRepository.findOne(id);
Integer age = girl.getAge();
if (age < 10) {
//返回"你还在上小学吧" code=100
throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
}else if (age > 10 && age < 16) {
//返回"你可能在上初中" code=101
throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
}
}
11:枚举类
public enum ResultEnum {
UNKONW_ERROR(-1, "未知错误"),
SUCCESS(0, "成功"),
PRIMARY_SCHOOL(100, "我猜你可能还在上小学"),
MIDDLE_SCHOOL(101, "你可能在上初中"),
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
12:http请求返回的最外层对象
public class Result<T> {
/** 错误码. */
private Integer code;
/** 提示信息. */
private String msg;
/** 具体的内容. */
private T data;
}
13:封装返回对象方法
public class ResultUtil {
public static Result success(Object object) {
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setData(object);
return result;
}
public static Result success() {
return success(null);
}
public static Result error(Integer code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
14:单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest { @Autowired
private GirlService girlService; @Test
public void findOneTest() {
Girl girl = girlService.findOne(73);
Assert.assertEquals(new Integer(13), girl.getAge());
}
} 15:测试controller
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GirlControllerTest { @Autowired
private MockMvc mvc; @Test
public void girlList() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/girls"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));
} }
16:事务控制
@Transactional
@Override
public void saveTwo() {
Girl girlA = new Girl();
girlA.setAge(18);
girlA.setCupSize("A");
girlRepository.save(girlA); Girl girlB = new Girl();
girlB.setAge(19);
girlB.setCupSize("B");
girlRepository.save(girlB); }
2小时学会spring boot 以及spring boot进阶之web进阶(已完成)的更多相关文章
- spring boot / cloud (十五) 分布式调度中心进阶
spring boot / cloud (十五) 分布式调度中心进阶 在<spring boot / cloud (十) 使用quartz搭建调度中心>这篇文章中介绍了如何在spring ...
- spring boot / cloud (十二) 异常统一处理进阶
spring boot / cloud (十二) 异常统一处理进阶 前言 在spring boot / cloud (二) 规范响应格式以及统一异常处理这篇博客中已经提到了使用@ExceptionHa ...
- 一:Spring Boot、Spring Cloud
上次写了一篇文章叫Spring Cloud在国内中小型公司能用起来吗?介绍了Spring Cloud是否能在中小公司使用起来,这篇文章是它的姊妹篇.其实我们在这条路上已经走了一年多,从16年初到现在. ...
- Spring Kafka和Spring Boot整合实现消息发送与消费简单案例
本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的 ...
- 使用Spring Session实现Spring Boot水平扩展
小编说:本文使用Spring Session实现了Spring Boot水平扩展,每个Spring Boot应用与其他水平扩展的Spring Boot一样,都能处理用户请求.如果宕机,Nginx会将请 ...
- 一起来学spring Cloud | 第一章:spring Cloud 与Spring Boot
目前大家都在说微服务,其实微服务不是一个名字,是一个架构的概念,大家现在使用的基于RPC框架(dubbo.thrift等)架构其实也能算作一种微服务架构. 目前越来越多的公司开始使用微服务架构,所以在 ...
- Spring,Spring MVC及Spring Boot区别
什么是Spring?它解决了什么问题? 我们说到Spring,一般指代的是Spring Framework,它是一个开源的应用程序框架,提供了一个简易的开发方式,通过这种开发方式,将避免那些可能致使代 ...
- 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践
由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...
- Spring Cloud Alibaba与Spring Boot、Spring Cloud之间不得不说的版本关系
这篇博文是临时增加出来的内容,主要是由于最近连载<Spring Cloud Alibaba基础教程>系列的时候,碰到读者咨询的大量问题中存在一个比较普遍的问题:版本的选择.其实这类问题,在 ...
随机推荐
- DW网页制作,数学,数据库管理
数学(函数关系的建立) 函数关系:确定性现象之间的关系常常表现为函数关系,即一种现象的数量确定以后,另一种现象的数量也随之完全确定,表现为一种严格的函数关系. 如:记为y=f(x),其中x称为自变量, ...
- 拼凑的宿主-host
开发两年之久,竟然不知道host这个词是什么意思.前些天有幸遇到了,就跟别人请教了.今天理絮一下.总比不知道强吧. 白话来说宿主就是一些框架运行机制运行时需要依赖的平台. 例如web开发常用的IIS, ...
- PAT 1040 Longest Symmetric String
#include <cstdio> #include <cstdlib> using namespace std; ]; ]; int syslen(char str[], i ...
- Django——form组件和ModelForm
一.原生form实现书城增删改查 1.构建模型并完成数据库迁移 (1)构建书城模型 from django.db import models # Create your models here. # ...
- vuex深入浅出
本文主要记录使用vuex的使用场景.重要组成部分和学习心得. 1.说在前面 学习vue有两周的时间了,目前已经对vue的基础使用比较熟悉了.但是一直对vuex的使用耿耿于怀,这么说是因为总是不太理解, ...
- js中的this问题
this this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上 this的最终指向的是那个调用它的对象(这里其实并不完全对,this的指向有时候会很微妙,得 ...
- Ubuntu16.04安装Docker1.12+开发实例+hello world+web应用容器
本次主要是详细记录Docker1.12在Ubuntu16.04上的安装过程,创建Docker组(避免每次敲命令都需要sudo),Docker常用的基本命令的总结,在容器中运行Hello world,以 ...
- JSP初学者4
Filter可认为是Servlet的“加强版”,他主要用于对用户请求进行预处理,也可以对HttpServletResponse进行后处理,是个典型的 处理链. 使用Filter完整的流程是:Filte ...
- ViewPager+fragment的使用
如图我在一个继承FragmentActivity的类中嵌套了3个fragment分别能实现3个不同的界面,默认展现第一个,在第一个的fragment中有个ViewPager在ViewPager中嵌套了 ...
- 【JS 综合】JS综合
视频教程链接:http://www.xuexi111.com/s/javascript/ 张孝祥:http://www.21edu8.com/pcnet/programming/26685/