REST (5) CXF implements REST

Apache CXF was generally used to develop Web Services based on the SOAP protocol. In fact, CXF also implements the JAX-RS (JSR311) interface. Here we use it to implement the REST API.

1. For the basic environment
of spring web, see the web project testRest created in the previous chapter.

2. The REST address
is similar to the previous section, design the RESTEasy module /restCxf/*.

3. The RESTEasy library
adds RESTEasy dependencies to the project pom.xml:
<properties>
	<restCxf.version>3.1.0</restCxf.version>
</properties>
<dependencies>	
	...
	<!-- restCxf begin -->
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-rt-frontend-jaxws</artifactId>
		<version>${restCxf.version}</version>
	</dependency>
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-rt-transports-http</artifactId>
		<version>${restCxf.version}</version>
	</dependency>
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-rt-transports-http-jetty</artifactId>
		<version>${restCxf.version}</version>
	</dependency>
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-rt-frontend-jaxrs</artifactId>
		<version>${restCxf.version}</version>
	</dependency>
	<dependency>
	    <groupId>org.apache.cxf</groupId>
	    <artifactId>cxf-rt-rs-client</artifactId>
	    <version>${restCxf.version}</version>
	</dependency>
	<!-- restCxf end -->
	...

Add cxf jaxrs library, http library and client library.

4. Servlet
configures RESTEasy access entry.
<!-- restCxf -->
<servlet>
	<servlet-name>restCxf</servlet-name>
	<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>restCxf</servlet-name>
	<url-pattern>/restCxf/*</url-pattern>
</servlet-mapping>

restCxfServlet will intercept all accesses under /restCxf/*.

5. Implement the api to
create a new com.sunbin.test.restCxf package and add a TeachersResource class to implement the interface of the /teachers path:
package com.sunbin.test.restCxf;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sunbin.test.teacher.pojo.Teacher;
import com.sunbin.test.teacher.service.TeacherService;

@Component
@Path("teachers")
@Produces(MediaType.APPLICATION_JSON)
public class TeachersResource {

	@Autowired
	private TeacherService teacherService;
	
	@GET
    public Map get(@Context HttpServletRequest arg0) {
		System.out.println("RestCxf TeachersResource.get:"
				+ arg0.getSession().getId());
		Map map = new HashMap();
		map.put("teachers", teacherService.list());
		return map;
    }
	
	@POST
	public Map post(@FormParam("age")  int age,@FormParam("name")  String name){
		Map map = new HashMap();
		try {
			Teacher teacher = new Teacher();
			teacher.setName(name);
			teacher.setAge(age);
			System.out.println("RestCxf TeachersResource.post:"+teacher);
			teacherService.save(teacher);
			map.put("status", "y");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		return map;
	}
}

Path annotation @Path, return type annotation @Produces, access method @GET, parameter read @FormParam are the same as Jersey's JAX-RS.

Add the TeacherResource class to implement the interface of the /teacher/{id} path:
package com.sunbin.test.restCxf;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sunbin.test.teacher.pojo.Teacher;
import com.sunbin.test.teacher.service.TeacherService;

@Component
@Path("teacher/{id}")
@Produces(MediaType.APPLICATION_JSON)
public class TeacherResource {

	@Autowired
	private TeacherService teacherService;
	
	@GET
    public Map get(@PathParam("id")  int id) {
		System.out.println("RestCxf TeacherResource.get:"+id);
		Teacher teacher = new Teacher();
		teacher.setId(id);
		Map map = new HashMap();
		map.put("teacher", teacherService.get(teacher));
		return map;
    }
	
	@PUT
	public Map put(@PathParam("id")  int id,@FormParam("age")  int age,@FormParam("name")  String name){
		Map map = new HashMap();
		try {
			Teacher teacher = new Teacher();
			teacher.setId(id);
			teacher.setName(name);
			teacher.setAge(age);
			System.out.println("RestCxf TeacherResource.put:"+id+":"+teacher);
			teacherService.update(teacher);
			map.put("status", "y");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		return map;
	}
	
	@DELETE
	public Map delete(@PathParam("id")  int id){
		Map map = new HashMap();
		try {
			System.out.println("RestCxf TeacherResource.delete:"+id);
			Teacher teacher = new Teacher();
			teacher.setId(id);
			teacherService.remove(teacher);
			map.put("status", "y");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		return map;
	}
}


6.js test
Use the test page src\main\webapp\rest\index.jsp in the previous section to test:
...
	<script type="text/javascript">
		// test framework
		//var restType = "jersey";
		//var restType = "restlet";
		//var restType = "resteasy";
		var restType = "restCxf";
		//var restType = "restMvc";
...

After redeploying, use a browser to visit http://localhost:8080/testRest/rest , the test content is the same as the Restlet test.

7.CXF Client test
CXF provides rest Client library for testing REST interface.
Create a new TestRestCxf class with the following code:
package com.sunbin.test.restCxf;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.apache.cxf.jaxrs.client.WebClient;

public class TestRestCxf {

	public static final String URL_BASE = "http://localhost:8080/testRest/restCxf/";

	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "config/restCxf/restCxfClient.xml" });
		WebClient teachersClient = (WebClient) context
				.getBean("teachersClient");
		WebClient teacherClient = ((WebClient) context.getBean("teacherClient"))
				.path("{id}", "1");

		String module = "teacher";
		String url = "";
		String result = "";
		Entity<Form> entity = null;
		Form form = null;

		url = URL_BASE + module + "s";
		System.out.println("get\t" + url);
		result = teachersClient.get(String.class);
		System.out.println(result);

		url = URL_BASE + module + "s";
		System.out.println("post\t " + url);
		form = new Form().param("age", "1").param("name", "a");
		entity = Entity.form(form);
		result = teachersClient.post(entity, String.class);
		System.out.println(result);

		url = URL_BASE + module + "s";
		System.out.println("get\t" + url);
		result = teachersClient.get(String.class);
		System.out.println(result);

		url = URL_BASE + module + "/1";
		System.out.println("get\t " + url);
		result = teacherClient.get(String.class);
		System.out.println(result);

		url = URL_BASE + module + "/1";
		System.out.println("put\t " + url);
		form = new Form().param("age", "11").param("name", "aa");
		entity = Entity.form(form);
		result = teacherClient.put(entity, String.class);
		System.out.println(result);

		url = URL_BASE + module + "s";
		System.out.println("get\t" + url);
		result = teachersClient.get(String.class);
		System.out.println(result);

		url = URL_BASE + module + "/1";
		System.out.println("delete\t " + url);
		result = teacherClient.delete().readEntity(String.class);
		System.out.println(result);

		url = URL_BASE + module + "s";
		System.out.println("get\t" + url);
		result = teachersClient.get(String.class);
		System.out.println(result);
	}
}

The test results are similar to Restlet.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326487302&siteId=291194637