Jax-rs (Jersey-based) + Spring 4.x + MyBatis building Rest Service architecture

Source: Internet
Author: User
Tags representational state transfer java web jboss jboss server pojo java

1. What is Jax-rs?

Jax-rs is a new technology introduced by Java EE6. Jax-rs, the Java API for RESTful Web Services, is an application interface for the Java programming language that supports the creation of WEB services in the Representational state Transfer (REST) architectural style.

Jax-rs uses Java annotations introduced in Java SE5 to simplify the development and deployment of client and server side of Web services.
Roy Fielding was also involved in Jax-rs's development, and he defined rest in his doctoral dissertation.

For developers who want to build restful Web services, Jax-rs gives another solution that differs from Jax-ws (JSR-224).


Jax-rs provides some annotations to encapsulate a resource class, a Pojo Java class, as a Web resource.

The framework based on JAX-RS implementation has jersey,resteasy and so on. The applications created by these two frameworks can be easily deployed to servlet containers, such as Tomcat,jboss.

It is worth mentioning that Resteasy was developed by JBoss, so deploying an application with the Resteasy framework to the JBoss server allows for a lot of additional functionality.

At present, there are 4 kinds of JAX-RS implementations, all of which support Spring,jersey is JAX-RS reference implementation, and this is the implementation of this article.

Jax-rs commonly used annotations:
@Path, label the relative path of the resource class or method
@GET, @PUT, @POST, @DELETE, the callout method is the type of the HTTP request.
@Produces, the type of MIME media returned by the callout
@Consumes, label the MIME media type that can accept the request
@PathParam, @QueryParam, @HeaderParam, @CookieParam, @MatrixParam, @FormParam,

The parameters of the separate annotation method come from different locations in the HTTP request.

For example

@PathParam the path from the URL,

@QueryParam query parameters from the URL,

@HeaderParam header information from the HTTP request,

@CookieParam the cookie from the HTTP request.

2. Why use Spring + MyBatis?

Spring I think it's not necessary to introduce, do Java all know.

MyBatis is an open source project for Apache Ibatis, which was migrated to Google code by the Apache Software Foundation in 2010 and renamed MyBatis.

Migrated to GitHub in November 2013.
MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings.
MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of the result set.

MyBatis uses simple XML or annotations for configuration and raw mapping, mapping interfaces and Java POJOs (Plain old Java Objects, ordinary Java objects) to records in a database.

The current status of Java EE development is that hibernate's data access layer has been declining, while lighter-weight mybati are gradually emerging in small and medium-sized projects.

3. Pre-development preparatory work

First of all, you want to download 2 necessary jars, one is jersey and the other is jersey-spring, since Jersey does not integrate spring by default, so the latter jar is especially important.

If you do not know where to download from, then the blogger provides:

Http://www.coolbaba.net/Upload/Jar/Jersey-Jax.zip

Then, create a new empty Java Web project, copy the downloaded 2 jars to your project and add a reference to them.

4. configuration file Editing

Need to prepare 2 configuration files, one is Spring-mybatis.xml,

It is the integrated configuration file for spring and MyBatis.

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:mvc= "Http://www.springframework.org/schema/mvc" Xsi:sche malocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans /spring-beans-3.1.xsd Http://www.springframework.org/schema/context http://w Ww.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/ MVC http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <!--automatically scanned-&lt ; Context:component-scan base-package= "BBC"/> <!--Introduction profile--<bean id= "Propertyconfigurer" CLA Ss= "Org.springframework.beans.faCtory.config.PropertyPlaceholderConfigurer "> <property name=" Location "value=" Classpath:jdbc.properties "/&G    T </bean> <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" &        Gt  <property name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "${jdbc.url}" /> <property name= "username" value= "${jdbc.username}"/> <property name= "password" value= "${jdb C.password} "/> <!--Initialize connection size--<property name=" InitialSize "value=" ${initialsize} "></pro        perty> <!--connection Pool Maximum number--<property name= "maxactive" value= "${maxactive}" ></property> <!--connection Pool Max idle--<property name= "Maxidle" value= "${maxidle}" ></property> <!--connection Pool min        Idle--<property name= "Minidle" value= "${minidle}" ></property> <!--get connection maximum wait time- <pRoperty name= "maxwait" value= "${maxwait}" ></property> </bean> <!--spring and MyBatis are seamlessly integrated without the need for MyBatis Configure the mapping file--<bean id= "sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property Name= "DataSource" ref= "DataSource"/> <!--automatically scans mapping.xml files--<property name= "mapperlocations "Value=" Classpath:bbc/mapping/*.xml "></property> <property name=" typealiasespackage "value=" Bbc.domai n "/> </bean> <!--DAO interface with the package name, spring will automatically find the class under it--<bean class=" Org.mybatis.spring.mapper.MapperSc Annerconfigurer "> <property name=" basepackage "value=" Bbc.dao "/> <property name=" sqlSessionFact Orybeanname "value=" sqlsessionfactory "></property> </bean> <!--(transaction management) transaction manager, use Jta TransactionManager for Global TX--<bean id= "TransactionManager" class= "Org.springframework.jdbc.datas Ource. DatasourcetransactioNmanager "> <property name=" dataSource "ref=" DataSource "/> </bean> <!--<bean id=" Spring ContextUtil "class=" Bbc.util.web.SpringContextUtil "scope=" singleton "/>--></beans>

