|
| 1 | +package com.baeldung.jersey.server.rest; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +import javax.ws.rs.GET; |
| 9 | +import javax.ws.rs.Path; |
| 10 | +import javax.ws.rs.PathParam; |
| 11 | +import javax.ws.rs.Produces; |
| 12 | +import javax.ws.rs.core.MediaType; |
| 13 | + |
| 14 | +import org.glassfish.jersey.server.mvc.ErrorTemplate; |
| 15 | +import org.glassfish.jersey.server.mvc.Template; |
| 16 | +import org.glassfish.jersey.server.mvc.Viewable; |
| 17 | + |
| 18 | +import com.baeldung.jersey.server.model.Fruit; |
| 19 | + |
| 20 | +@Path("/fruit") |
| 21 | +public class FruitResource { |
| 22 | + |
| 23 | + @GET |
| 24 | + public Viewable get() { |
| 25 | + return new Viewable("/index.ftl", "Fruit Index Page"); |
| 26 | + } |
| 27 | + |
| 28 | + @GET |
| 29 | + @Template(name = "/all.ftl") |
| 30 | + @Path("/all") |
| 31 | + @Produces(MediaType.TEXT_HTML) |
| 32 | + public Map<String, Object> getAllFruit() { |
| 33 | + final List<Fruit> fruits = new ArrayList<>(); |
| 34 | + fruits.add(new Fruit("banana", "yellow")); |
| 35 | + fruits.add(new Fruit("apple", "red")); |
| 36 | + fruits.add(new Fruit("kiwi", "green")); |
| 37 | + |
| 38 | + final Map<String, Object> model = new HashMap<String, Object>(); |
| 39 | + model.put("items", fruits); |
| 40 | + return model; |
| 41 | + } |
| 42 | + |
| 43 | + @GET |
| 44 | + @ErrorTemplate(name = "/error.ftl") |
| 45 | + @Template(name = "/named.ftl") |
| 46 | + @Path("{name}") |
| 47 | + @Produces(MediaType.TEXT_HTML) |
| 48 | + public String getFruitByName(@PathParam("name") String name) { |
| 49 | + if (!"banana".equalsIgnoreCase(name)) { |
| 50 | + throw new IllegalArgumentException("Fruit not found: " + name); |
| 51 | + } |
| 52 | + return name; |
| 53 | + } |
| 54 | + |
| 55 | +} |
0 commit comments