请把下面这段代码改成rest风格 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); List<Product> productList = (List<Product>) getServletContext().getAttribute("products"); for (Product product : productList) { String item = response.encodeURL(request.getContextPath() + "/item?id=" + product.getId()); response.getWriter().println("<a href='" + item + "'>" + product.getName() + "</a>"); } response.getWriter().println("浏览足迹为:"); History.showRecentViews(request, response); }
时间: 2024-02-06 12:04:07 浏览: 86
将该段代码改成REST风格后,可以将其转换为以下形式:
```
@GET
@Path("/products")
@Produces(MediaType.TEXT_HTML + ";charset=utf-8")
public void getProducts(@Context ServletContext context, @Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException, ServletException {
List<Product> productList = (List<Product>) context.getAttribute("products");
for (Product product : productList) {
String item = response.encodeURL(request.getContextPath() + "/item?id=" + product.getId());
response.getWriter().println("<a href='" + item + "'>" + product.getName() + "</a>");
}
response.getWriter().println("浏览足迹为:");
History.showRecentViews(request, response);
}
```
在这个新的代码中,我们使用了 `@GET` 注解和 `@Path` 注解来定义 REST API 的路径,使用了 `@Produces` 注解来指定返回的媒体类型。同时,我们还使用了 `@Context` 注解来注入 `ServletContext`、`HttpServletRequest` 和 `HttpServletResponse` 对象,从而使得代码更加简洁和易于维护。
阅读全文