Last active
August 29, 2015 14:21
-
-
Save jeorfevre/260067c5b265f65f93b3 to your computer and use it in GitHub Desktop.
GET user Jersey - http://stackoverflow.com/questions/30216798
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
id: 30216798 | |
uri: http://stackoverflow.com/questions/30216798 | |
tags: jersey rest get |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// register in you app the new Resource in order to serve it | |
register(UserResource.class); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can test it calling endpoint : | |
http://localhost:8080/user/details |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.rizze.skytest.uri; | |
import javax.ws.rs.GET; | |
import javax.ws.rs.Path; | |
import javax.ws.rs.Produces; | |
import javax.ws.rs.core.MediaType; | |
import javax.ws.rs.core.Response; | |
import javax.ws.rs.core.Response.Status; | |
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
@Path("/user") | |
public class UserResource{ | |
@GET | |
@Path("details") | |
@Produces( { MediaType.APPLICATION_JSON }) | |
public Response get_details(){ | |
BeanUser myUser = new BeanUser(); | |
boolean found = true; //perform process here to find user.... | |
if( found ==true){ | |
myUser.login="je"; | |
myUser.name="rizze"; | |
myUser.company="rizze"; | |
//found returns it as json | |
return Response.status(Status.FOUND).entity(myUser.toJson()).build(); | |
} | |
else{ | |
//not found | |
//return 404 if not found (better than 204 that means empty) | |
return Response.status(Status.NOT_FOUND).build(); | |
} | |
} | |
public class BeanUser{ | |
String login; | |
String name; | |
String company; | |
public String toJson(){ | |
ObjectMapper mapper = new ObjectMapper(); | |
try { | |
return mapper.writer().writeValueAsString(this); | |
} catch (JsonProcessingException e) { | |
return null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment