文档章节

SpringBoot使用WEB进阶

黄柳淞
 黄柳淞
发布于 2017/07/23 00:42
字数 1004
阅读 35
收藏 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
Spring Boot 全家桶 - SpringBootBucket

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

一刀
03/05
0
1
微服务资源springboot、springcloud、docker、dubbo项目实战等倾心分享

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

公众号_好好学java
08/06
0
0
【SpringBoot专题】快速体验

前言 在Spring 4推出来之前,我们的编码是存在一些问题,比如:大量的xml配置存在项目中,配置相当繁琐;整合第三方框架非常麻烦;开发效率和部署效率不高等问题。正是因为这些问题,Spring开...

张丰哲
08/05
0
0
Spring Boot入门资料整理

Spring Boot 初识 SpringBoot前世今生 本文主要讲述spring boot的由来,即其它诞生的背景,初衷,现状,及对未来的展望。 Spring Boot参考指南中文版--Chapter1.Spring Boot中文文档 本节提供...

小致dad
2017/11/07
0
0

没有更多内容

加载失败,请刷新页面

加载更多

打开eclipse出现an error has occurred see the log file

解决方法: 1,打开eclipse安装目录下的eclipse.ini文件; 2,打开的文本文件最后添加一行 --add-modules=ALL-SYSTEM 3,保存重新打开Eclipse。...

任梁荣
昨天
3
0
搞定Northwind示例数据库,无论哪个版本的SQLServer都受用

Northwind数据库 从这里可以找到突破口: http://social.msdn.microsoft.com/Forums/zh-CN/Vsexpressvb/thread/8490a1c6-9018-40c9-aafb-df9f79d29cde 下面是MSDN: http://msdn2.microsoft......

QQZZFT
昨天
1
0
mysql主从同步,安装配置操作

准备 两台mysql服务,我这里准备了如下: 主库:192.168.176.128 从库:192.168.176.131 如何在Linux上安装mysql服务,请看https://blog.csdn.net/qq_18860653/article/details/80250499 操作...

小致dad
昨天
3
0
一个手机装天下,走遍中国都不怕!

导读 “1200元(人民币,下同),微信支付,可以,你扫我。”来自西非马里共和国的展商Albert拿着手机,和一位买走他手鼓的中国游客用简单的汉语交流着。 近日,“第十四届中俄蒙经贸洽谈暨商品...

问题终结者
昨天
2
0
Redis的“死键”问题

大规模的数据库存储系统中,数据的生命周期管理是很有必要的;从业务角度发现过期数据,数据归档和数据碎片整理等。以MySQL为例,1个运行很久的TB级MySQL实例中,极有可能数百GB的数据,对业...

IT--小哥
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部