Java Reference
In-Depth Information
public String add(@QueryParam("text") String text){
this.message = text;
return message;
}
}
In the example, the
@Path
annotation specifies
/simplerest
as the service path, so the URL
http://localhost:8080/IntroToJavaEE7/rest/simplerest
will invoke the web service. It is possible to include
variables within a URL by enclosing them in the
@Path
annotation, within brackets using the syntax
{var}
. For
example, if each user had his or her own profile for a particular site, the
@Path
designation could be as follows:
...
@Path("/simplerest/{user}")
...
In such a case, the URL could look like the following:
In addition to specifying the
@Path
annotation at the class level, it can also be specified before any methods that
are marked with
@GET
,
@POST
,
@PUT
, or
@DELETE
in order to specify a URI for invoking the denoted method. Moreover,
variables can be placed within the path in order to accept a more dynamic URL. For instance, suppose a method was
added to the class in Solution #1 that would return a greeting for the user specified as a parameter within the URL.
You can do something like the following in order to make the URL unique:
@Path("{user}")
@GET
@Produces("text/html")
public String getUserMessage(@PathParam("user") String user){
return "Greetings " + "<b>" + user + "</b>";
}
In this case, the
getUserMessage
method would be invoked if a URL such as the following were placed into the
browser:
http://localhost:8080/IntroToJavaEE7/rest/simplerest/josh
. If this URL were specified, then the
method would be invoked, passing
josh
as the user variable value, and the message would be displayed as follows:
Greetings josh
Producing Content
To produce content via a web resource, create a Java class and annotate it with the
@Path
annotation, specifying a path
you want to use for publishing the resource. Use the
@Produces
annotation to specify the MIME type for content you
want to produce from a decorated method. The following excerpt demonstrates the use of
@Produces
:
...
@GET
@Path("/get")
// Produces an XML message
@Produces(MediaType.APPLICATION_XML)
public String getProducts() {
List<Product> productList = productSession.findAll();
StringBuilder xmlstring= new StringBuilder();