Spring Boot Implementation RESTful WebService server example

Source: Internet
Author: User
Tags getmessage

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 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 F Ile.  This file was 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 */@SpringBootApplicationpublic class Wit    app{public static void Main (string[] args) {Springapplication.run (witapp.class, args); }}

3.Rest controller 
Wituserrest.java

/* * Copyright 2016-2017 witpool.org All rights Reserved. * * 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 F Ile.  This file was 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 L    og = 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 Witresul            T<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 (@Request    Body Wituser user) {return witutil.success (reposit.save (user)); }/** * * @Title: DeleteUser * @Description: Delete User by ID * @param @param userId * @param @return * @return Witresult<witus er> * @throws * * * @DeleteMapping (value = "/{userid}") Public witresult<wituser> DeleteUser (@PathVaria        BLE ("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<witu    Ser> Getuserbyid (@PathVariable ("userid") Integer userId) {return witutil.success (userid)); }/** * * @Title: Getuserbyname * @Description: Get user by name * @param @param userName * @param @return * @return witresult<wituser> * @throws */@GetMapping (value = "/name/{username}") Public Wi Tresult<wituser> Getuserbyname (@PathVaRiable ("UserName") String userName) {return witutil.success (Reposit.findbyusername (userName)); }/** * * @Title: Getusers * @Description: Get All Users * @param @return * @return Witresult<wit user> * @throws * * @GetMapping public witresult<wituser> getusers () {return witutil.succe    SS (Reposit.findall ()); }}

4.aspect 
Witaspect.java

/* * Copyright 2016-2017 witpool.org All rights Reserved. * * 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 F Ile.  This file was 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 @componentpublic 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 ()); Class method Log.info ("Wit:rest class={}", Jp.getsignature (). Getdeclaringtypename () + "." + jp.getsignature (). GetName ())        ; Parameter 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.in    Fo ("wit:response={}", obj.tostring ()); }}

5.Controller advice 
Witexcepthandle.java

/* * Copyright 2016-2017 witpool.org All rights Reserved. * * 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 F Ile.  This file was 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-15PM 3:46:14 * @version 1.0 */@ControllerAdvicepublic class witexcepthandle{private final static Logger Logger = Logge    Rfactory.getlogger (Witexcepthandle.class); @ExceptionHandler (value = exception.class) @ResponseBody public witresult handle (Exception e) {if (E inst            Anceof 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. * * 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 F Ile.  This file was 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 (Stri ng UserName);}

7. Code download, compile, package

To download the code, visit the Witpool/wit-neptune on GitHub.
Import the project file, compile, and package the following steps:
Eclipse Import Maven Project

Maven Pack

8. Start and UT steps
Launch application: Java-jar Wit-rest-1.0.jar

UT steps:
(1). Download Wisdomtool REST Client
(2). Double-click the Jar package Restclient-1.1.jar startup tool
To import a test case file:

For more help with Wisdomtool REST client, refer to GitHub wisdomtool/rest-client

Spring Boot Implementation RESTful WebService server example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.