Spring Boot 实现RESTful webservice服务端实例

简介: Spring Boot 实现RESTful webservice服务端实例

1.Spring Boot configurations 
application.yml

spring:
  profiles:
    active: dev
  mvc:
    favicon:
      enabled: false
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/wit_neptune?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

2.Spring Boot Application 
WitApp.java

/* 
 * Copyright 2016-2017 WitPool.org All Rights Reserved.
 * 
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at

 *  http://www.witpool.org/licenses
 * 
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package org.witpool;

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

/** 
 * @ClassName: WitApp 
 * @Description: WitPool Application  
 * @author Dom Wang 
 * @date 2017-11-15 AM 11:21:55 
 * @version 1.0 
 */
@SpringBootApplication
public class WitApp
{

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

3.Rest Controller 
WitUserRest.java

/* 
 * Copyright 2016-2017 WitPool.org All Rights Reserved.
 * 
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at

 *  http://www.witpool.org/licenses
 * 
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package org.witpool.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.witpool.common.enums.WitCode;
import org.witpool.common.model.bean.WitResult;
import org.witpool.common.model.po.WitUser;
import org.witpool.common.util.WitUtil;
import org.witpool.persist.WitRepository;
import org.witpool.service.WitService;

/**
 * @Class Name : WitUserRest
 * @Description: WitPool User Rest
 * @Author     : Dom Wang
 * @Email      : witpool@outlook.com 
 * @Date       : 2017-11-15 PM 2:50:27 
 * @Version    : 1.0
 */
@RestController
@RequestMapping("/users")
public class WitUserRest
{
    private final static Logger log = LoggerFactory.getLogger(WitUserRest.class);

    @Autowired
    private WitRepository reposit;

    @Autowired
    private WitService service;

    /**
    * 
    * @Title: addUser 
    * @Description: Add one user 
    * @param @param user
    * @param @return 
    * @return WitResult<WitUser>
    * @throws
     */
    @PostMapping
    public WitResult<WitUser> addUser(@RequestBody WitUser user)
    {
        return WitUtil.success(reposit.save(user));
    }

    /**
    * 
    * @Title: addUsers 
    * @Description: Add users by specified number
    * @param @param num
    * @param @return 
    * @return WitResult<WitUser>
    * @throws
     */
    @PostMapping(value = "/{number}")
    public WitResult<WitUser> addUsers(@PathVariable("number") Integer num)
    {
        if (num < 0 || num > 10)
        {
            log.error("The number should be [0, 10]");
            return WitUtil.failure(WitCode.WIT_ERR_INVALID_PARAM);
        }
        return WitUtil.success(service.addUsers(num));
    }

    /**
    * 
    * @Title: updateUser 
    * @Description: Update user 
    * @param @param user
    * @param @return 
    * @return WitResult<WitUser>
    * @throws
     */
    @PutMapping
    public WitResult<WitUser> updateUser(@RequestBody WitUser user)
    {
        return WitUtil.success(reposit.save(user));
    }

    /**
    * 
    * @Title: deleteUser 
    * @Description: delete user by ID 
    * @param @param userId
    * @param @return 
    * @return WitResult<WitUser>
    * @throws
     */
    @DeleteMapping(value = "/{userId}")
    public WitResult<WitUser> deleteUser(@PathVariable("userId") Integer userId)
    {
        reposit.delete(userId);
        return WitUtil.success();
    }

    /**
    * 
    * @Title: getUserByID 
    * @Description: Get user by ID 
    * @param @param userId
    * @param @return 
    * @return WitResult<WitUser>
    * @throws
     */
    @GetMapping(value = "/{userId}")
    public WitResult<WitUser> getUserByID(@PathVariable("userId") Integer userId)
    {
        return WitUtil.success(reposit.findOne(userId));
    }

    /**
    * 
    * @Title: getUserByName 
    * @Description: Get user by name 
    * @param @param userName
    * @param @return 
    * @return WitResult<WitUser>
    * @throws
     */
    @GetMapping(value = "/name/{userName}")
    public WitResult<WitUser> getUserByName(@PathVariable("userName") String userName)
    {
        return WitUtil.success(reposit.findByUserName(userName));
    }

