Release REST services (jax-RS) using Spring + CXF

Keywords: REST Spring xml Apache

Today we focus on REST, another widely used Web service after SOAP. Unlike SOAP, REST does not have the concept of WSDL or what is called an "envelope", because REST advocates a simple and crude way to express data, which can be in JSON format or XML format. It's entirely up to you to decide.

The full name of REST is Representational State Transfer (Representational State Transfer). It is a paper on software architecture style written by Dr. Roy Fielding in 2000. Many well-known Internet companies have begun to adopt this lightweight Web service. It is customary to call it RESTful Web Services, or REST services for short.

So what exactly is REST?

REST is essentially a way of accessing resources using URLs. As we all know, URL is the request address we usually use. It includes two parts: request mode and request path. GET and POST are the common request modes. However, in REST, several other types of request modes are put forward, which can be summarized into six categories: GET, POST, PUT, DELETE, HEAD and OPTIONS. Especially the first four operations correspond to the four CRUD operations: GET (check), POST (increase), PUT (change), DELETE (delete), which is the secret of REST!

In fact, REST is a "stateless" architecture mode, because at any time the client can send requests to the server and eventually return the data they want. That is to say, the server publishes REST services with internal resources, and the client accesses these resources through URL s. Isn't that the idea of "service-oriented" advocated by SOA? Therefore, REST is also seen as a lightweight SOA implementation technology, so it has been widely used in enterprise applications and Internet applications.

In the Java world, there is a specification named JAX-RS, which is used to implement REST services. Now it has developed to version 2.0, namely JSR-339 specification. If you want to study REST deeply, please read this specification in depth.

JAX-RS specification currently has the following popular implementation technologies:

In this paper, CXF as an example, I strive to use the most refined text, so that you quickly learn how to use CXF to develop REST services, in addition, Spring and CXF will be integrated to make development more efficient!

Publishing REST services using Spring + CXF

Step 1: Adding Maven dependencies

    <properties>
        <cxf.version>3.0.0</cxf.version>
        <jackson.version>2.4.1</jackson.version>
    </properties>

    <dependencies>
        <!-- CXF -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <!-- Jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>

It relies only on Spring Web modules (no MVC modules are needed), in addition to CXF and Jackson.

Step 2: Configure web.xml

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>

Use the ContextLoaderListener provided by Spring to load the Spring configuration file spring.xml; and use the CXFServlet provided by CXF to process REST requests prefixed with / ws /.

Step 3: Publish the implementation class of the interface

user.java

@SuppressWarnings("restriction")
@XmlRootElement  
public class User implements Serializable{

    private static final long serialVersionUID = 1L;
}

UserService.java

@Path("/user")
@Produces( {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public interface UserService {
    /** 
     * Get getMap 
     */  
    @GET
    @Path("/getMap")
    @Produces( {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
    public Map<String,String> getMap();

    /** 
     * Get getBean 
     */  
    @GET
    @Path("/getBean")
    @Produces( {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
    public User getBean();
}

UserServiceImp.java

@Service("userService")
public class UserServiceImp implements UserService{
    @Autowired 
    private UserDao userDao;

   public Map<String, String> getMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("111", "222");
        return map;
    }

    public User getBean() {
        User user = new User();
        user.setUsername("huangyu");
        user.setPassword("123456");
        return userDao.findUser(user);
    }
}

Entities need to be serialized!

Step 4: Configure Spring

spring.xml

& lt;! -- Auto-scan contains @Service and injects it into beans - & gt;
<context:component-scan base-package="com.hy.loong"/>
<import resource="rest-webservice.xml"/>

rest-webservice.xml

<?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:jaxrs="http://cxf.apache.org/jaxrs"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxrs
    http://cxf.apache.org/schemas/jaxrs.xsd">
    <bean id="Jackson" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"></bean>  
    <jaxrs:server address="/user">
     <jaxrs:serviceBeans>
         <ref bean="userService"/>
     </jaxrs:serviceBeans>
     <jaxrs:providers>
         <ref bean="Jackson"/>
     </jaxrs:providers>
    </jaxrs:server>
</beans>

Use the Spring namespace provided by CXF to configure Service Bean (the Resouurce Class mentioned above) and Provider. Note that an address attribute is configured as "/ rest" to represent the relative path of REST requests, combined with the "/ ws/*" configuration in web.xml. The final root path of REST requests is "/ ws/rest", and the path configured by the @Path annotation on the Product Service interface method is only a relative path.

Step 5: Call REST services Request: http://localhost:8080/Loong/ws/user/user/getMap

Return:

{
  "11": "222"
}

Request: http://localhost:8080/Loong/ws/user/user/getBean

Return:

{
  "id": 1,
  "username": "huangyu",
  "password": "123456"
}
Reference resources:

[https://my.oschina.net/huangyong/blog/294324?utm_source=tuicool&utm_medium=referral]

Posted by hours12 on Wed, 17 Apr 2019 09:09:34 -0700