文档章节

SpringBoot使用WEB进阶

黄柳淞
 黄柳淞
发布于 2017/07/23 00:42
字数 1004
阅读 39
收藏 1

1.使用aop处理请求get,post

2.统一异常检查

3.单元测试

4效果预览:

 

5.开发环境

    maven开发环境:3.3.9

    Itellij IDEA旗舰版

    java开发环境java version "1.8.0_91"

6.完成的 完整的代码实例

HttpAspect

package com.hls;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HlsApplication {

	public static void main(String[] args) {
		SpringApplication.run(HlsApplication.class, args);
	}
}

 

BoyController


package com.hls.controller;

import com.hls.domain.Boy;
import com.hls.domain.Result;
import com.hls.repository.BoyRepository;
import com.hls.service.BoyService;
import com.hls.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by huangliusong on 2017/7/19.
 * 查询男生列表
 */
@RestController
public class BoyController {
    @Autowired
    private BoyRepository boyRepository;
    @Autowired
    private BoyService boyService;
    @GetMapping(value = "/boys")
    public List<Boy> boylist(){
        return boyRepository.findAll();
    }

    @PostMapping(value="/boys")
    public Result<Boy>  boyadd(@Valid Boy boy, BindingResult bindingResult){
        if(bindingResult.hasErrors()){

            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        boy.setAge(boy.getAge());
        boy.setBirth(boy.getBirth());
        boy.setId(1001);
        return ResultUtil.success(boyRepository.save(boy));
    }

    //查询
    @GetMapping(value = "/boys/{id}")
    public Boy findBoy(@PathVariable("id")Integer id){
        return boyRepository.findOne(id);
    }
    //更新
    @PostMapping(value = "/boys/{id}")
    public Boy updateBoy(@PathVariable("id")Integer id,
                         @RequestParam("age")String age,
                         @RequestParam("birth")String birth){
        Boy boy=new Boy();
        boy.setId(id);
        boy.setBirth(birth);
        boy.setAge(age);
        return boyRepository.save(boy);
    }
    //删除
    @DeleteMapping(value = "/boys/{id}")
    public void deleteBoy(@PathVariable("id")Integer id){
        boyRepository.delete(id);
    }

    //通过年龄查询
    @GetMapping(value = "boys/age/{age}")
    public List<Boy> boylistByAge(@PathVariable("age") String age){
        return boyRepository.findByAge(age);
    }

    @PostMapping(value = "/boys/two")
    public void boyTwo(){
        boyService.insertBoyTow();
    }

    /**
     * 对年龄进行判断
     */
    @GetMapping(value = "/boys/getAge/{id}")
    public void  getAge(@PathVariable("id")Integer id)throws Exception{
        boyService.getAge(id);
    }
}


HelloController

package com.hls.controller;

import com.hls.repository.Boyproperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by huangliusong on 2017/7/18.
 */
@RestController
@RequestMapping("/huang")
public class HelloController {

    @Autowired
    private Boyproperties boyproperties;
    @GetMapping("/liu1")
    public String say  (@RequestParam(value="id",required = false, defaultValue ="0") Integer id){
        return "index.html?"+id;
    }
}

Boy

package com.hls.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Min;

/**
 * Created by huangliusong on 2017/7/19.
 */
@Entity
public class Boy {
    @Id
    @GeneratedValue
    private Integer id;
    @Min(value=18,message = "不是18,不能录入进去")
    private String age;
    private String birth;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAge() {
        return age;
    }

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

    public String getBirth() {
        return birth;
    }

    public void setBirth(String birth) {
        this.birth = birth;
    }

    public Boy() {
    }

    @Override
    public String toString() {
        return "Boy{" +
                "id=" + id +
                ", age='" + age + '\'' +
                ", birth='" + birth + '\'' +
                '}';
    }
}


Result

package com.hls.domain;

/**
 * http请求返回的最外层对象
 * Created by huangliusong on 2017/7/22.
 */
public class Result<T> {
    //错误码
    private Integer code;
    //提示信息
    private  String msg;
    //具体的内容
    private T data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

ResultEnum

package com.hls.enmus;

/**
 * Created by huangliusong on 2017/7/22.
 */
public enum ResultEnum {
    UNKNOW_ERROR(-1,"未知错误"),
    SUCCESS(0,"成功"),
    PRIMARY_SCHOOL(1001,"你还在上小学"),
    MIDDLE_SCHOOL(1002,"你还在上初中")

            ;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    private Integer code;
    private String msg;

    ResultEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

BoyException

package com.hls.exception;

import com.hls.domain.Result;
import com.hls.enmus.ResultEnum;

/**
 * Created by huangliusong on 2017/7/22.
 */
public class BoyException extends RuntimeException{
    private   Integer code;

    public BoyException(ResultEnum resultEnum) {
        super(resultEnum.getMsg());
        this.code = resultEnum.getCode();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

ExceptionHandle

package com.hls.handler;

import com.hls.domain.Result;
import com.hls.exception.BoyException;
import com.hls.util.ResultUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by huangliusong on 2017/7/22.
 */
@ControllerAdvice
public class ExceptionHandle {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handler(Exception e){
        if(e instanceof BoyException){
            BoyException boyException=(BoyException)e;
            return ResultUtil.error(boyException.getCode(),boyException.getMessage());
        }else{
            return ResultUtil.error(-1,"未知错误");
        }

    }
}

Boyproperties

package com.hls.repository;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * Created by huangliusong on 2017/7/18.
 */
@Component
@ConfigurationProperties(prefix = "boy")
public class Boyproperties {
    private String hlsBirth;
    private Integer hlsAge;
    public String getHlsBirth() {
        return hlsBirth;
    }

    public void setHlsBirth(String hlsBirth) {
        this.hlsBirth = hlsBirth;
    }

    public void setHlsAge(Integer hlsAge) {
        this.hlsAge = hlsAge;
    }

    public Integer getHlsAge() {
        return hlsAge;
    }


}


BoyRepository

package com.hls.repository;

import com.hls.domain.Boy;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * Created by huangliusong on 2017/7/19.
 */
public interface BoyRepository extends JpaRepository<Boy,Integer>{
    //通过年龄查询
    public List<Boy> findByAge(String age);
}

    BoyService

package com.hls.service;

import com.hls.enmus.ResultEnum;
import com.hls.exception.BoyException;
import com.hls.repository.BoyRepository;
import com.hls.domain.Boy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Created by huangliusong on 2017/7/21.
 */
@Service
public class BoyService {
    @Autowired
    private BoyRepository boyRepository;
    //添加事物注解
    @Transactional
    public void insertBoyTow(){
        Boy boy1=new Boy();
        boy1.setAge("67");
        boy1.setBirth("1967");
        Boy boy2=new Boy();
        boy2.setAge("688");
        boy2.setBirth("1968");

        boyRepository.save(boy1);
        boyRepository.save(boy2);
    }
    public void getAge(Integer id) throws  Exception{
        Boy boy=boyRepository.findOne(id);
        Integer age=Integer.parseInt(boy.getAge());
        System.out.println(age);
        if(age<10){
            //返回你还在上小学
            throw new BoyException(ResultEnum.PRIMARY_SCHOOL);
        }else if(age>10&&age<16){
            //返回 你还在上初中
            throw new BoyException(ResultEnum.MIDDLE_SCHOOL);
        }

    }

    /**
     * 通过id查询详细信息
     * @param id
     * @return
     */
    public Boy findOneBoy(Integer id){
        return boyRepository.findOne(id);
    }
}

ResultUtil

package com.hls.util;

import com.hls.domain.Result;
import com.sun.org.apache.regexp.internal.RE;

/**
 * Created by huangliusong on 2017/7/22.
 */
public class ResultUtil {
    public static Result success(Object object){
        Result result=new Result();
        result.setCode(0);
        result.setData(object);
        result.setMsg("成功");
        return result;
    }
    public  static Result success(){
        return success(null);
    }
    public static Result error(Integer code,String msg){
        Result result=new Result();
        result.setMsg(msg);
        result.setCode(code);
        result.setData("null");
        return result;
    }
}

HlsApplication

package com.hls;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HlsApplication {

	public static void main(String[] args) {
		SpringApplication.run(HlsApplication.class, args);
	}
}

 

© 著作权归作者所有

黄柳淞
粉丝 2
博文 108
码字总数 54251
作品 0
南宁
程序员
私信 提问
springboot(一)入门篇

今天来整理下springboot,开发工具使用eclipse(后期会再做个idea的).主要实现的功能是 1.通过数据库的查询返回前端数据. 第二步:新建entity 第三步:新建UserMapper(需要在application.propert...

zhuyuansj
2017/10/06
0
0
微服务资源springboot、springcloud、docker、dubbo项目实战等倾心分享

精彩内容 java实战练习项目教程 全网最全电子图书分享 你所需要的大数据视频教程 java学习视频教程及源码 今天又是周末,还是想给大家送一些福利,因为最近一直有小伙伴问我要springboot等微...

公众号_好好学java
2018/08/06
0
0
SpringBootBucket 2.0.4 发布,代号“傲娇的小二晶”

SpringBootBucket 自从1.0.0版本发布后就有好多人喜欢,目前码云上面star数量接近1.2k。上个月还收到了红薯签名的1000 star奖杯,这个我自己也觉得很惊讶。 由于SpringBoot 1.x官方将终止维护...

一刀
2018/09/16
1K
4
SpringBootBucket 1.0.0 发布,SprintBoot 全家桶

Spring Boot 现在已经成为Java 开发领域的一颗璀璨明珠,它本身是包容万象的,可以跟各种技术集成。 本项目对目前Web开发中常用的各个技术,通过和SpringBoot的集成,并且对各种技术通过“一...

一刀
2018/03/05
7.3K
17
Spring Boot 全家桶 - SpringBootBucket

Spring Boot 现在已经成为Java 开发领域的一颗璀璨明珠,它本身是包容万象的,可以跟各种技术集成。 本项目对目前Web开发中常用的各个技术,通过和SpringBoot的集成,并且对各种技术通过“一...

一刀
2018/03/05
0
1

没有更多内容

加载失败,请刷新页面

加载更多

Jenkins系列_插件安装及报错处理

进入Jenkins之后我们可以进行插件的安装,插件管理位于以下模块: 发现上面报了一堆错误,是因为插件的依赖没有安装好,那么这一节,就先把这些错误解决掉吧。解决完成后,也就基本会使用插件...

shzwork
今天
2
0
mysql mysql的所有查询语句和聚合函数(整理一下,忘记了可以随时看看)

查询所有字段 select * from 表名; 查询自定字段 select 字段名 from 表名; 查询指定数据 select * from 表名 where 条件; 带关键字IN的查询 select * from 表名 where 条件 [not] in(元素...

edison_kwok
昨天
8
0
多线程同时加载缓存实现

import com.google.common.cache.Cache;import com.google.common.cache.CacheBuilder;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorServi......

暗中观察
昨天
2
0
利用VisualVM 内存查看

准备工作,建几个测试类。等下就是要查看这几个类里面的属性 package visualvm;public class MultiObject { private String str; private int i; MultiObject(String str...

冷基
昨天
2
0
组装一台工作游戏两用机

一、配置清单如下: 分类 项目 价格(元) 主板 华硕(ASUS)TUF Z370-PLUS GAMING II 电竞特工 Z370二代 支持9代CPU 1049 CPU 英特尔(Intel) i7 8700K 酷睿六核 盒装CPU处理器 2640 风扇 九...

mbzhong
昨天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部