    /**
    * 
    * @Title: getUsers 
    * @Description: Get all users 
    * @param @return 
    * @return WitResult<WitUser>
    * @throws
     */
    @GetMapping
    public WitResult<WitUser> getUsers()
    {
        return WitUtil.success(reposit.findAll());
    }
}

4.Aspect 
WitAspect.java

/* 
 * Copyright 2016-2017 WitPool.org All Rights Reserved.
 * 
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at

 *  http://www.witpool.org/licenses
 * 
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package org.witpool.common.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/** 
 * @ClassName: WitAspect 
 * @Description: WitPool Http Aspect 
 * @author Dom Wang 
 * @date 2017-11-15 PM 3:36:38 
 * @version 1.0 
 */
@Aspect
@Component
public class WitAspect 
{
    private final static Logger log = LoggerFactory.getLogger(WitAspect.class);

    @Pointcut("execution(public * org.witpool.rest.WitUserRest.*(..))")
    public void log()
    {
    }

    @Before("log()")
    public void doBefore(JoinPoint jp)
    {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attr.getRequest();

        // URL
        log.info("WIT: URL={}", req.getRequestURL());

        // Method
        log.info("WIT: HTTP Method={}", req.getMethod());

        // IP
        log.info("WIT: IP={}", req.getRemoteAddr());

        // 类方法
        log.info("WIT: REST CLASS={}", jp.getSignature().getDeclaringTypeName() + "." + jp.getSignature().getName());

        // 参数
        log.info("WIT: ARGS={}", jp.getArgs());
    }

    @After("log()")
    public void doAfter()
    {
        log.info("WIT: do after");
    }