The jdbc.properties configuration is as follows:

jdbc.driver=com.mysql.jdbc.driverjdbc.url=jdbc:mysql://localhost:3306/your_database?useunicode=true& characterencoding=utf-8jdbc.username=your_usernamejdbc.password=your_passwordinitialsize=0# defines the maximum number of connections maxactive=20 #定义最大空闲maxIdle =20# define the minimum idle minidle=1# to define the maximum wait time maxwait=60000

Finally, Web. xml

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:xsi= "htt P://www.w3.org/2001/xmlschema-instance "xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http://ja Va.sun.com/xml/ns/javaee/web-app_3_0.xsd "version=" 3.0 > <!--handling Chinese characters--<filter> &L T;filter-name>characterencodingfilter</filter-name> <filter-class> Org.springframework.web.filter.characterencodingfilter</filter-class> <init-param> <param        -name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> &LT;PARAM-VALUE&GT;TRUE&L t;/param-value> </init-param> </filter> <filter-mapping> <filter-name>chara Cterencodingfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>contextconfiglo Cation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param        > <listener> <listener-class> Org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <servlet> <servlet-name>comicjaxservlet</servle        T-name> <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>            <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>bbc.resource</param-value> </init-param> <load-on-startup>1</load-o n-startup> </servlet> <servlet-mapping> &LT;SERVLET-NAME&GT;COMICJAXSERVLET&LT;/SERVLET-NAME&G        T <url-pattern>/resources/*</url-pattern> </servlet-mapping></web-app> 

There are two places to pay special attention:

One is the configuration of the servlet, the class needs to be changed to

Com.sun.jersey.spi.spring.container.servlet.SpringServlet

Rather than the original

Com.sun.jersey.spi.container.servlet.ServletContainer (Error!! )

The second is the Init-param Bbc.resource is the package name of my rest service, here you can change to your own.

5. Writing domain Pojo

Series.java

Package bbc.domain;/** * Created by KG on 16/11/24.    */public class Series extends Basedomain {private int id;    private int SourceID;    private String name;    Private String Brief;    Private String address;    Private String folder;    Private String cover;    public int getId () {return id;    } public void setId (int id) {this.id = ID;    } public int Getsourceid () {return sourceid;    } public void Setsourceid (int sourceid) {This.sourceid = SourceID;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public String Getbrief () {return brief;    } public void Setbrief (String brief) {this.brief = brief;    } public String getaddress () {return address;    The public void setaddress (String address) {this.address = address;    } public String GetFolder () {return folder; } public void Setfolder (String folder) {       This.folder = folder;    } public String Getcover () {return cover;    } public void Setcover (String cover) {this.cover = cover; }}

6. Writing DAO and Mapping files

Seriesdao.java

Package Bbc.dao;import bbc.domain.series;import java.util.list;/** * Created by KG on 16/11/24. */public interface Seriesdao {    list<series> selectallrecords ();}

Seriesdao.xml

 <?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><  Mapper namespace= "Bbc.dao.SeriesDao" > <resultmap type= "Series" id= "Seriesresult" > <id property= "id" column= "id"/> <result property= "SourceID" column= "source_id"/> <result property= "name" column = "Name"/> <result property= "brief" column= "brief"/> <result property= "Address" column= "address        "/> <result property=" folder "column=" folder "/> <result property=" cover "column=" Cover "/> <result property= "Createtime" column= "Create_time"/> <result property= "Lastupda" column= "Last_upda        "/> </resultMap> <select id=" selectallrecords "resulttype=" Series "resultmap=" Seriesresult "> SELECT * from series </select></mapper> 

7. Write the rest service and inject the DAO into the service through spring

Seriesresource.java

Package Bbc.resource;import Bbc.dao.seriesdao;import Bbc.domain.series;import bbc.service.seriesservice;import Com.sun.jersey.api.core.injectparam;import Com.sun.jersey.spi.inject.inject;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Scope; Import Org.springframework.stereotype.component;import Org.springframework.stereotype.service;import Javax.annotation.resource;import Javax.ws.rs.get;import Javax.ws.rs.path;import Javax.ws.rs.Produces;import java.util.list;/** * Created by KG on 16/11/24. */@Path ("/series/") @Component @scope ("prototype") public class Seriesresource {    @Autowired    private Seriesdao Seriesdao;    @GET    @Produces ("Application/json") public    String getallseries () {        list<series> serieslist = Seriesdao.selectallrecords ();       ....    }}

The implementation of the DAO interface is automatically bound by autowired.

In general, the most used in our service is the POST request, if the post is also very simple, as follows:

@Path ("/some/") @Componentpublic class Someresource {    @POST    @Path ("/testpost")    @Produces ("application/ JSON ") public    string Testpost (String request) {        return" Response: "+ Request;    }}

The parameter request above will automatically receive a JSON string from the client, then you can choose to parse the JSON and deserialize it into the Pojo object for the next step.

Finally, the result is serialized into JSON and dropped back to the client.

All right, everything's done!!

To launch Tomcat, you can access your service from the following address:

Http://localhost:8080/resources/series

Jax-rs (Jersey-based) + Spring 4.x + MyBatis building Rest Service architecture

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.