Jersey_返回JSON格式

1. pom.xml添加依赖

 
    org.springframework.boot
    spring-boot-starter-parent
    1.4.2.RELEASE
 
 
    
        org.springframework.boot
        spring-boot-starter-web
    
         
      
       org.springframework.boot  
       spring-boot-starter-jersey  
      
 

2.application.properties配置文件

server.port=8087
spring.application.name=jerseyDemo

3.项目结构

Jersey_返回JSON格式_第1张图片
Paste_Image.png

4.SpringBoot集成Jersey,启动类照样即可,新建配置类,注册Jersey容器

@Configuration
@ApplicationPath("/rest")
public class JerseyConfig extends ResourceConfig {
     public JerseyConfig() {
        register(JerseyController.class);//返回json格式
        register(JerseyControllerXml.class);//返回xml格式
        //packages("com.vergilyn.demo.springboot.jersey"); // 通过packages注册。
     }
}

5.Controller类

//默认情况下,资源类的生命周期是per-request,也就是系统会为每个匹配资源类URI的请求创建一个实例,
//这样的效率很低,可以对资源类使用@Singleton注解,这样在应用范围内,只会创建资源类的一个实例
@Singleton 
@Component
@RestController
@Path("/jersey")
public class JerseyController {
    
        @GET
        @Path("get")
        //定义请求的媒体类型,如果不指定,则容器默认可接受任意媒体类型,容器负责确认被调用的方法可接受HTTP请求的媒体类型,否则返回415 Unsupported Media Type
        @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
        //定义响应媒体类型,如果不指定,则容器默认可接受任意媒体类型,容器负责确认被调用的方法可返回HTTP请求可以接受媒体类型,否则返回406 Not Acceptable
        @Produces(MediaType.APPLICATION_JSON)
        public Map getMessage() {
            Map map = new HashMap(); 
            map.put("Id", "100");
            map.put("Name", "Jimmy");
            return map;
        }

        @GET
        @Path("/get/{param1}/{param2}")
        @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
        @Produces(MediaType.APPLICATION_JSON)
        public String getMessageStr(@PathParam("param2")String userName,@DefaultValue("china")@QueryParam("address")String address) {
            System.out.println(address+"-==============");
            String str = "hello " + userName+"-"+address;
            return str;
        }
        
        @POST   
        @Path("/post")
        @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
        @Produces(MediaType.APPLICATION_JSON)
        public Map postMessage() {
            Map map = new HashMap(); 
            map.put("Id", "101");
            map.put("Name", "Lucy");
            return map;
        }
}

6.访问:注意路径

http://localhost:8087/rest/jersey/get

Jersey_返回JSON格式_第2张图片
Paste_Image.png

http://localhost:8087/rest/jersey/get/jim/wuxi?address=jiangsu--注意参数

Jersey_返回JSON格式_第3张图片
Paste_Image.png

你可能感兴趣的:(Jersey_返回JSON格式)