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      : [email protected]
 * @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      : [email protected]
 * @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打包 

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

时间: 2024-11-01 00:23:44

Spring Boot 实现RESTful webservice服务端示例的相关文章

CXF+Spring+Hibernate实现RESTful webservice服务端实例

1.RESTful API接口定义 /* * 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

webservice服务端示例

第一步,写一个接口类: package webservice; import javax.jws.WebMethod; import javax.jws.WebService; /* * SEI */ @WebService public interface HelloWS { //声明 @WebMethod public String sayHello(String name); } 第二步,写一个接口实现类: package webservice; import javax.jws.WebS

spring + cxf 的webservice服务端和客户端功能

原文:spring + cxf 的webservice服务端和客户端功能 源代码下载地址:http://www.zuidaima.com/share/1550463730928640.htm spring + cxf 的webservice服务端和客户端功能. 提供页面调用ws和java代码调用两种方式. 引用jar包请下载:http://pan.baidu.com/s/1jGog2WI

【webservice】发布axis2的webservice服务端

axis2版本:axis2-1.5.4 准备工作:下载axis2-1.5.4-war.zip(生成服务端).axis2-1.5.4-bin.zip(axis2的jar包),jdk5(及以上版本).tomcat(端口我设成8086了) 手把手超级详细介绍axis2的webservice服务端的生成与发布. 1. 解压axis2-1.5.4-war.zip得axis2.war,把axis2.war放到tomcat的webapps目录, 启动tomcat就能加载axis2.war并生成新的axis2目

C#根据WSDL文件生成WebService服务端代码

转自:http://www.cnblogs.com/liyi93/archive/2012/01/30/2332320.html 虽然现在已经进入了.NET FrameWork 4.0的时代,WebService也已经逐渐被淘汰,取而代之的是WCF. 但在工作中难免遇到需要兼容旧版本程序和按照以前的文档进行开发. 一般一个已经实现功能的WebService会发布自己的WSDL文件,供客户端调用生成代理类. 但有时是先有server与client交互的接口定义(WSDL)文件,然后由server和

PHP写webservice服务端

1) WebService技术介绍 WebService是一种跨编程语言和跨操作系统平台的远程调用技术.仅仅有通过Web Service,client和server才可以自由的用HTTP进行通信.不论两个程序的平台和变成语言是什么. XML.SOAP和WSDL是Web Service平台的三大技术: WebService採用HTTP协议数据传输.採用XML格式封装数据,即XML中说明调用远程服务对象的哪个方法.传递的參数是什么.以及服务对象的返回结果是什么. XML是WebService平台中表

myeclipse-简历webservice服务端和客户端

一.建立webservice服务端: 1.新建一个web service project,名称为webservice_server截图如下,点击finish. 2.选择工程,点击右键,选择new->other,选择myelipse中的webservice->Web Service,点击next, 此处的hello可在server.xml中匹配可见,点击finish,然后修改其生成的方法. 3.将该工程部署至Tomcat中,并启动该工程,在浏览器中输入http://localhost:8080/

delphi调用 java 的 WebService服务端.

// InvRegistry.RegisterInvokeOptions(TypeInfo(ModelADServicePortType), ioLiteral); InvRegistry.RegisterInvokeOptions(TypeInfo(ModelADServicePortType), ioDocument); delphi调用 java 的 WebService服务端.,布布扣,bubuko.com

JAVA WEBSERVICE服务端&amp;客户端的配置及调用(基于JDK)

前言:我之前是从事C#开发的,因公司项目目前转战JAVA&ANDROID开发,由于对JAVA的各种不了解,遇到的也是重重困难.目前在做WEBSERVICE提供数据支持,看了网上相关大片的资料也是云里雾里的,索性最后得以解决,现将代码及方法发布如下,有需要的朋友可以参考,谢谢! --------------------------------------------------- WEBSERVICE服务端 package lavasoft; import javax.jws.WebMethod;