文档章节

SpringBoot使用WEB进阶

黄柳淞
 黄柳淞
发布于 2017/07/23 00:42
字数 1004
阅读 36
收藏 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
08/06
0
0
SpringBootBucket 2.0.4 发布,代号“傲娇的小二晶”

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

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

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

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

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

一刀
03/05
0
1

没有更多内容

加载失败,请刷新页面

加载更多

eslint rules 规则

'rules': { "comma-dangle": ["error", "never"], //是否允许对象中出现结尾逗号 "no-cond-assign": 2, //条件语句的条件中不允许出现赋值运算符 "no-console": 2, //不允许出现console语句 ...

agenyun
21分钟前
1
0
类型判断时instanceof和equals的不同用法

接口设计时为了避免序列化的麻烦,将接口定义为参数为map<String,String>类型的接口,但是现在调用时需要转换当前的实体Bean为Map,接口接收方再把Map转换为另一个Bean实体。过程中的需要对类...

wangtx
27分钟前
1
0
vue 组件间传值(个人精编)

1.父组件向子组件传值 1⃣️.子组件标签绑定需要传递的参数名2⃣️.子组件页面使用props 接收参数 2.子组件向父组件传值  1⃣️.子组件使用$emit来触发一个自定义事件,并传递一个参...

MrBoyce
37分钟前
1
0
(荷兰)彼得·冯·门施著:博物馆学研究的目的

博物馆学研究的目的 (荷)彼得·冯·门施 尽管诸多关于博物馆学认知目的的不同看法可以被归纳为数个主要群体,但没有一个群体可以被称为“学派”。一般来说,学派是由于博物馆学研究目的的不...

乔老哥
47分钟前
2
0
Vue slot的用法

之前看官方文档,由于自己理解的偏差,不知道slot是干嘛的,看到小标题,使用Slot分发内容,就以为 是要往下派发内容。然后就没有理解插槽的概念。其实说白了,使用slot就是先圈一块地,将来...

peakedness丶
59分钟前
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部