1.什么叫restful风格
restful是一组架构约束条件和原则,满足这些约束条件和原则的应用程序即是restful风格。
2.jax-rs实现步骤
1.创建一个简单应用(略)
2.添加依赖jar包
<!--cxf的客户端和服务端 --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-client</artifactId> <version>3.0.1</version> </dependency> <!-- CXF的json转换器,拓展json --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-extension-providers</artifactId> <version>3.0.1</version>
</dependency> <!-- 转换json的工具包,被cxf-rt-rs-extension-providers包依赖 --> <dependency> <groupId>org.codehaus.jettison</groupId> <artifactId>jettison</artifactId> <version>1.3.7</version> </dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.1</version>
</dependency>
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.1</version>
</dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.23</version> </dependency>
3.配置cxf的servlet
<servlet> <servlet-name>CXFService</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFService</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping>
4.配置webservice服务
<jaxrs:server id="userService"> <jaxrs:serviceBeans> <bean class="cn.cxf.rs.interfaces.impl.UserServiceImpl"></bean> <bean class="cn.cxf.rs.interfaces.impl.PetImpl"></bean> </jaxrs:serviceBeans> <jaxrs:inInterceptors> <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" /> </jaxrs:inInterceptors> <jaxrs:outInterceptors> <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" /> </jaxrs:outInterceptors> </jaxrs:server>
5.代码编写
接口定义
@Path("/userService") @Produces("*/*") public interface IUserService { @POST @Path("/saveUser") @Consumes({"application/json"}) @Produces({"application/json"}) User saveUser( User user); @POST @Path("/pet/{petId}") @Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_XML}) @Produces({"application/json"}) void pet(@PathParam("petId") String petId,@HeaderParam("xcl") String xcl,User user); @PUT @Path("/updateUser") @Consumes({"application/xml","application/json"}) @Produces({"application/json"}) void updateUser(User user); @GET @Path("/findAllUsers") @Produces({"application/json"}) List<User> findAllUsers(@QueryParam("status") String[] status); @GET @Path("/findUserById/{id}/{name}") @Produces({"application/json"}) @Consumes("applcation/xml") User findUserById(@PathParam("id") Integer id,@PathParam("name") String name); @DELETE @Path("/user/{id}") @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) void deleteUser(@PathParam("id") Integer id); @GET @Path("/findUserByArray") @Consumes({"applcation/xml","applcation/json"}) @Produces({"application/json"}) User findUserByArray(@QueryParam("name") String name,@QueryParam("id") String id); @POST @Path("/upload") @Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED}) void fileUpLoad( @Multipart("file") Attachment image,@Multipart("id") String id,@Multipart("name") String name); @GET @Path("/Context") @Consumes({MediaType.APPLICATION_XML}) void contextTest( @MatrixParam("mp") String[] mp,@CookieParam("cookie") Cookie cookie); @POST @Path("/testMultipart") @Consumes({MediaType.MULTIPART_FORM_DATA}) void testMultipart( @Multipart(value="file") Attachment image); @POST @Path("/postAttribute") @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) @Produces({MediaType.APPLICATION_JSON}) User postAttribute(@FormParam("name")String name,@FormParam("id")String id); @GET @Path("/getById/{id}") @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) User getById(@PathParam("id") String id); @GET @Path("/getMap") @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> getMap(); @GET @Path("/getByHeader/{id}") @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) User getByHeader(@PathParam("id") Integer id, @HeaderParam("xcl") String xcl); @POST @Path("/getListByForm") @Consumes({"application/xml","application/json",MediaType.APPLICATION_FORM_URLENCODED}) List<User> getListByForm( @FormParam("name")String name,@FormParam("id")String id); @POST @Path("/getListByBody") @Consumes({"application/json"}) @Produces("application/json") List<User> getListByBody(User user); @POST @Path("/getBodyByList") @Consumes({"application/xml","application/json",MediaType.APPLICATION_FORM_URLENCODED}) @XmlJavaTypeAdapter(MapAdapter.class) User getBodyByList(List<User> users); }
接口实现
public class UserServiceImpl implements IUserService { public User saveUser(User user) { System.out.println("save user:" + user); return user; } public void updateUser(User user) { System.out.println("update user:" + user); } public List<User> findAllUsers(String[] status) { for (String string : status) { System.out.println(string); } List<User> users = new ArrayList<User>(); User user1 = new User(); user1.setId(1); user1.setUsername("小强"); user1.setCity("北京"); List<Car> carList1 = new ArrayList<Car>(); Car car1 = new Car(); car1.setId(101); car1.setCarName("保时捷"); car1.setPrice(1000000d); carList1.add(car1); Car car2 = new Car(); car2.setId(102); car2.setCarName("宝马"); car2.setPrice(400000d); carList1.add(car2); user1.setCars(carList1); users.add(user1); return users; } public void deleteUser(Integer id) { System.out.println("delete user id :" + id); } public User findUserById(Integer id,String name) { if (id == 1) { User user1 = new User(); user1.setId(1); user1.setUsername("小明"); user1.setCity("北京"); String userString = JSON.toJSONString(user1); return user1; } return null; } public void pet(String petId, String xcl ,User user) { System.out.println(petId+","+xcl); } public User findUserByArray(String name,String id) { User user = new User(); user.setId(Integer.parseInt(id)); user.setUsername(name); return user; } public void fileUpLoad(Attachment image,String id,String name) { ContentDisposition contentDisposition = image.getContentDisposition(); System.out.println(contentDisposition.toString()); MediaType type = image.getContentType(); MultivaluedMap<String, String> maps = image.getHeaders(); Set<String> keysSet = maps.keySet(); for (String string : keysSet) { System.out.println(maps.get(string).toString()); } Object object = image.getObject(); System.out.println(object); System.out.println(id+","+type.toString()); /*try{ FileOutputStream outputStream = new FileOutputStream("d:/new.png"); DataHandler handler = image.getDataHandler(); InputStream in = handler.getInputStream(); byte[] bytes = new byte[1024]; int longer = 0; while ((longer=in.read(bytes))!=-1) { outputStream.write(bytes, 0, longer); } in.close(); outputStream.close(); System.out.println(handler.getName()); }catch(Exception e){ throw new RuntimeException(e); } */ } public void contextTest(String[] mp,Cookie cookie) { for (String string : mp) { System.out.println(string); } System.out.println(cookie.getValue()); } public void testMultipart(Attachment image) { try { /*File file = (File) image.getObject(); System.out.println(file.getName());*/ System.out.println(image.getContentId()); DataHandler handler = image.getDataHandler(); String type = handler.getContentType(); String name = handler.getName(); System.out.println(type+","+name); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } public User postAttribute(String name, String id) { System.out.println(name+","+id); User user = new User(); user.setId(11); user.setUsername("hah"); return user; } public User getById(String id) { User user = new User(); if(id.equals("1")){ user.setUsername("xcl"); } return user; } public Map<String, Object> getMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "xcl"); map.put("id", "11"); return map; } public User getByHeader(Integer id, String xcl) { System.out.println(id+","+xcl); return null; } public List<User> getListByForm(String name, String id) { List<User> users = new ArrayList<User>(); User user1 = new User(); user1.setId(1); user1.setUsername("小强"); user1.setCity("北京"); List<Car> carList1 = new ArrayList<Car>(); Car car1 = new Car(); car1.setId(101); car1.setCarName("保时捷"); car1.setPrice(1000000d); carList1.add(car1); Car car2 = new Car(); car2.setId(102); car2.setCarName("宝马"); car2.setPrice(400000d); carList1.add(car2); user1.setCars(carList1); users.add(user1); return users; } public List<User> getListByBody(User user) { List<User> users = new ArrayList<User>(); User user1 = new User(); user1.setId(1); user1.setUsername("小强"); user1.setCity("北京"); List<Car> carList1 = new ArrayList<Car>(); Car car1 = new Car(); car1.setId(101); car1.setCarName("保时捷"); car1.setPrice(1000000d); carList1.add(car1); Car car2 = new Car(); car2.setId(102); car2.setCarName("宝马"); car2.setPrice(400000d); carList1.add(car2); user1.setCars(carList1); users.add(user1); return users; } public User getBodyByList(List<User> users) { User user = new User(); user.setId(11); user.setUsername("xcl"); return user; }
6.注解讲解
@Path("/userService"):路径
@Produces("*/*"):产生内容 @Produces({"application/json"}),@Produces({"application/xml"});
@Consumes({"application/xml","application/json"}):消费内容;MediaType.APPLICATION_FORM_URLENCODED{表单内容}
MediaType.MULTIPART_FORM_DATA{附件内容}
@XmlRootElement(name="User")实体类根元素
@POST:post请求方式
@PUT:put请求方式,一般用于存储{不常用}
@GET:get请求方式
@DELETE:delete请求方式,一般用于删除{不常用}