`

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

 

分享到:
评论

相关推荐

    Spring Boot 实现Restful webservice服务端示例代码

    Spring Boot 实现Restful Webservice 服务端示例代码 Spring Boot 是一个基于 Java 的框架,用于快速构建生产级别的应用程序。它提供了许多有用的特性,如自动配置、嵌入式容器、生产准备等。下面,我们将探讨如何...

    android webservice 客户端、服务端实例

    Web Service服务端可以使用多种技术实现,如PHP、Java的Spring Boot、ASP.NET等。这里我们主要讨论Java环境下的实现。 1. **SOAP与RESTful API**: 两种常见的Web Service协议。SOAP是基于XML的,结构严谨但复杂;...

    webservice cxf spring整合返回list,bean,string,json,xml项目完整实例

    【标题】:在Java EE环境中,使用Apache CXF与Spring框架整合实现Web服务,返回List、Bean、String、JSON及XML的完整项目实例 【描述】:本项目旨在展示如何在Java企业级应用(Java EE)中,通过Apache CXF框架创建...

    CXF3.0.2+Spring3.2.14 WebService入门实例四

    2. **Spring框架与CXF的集成**:Spring通过其`Spring-WS`模块支持Web服务,但也可以通过Spring-Boot集成CXF,实现更灵活的服务配置。在本实例中,我们将使用Spring的依赖注入和配置管理特性,结合CXF的Web服务功能。...

    使用Xfire构建JAVA的webService全过程(从服务端到客户端)

    在IT行业中,Web服务是一种广泛使用的通信...然而,随着Web服务技术的发展,现在的开发者更倾向于使用Spring Boot集成的Web服务框架,如Spring Web Services或Spring MVC,它们提供了更全面的功能和更好的社区支持。

    spring-webservice-example

    "spring-webservice-example"项目恰好为我们提供了一个基于Spring框架构建Web服务的实例,这将帮助我们深入理解Spring如何处理Web服务的创建和交互。以下是对该项目的详细解析。 首先,我们要明确的是,Web服务是一...

    springboot web services例子 web服务例子

    本实例将深入探讨如何利用Spring Boot集成Apache CXF来创建Web服务,包括服务端和客户端的实现。 **一、Spring Boot与Web Services** Spring Boot以其“约定优于配置”的理念,极大地提高了开发效率。对于Web服务...

    WebServices服务端和客户端DEMO

    总结来说,"WebServices服务端和客户端DEMO"涵盖的内容广泛,包括Spring Boot的使用、Apache CXF的集成、服务端Web Services的创建、以及客户端的SOAP请求和响应处理。理解这些概念和技术对于开发分布式系统和实现跨...

    JAVA实现web service

    Spring框架提供了对Web Service的支持,可以通过Spring-WS或Spring Boot轻松地创建和消费Web Service,同时Spring的依赖注入和AOP特性使服务的管理更为便捷。 9. **调试与测试** 使用像SOAPUI这样的工具,可以...

    webservice入门教程

    2. 使用Spring Boot创建基于JAX-WS的SOAP服务,利用注解简化配置。 六、学习资源 1. "web+service入门教程ppt":这份PPT资料将深入浅出地介绍Web服务的基本概念,实例演示创建和使用Web服务的过程,对初学者非常...

    安卓网站交互JSONxmlWebserviceUPnP相关-android使用JSON进行网络数据交换(服务端客户端)的实现.zip

    这些API可以使用Java的Spring Boot或Node.js的Express等框架来实现。 4. **数据模型**:为了处理JSON数据,需要定义相应的Java类,这些类的属性与JSON对象的键相对应,方便解析和序列化。 5. **错误处理**:在网络...

    webservice创建加使用的文档

    尽管现在可能更多的开发者倾向于使用Apache CXF或Spring Boot等更现代的框架,但理解XFire的工作原理对学习Web服务的基础概念仍然有帮助。在XFire中,你需要选择包含基本依赖的前三个包,这些包通常包括核心服务、...

    cxfwebservice

    在 CXF 中,通常会有一个主程序类,它使用 `Spring` 或者 `Spring Boot` 来初始化服务,并启动服务器。例如,以下是一个简化的 Spring 配置示例: ```java @Configuration public class AppConfig { @Bean ...

    Web Service之XFire

    【正文】 Web服务是互联网上实现应用程序之间交互的一种标准方式,它...尽管现在已经有了更多现代的Web服务解决方案,如Apache CXF和Spring Boot,但XFire的历史地位和它所代表的技术理念仍然值得我们去学习和借鉴。

    Web service架构

    7. **开发工具与框架**:实践中,开发者可能会使用各种工具和框架来简化Web服务的开发,比如Java的Spring Boot和.NET的ASP.NET Core,它们都提供了方便的API来创建和消费Web服务。 8. **测试与调试**:对于Web服务...

Global site tag (gtag.js) - Google Analytics