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打包

8.启动和UT步骤

启动应用:java -jar wit-rest-1.0.jar

UT步骤:

(1). 下载WisdomTool REST Client

(2). 双击 JAR包 restclient-1.1.jar 启动工具

导入测试用例文件:

关于WisdomTool REST Client更多的使用帮助,请参考GitHub wisdomtool/rest-client

总结

以上所述是小编给大家介绍的Spring Boot 实现Restful webservice服务端示例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • Spring整合CXF webservice restful实例详解

    webservice restful接口跟soap协议的接口实现大同小异,只是在提供服务的类/接口的注解上存在差异,具体看下面的代码,然后自己对比下就可以了. 用到的基础类 User.java @XmlRootElement(name="User") public class User { private String userName; private String sex; private int age; public User(String userName, String s

  • spring如何集成cxf实现webservice接口功能详解

    前言 由于cxf的web项目已经集成了Spring,所以cxf的服务类都是在spring的配置文件中完成的.以下是步骤: 第一步:建立一个web项目. 第二步:准备所有jar包.将cxf_home\lib项目下的所有jar包全部copy到新项目的lib目录下,里面已经包含了spring3.0的jar包. 第三步:在web.xml中配置cxf的核心servlet,CXFServlet. 第四步:创建(最好是Copy)cxf-servlet.xml文件.这是一个spring的配置文件. 1.web.

  • Spring boot 整合CXF开发web service示例

    前言 说起web service最近几年restful大行其道,大有取代传统soap web service的趋势,但是一些特有或相对老旧的系统依然使用了传统的soap web service,例如银行.航空公司的机票查询接口等. 目前就遇到了这种情况,需要在系统中查询第三方提供的soap web service接口,也就是说要将它整合进现有的系统当中. spring整合CXF本来十分简单,但是因为使用了Spring boot,不想用以前xml一堆配置的方式,那么能否按照Spring boot的

  • 详解Spring boot+CXF开发WebService Demo

    最近工作中需要用到webservice,而且结合spring boot进行开发,参照了一些网上的资料,配置过程中出现的了一些问题,于是写了这篇博客,记录一下我这次spring boot+cxf开发的webservice的配置过程,仅供参考. 一.本次开发除了用到spring boot基础jar包外,还用到了cxf相关jar包: <!-- cxf支持 --> <dependency> <groupId>org.apache.cxf</groupId> <

  • spring整合cxf框架实例

    CXF是webService的框架,能够和spring无缝整合 ##服务端编写 1.创建动态web项目 2.导入cxf和spring相关jar包(CXF核心包:cxf-2.4.2.jar) 3.在web.xml中配置CXF框架的核心Servlet <servlet> <servlet-name>cxf</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</s

  • 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&

  • Java spring boot 实现支付宝支付功能的示例代码

    一.准备工作: 1.登陆支付宝开发者中心,申请一个开发者账号. 地址:https://openhome.alipay.com/ 2.进入研发服务: 3.点击链接进入工具下载页面: 4.点击下载对应版本的RSA公钥生成器: 5.生成公钥密钥(记录你的应用私钥): 6.在支付宝配置公钥(点击保存): 二.搭建demo 1.引入jia包: <dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alip

  • Spring Boot加密配置文件特殊内容的示例代码详解

    有时安全不得不考虑,看看新闻泄漏风波事件就知道了我们在用Spring boot进行开发时,经常要配置很多外置参数ftp.数据库连接信息.支付信息等敏感隐私信息,如下 ​ 这不太好,特别是互联网应用,应该用加密的方式比较安全,有点类似一些应用如电商.公安.安检平台.滚动式大屏中奖信息等显示身份证号和手机号都是前几位4109128*********和158*******.那就把图中的明文改造下1. 引入加密包,可选,要是自己实现加解密算法,就不需要引入第三方加解密库 <dependency> &l

  • JQuery以JSON方式提交数据到服务端示例代码

    JQuery将Ajax数据请求进行了封装,从而使得该操作实现起来容易许多.以往我们要写很多的代码来实现该功能,现在只需要调用$.ajax()方法,并指明请求的方式.地址.数据类型,以及回调方法等.下面的代码演示了如何将客户端表单数据封装成JSON格式,然后通过JQuery的Ajax请求将数据发送到服务端,并最终将数据存储到数据库中.服务端定义为一个.ashx文件,事实上你可以将服务端定义为任何能接收并处理客户端数据的类型,如Web Service,ASP.NET Page,Handler等. 首

  • spring boot中使用http请求的示例代码

    因为项目需求,需要两个系统之间进行通信,经过一番调研,决定使用http请求. 服务端没有什么好说的,本来就是使用web 页面进行访问的,所以spring boot启动后,controller层的接口就自动暴露出来了,客户端通过调用对应的url即可,所以这里主要就客户端. 首先我自定义了一个用来处理http 请求的工具类DeviceFactoryHttp,既然是url访问,那就有两个问题需要处理,一个请求服务的url,和请求服务端的参数,客户端的消息头请求服务的url:请求服务端url我定义的是跟

  • 使用Spring Boot创建Web应用程序的示例代码

    在这篇文章中,我们将探讨使用Spring Boot创建Web应用程序的细节. 我们将探索Spring Boot如何帮助你加速应用程序开发. 我们将使用Spring Boot构建一个简单的Web应用程序,并为其添加一些有用的服务. 1. 介绍 启动一个新项目的主要挑战之一是该项目的初始设置. 我们需要对不同的目录结构进行调用,并且需要确保我们遵循所有行业标准.对于使用Spring Boot创建Web应用程序,我们需要以下工具: 我们自己喜欢的IDE (我将使用IntelliJ) Maven JDK

  • spring boot的拦截器简单使用示例代码

    1.spring boot拦截器默认有: HandlerInterceptorAdapter AbstractHandlerMapping UserRoleAuthorizationInterceptor LocaleChangeInterceptor ThemeChangeInterceptor 其中 LocaleChangeInterceptor 和 ThemeChangeInterceptor 比较常用. 2.实现自定义拦截器只需要3步: 1).创建我们自己的拦截器类并实现 Handler

  • 使用spring的websocket创建通信服务的示例代码

    基于socket通信,spring也有自己的socket通信服务:websocket,这次就介绍如何在spring项目中使用websocket进行通信交互. 后台:spring boot:前台:angularjs 后台建立服务 首先我们先建立起后台的服务,以实现进行socket连接. 1.引入websocket依赖 建立好一个maven项目之后,我们需要在xml中引入websocket的相关 依赖: <dependencies> <!--webSocket--> <depen

  • Spring Boot+AngularJS+BootStrap实现进度条示例代码

    Spring Boot+AngularJS+BootStrap实现进度条 原理 进度条的原理是在上传文件的时候,当程序运行到某一个部分,往Session中设置一个1到100的值.然后前台再每隔很小的一段时间去请求这个值. 在AngularJS中,$http对象有3种状态,分别是success,progress,error,其中progress方法就会在success方法调用之前(也就是上传完成之前),不断地调用.而我们要做的就是在progress中在添加一个请求,去后台拿我们设置在session

  • Spring Boot应用的极速部署脚本示例代码

    前言 本文主要给大家介绍了关于Spring Boot应用极速部署脚本的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 部署方法如下: 在 pom.xml 路径下新建文件 start.sh #!/bin/bash #0.删除原有的日志文件 rm -f nohup.out #1.获取正在运行的 Spring Boot 应用的 pid appPid=`netstat -ntlp | grep java | awk '{print $7}' | head -1 | grep

随机推荐