    @AfterReturning(returning = "obj", pointcut = "log()")
    public void doAfterReturning(Object obj)
    {
        log.info("WIT: RESPONSE={}", obj.toString());
    }
}

5.Controller Advice 
WitExceptHandle.java

/* 
 * Copyright 2016-2017 WitPool.org All Rights Reserved.
 * 
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at

 *  http://www.witpool.org/licenses
 * 
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package org.witpool.common.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.witpool.common.enums.WitCode;
import org.witpool.common.except.WitException;
import org.witpool.common.model.bean.WitResult;

/** 
 * @class name: WitExceptHandle 
 * @description: WitPool Result 
 * @author Dom Wang 
 * @date 2017-11-15 PM 3:46:14 
 * @version 1.0 
 */
@ControllerAdvice
public class WitExceptHandle
{
    private final static Logger logger = LoggerFactory.getLogger(WitExceptHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public WitResult handle(Exception e)
    {
        if (e instanceof WitException)
        {
            WitException we = (WitException) e;
            return new WitResult(we.getCode(), we.getMessage());
        }
        else
        {
            logger.error(WitCode.WIT_ERR_INNER.getMsg() + "{}", e);
            return new WitResult(WitCode.WIT_ERR_INNER.getCode(), e.getMessage());
        }
    }
}

6.Jpa Repository 
WitRepository.java

/* 
 * Copyright 2016-2017 WitPool.org All Rights Reserved.
 * 
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at

 *  http://www.witpool.org/licenses
 * 
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package org.witpool.persist;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.witpool.common.model.po.WitUser;

/**
 * @Class Name : WitRepository
 * @Description: WitPool Repository
 * @Author     : Dom Wang
 * @Email      : witpool@outlook.com 
 * @Date       : 2017-11-15 PM 2:50:27 
 * @Version    : 1.0
 */
public interface WitRepository extends JpaRepository<WitUser, Integer>
{
    public List<WitUser> findByUserName(String userName);
}

7.代码下载、编译、打包 

代码下载请访问 GitHub上的 witpool/Wit-Neptune 
导入工程文件、编译、打包步骤如下: 
Eclipse 导入maven工程 
导入Maven工程

Maven打包 
Maven install打包

生成的JAR包

8.启动和UT步骤 
启动应用:java -jar wit-rest-1.0.jar 
启动应用

UT步骤: 
(1). 下载Wisdom REST Client 
(2). 双击 JAR包 restclient-1.1.jar 启动工具 
导入测试用例文件: 
WisdomTool RESTClient

 

目录
相关文章
|
3月前
|
Java API 数据库
构建RESTful API已经成为现代Web开发的标准做法之一。Spring Boot框架因其简洁的配置、快速的启动特性及丰富的功能集而备受开发者青睐。
【10月更文挑战第11天】本文介绍如何使用Spring Boot构建在线图书管理系统的RESTful API。通过创建Spring Boot项目,定义`Book`实体类、`BookRepository`接口和`BookService`服务类,最后实现`BookController`控制器来处理HTTP请求,展示了从基础环境搭建到API测试的完整过程。
66 4
|
4月前
|
Java 网络架构 Spring
springboot中restful风格请求的使用
本文介绍了在Spring Boot中如何使用RESTful风格的请求,包括创建HTML表单页面、在application.yaml配置文件中开启REST表单支持、编写Controller层及对应映射处理,并进行服务启动和访问测试。HTML表单默认只支持GET和POST请求,因此对于DELETE和PUT请求,需要使用隐藏域`_method`来支持。
springboot中restful风格请求的使用
|
3月前
|
Java API 数据库
如何使用Spring Boot构建RESTful API,以在线图书管理系统为例
【10月更文挑战第9天】本文介绍了如何使用Spring Boot构建RESTful API,以在线图书管理系统为例,从项目搭建、实体类定义、数据访问层创建、业务逻辑处理到RESTful API的实现,详细展示了每个步骤。通过Spring Boot的简洁配置和强大功能,开发者可以高效地开发出功能完备、易于维护的Web应用。
99 3
|
4月前
|
缓存 Java 应用服务中间件
随着微服务架构的兴起,Spring Boot凭借其快速开发和易部署的特点,成为构建RESTful API的首选框架
【9月更文挑战第6天】随着微服务架构的兴起,Spring Boot凭借其快速开发和易部署的特点,成为构建RESTful API的首选框架。Nginx作为高性能的HTTP反向代理服务器,常用于前端负载均衡,提升应用的可用性和响应速度。本文详细介绍如何通过合理配置实现Spring Boot与Nginx的高效协同工作,包括负载均衡策略、静态资源缓存、数据压缩传输及Spring Boot内部优化(如线程池配置、缓存策略等)。通过这些方法,开发者可以显著提升系统的整体性能,打造高性能、高可用的Web应用。
87 2
|
5月前
|
Java API 数据库
【神操作!】Spring Boot打造RESTful API:从零到英雄,只需这几步,让你的Web应用瞬间飞起来!
【8月更文挑战第12天】构建RESTful API是现代Web开发的关键技术之一。Spring Boot因其实现简便且功能强大而深受开发者喜爱。本文以在线图书管理系统为例,展示了如何利用Spring Boot快速构建RESTful API。从项目初始化、实体定义到业务逻辑处理和服务接口实现,一步步引导读者完成API的搭建。通过集成JPA进行数据库操作,以及使用控制器类暴露HTTP端点,最终实现了书籍信息的增删查改功能。此过程不仅高效直观,而且易于维护和扩展。
91 1
|
6月前
|
消息中间件 Java Kafka
Spring boot 自定义kafkaTemplate的bean实例进行生产消息和发送消息
Spring boot 自定义kafkaTemplate的bean实例进行生产消息和发送消息
237 5
|
5月前
|
Java 测试技术 API
SpringBoot单元测试快速写法问题之创建 PorkInst 实例如何解决
SpringBoot单元测试快速写法问题之创建 PorkInst 实例如何解决
|
5月前
|
XML Java 数据库
Spring5入门到实战------10、操作术语解释--Aspectj注解开发实例。AOP切面编程的实际应用
这篇文章是Spring5框架的实战教程,详细解释了AOP的关键术语,包括连接点、切入点、通知、切面,并展示了如何使用AspectJ注解来开发AOP实例,包括切入点表达式的编写、增强方法的配置、代理对象的创建和优先级设置,以及如何通过注解方式实现完全的AOP配置。
|
5月前
|
Java Spring
Spring Boot Admin 离线实例
Spring Boot Admin 离线实例
44 0
|
5月前
|
Java API
SpringBoot WebService 及 注意项
SpringBoot WebService 及 注意项
34 0