我很难将url路径更新为更具可读性。路径曾经是https://mywebsite.com/article/EjJKd39
。如您所见,字母数字ID不太容易阅读。我只想更改它以显示文章标题(即https://mywebsite.com/article/change-url-pattern-in-java
)。
这是我的servlet代码。
@WebServlet(urlPatterns = {"/article/*"})
public class ArticleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Logic to retrieve article information from database.
String redirectUrl = "mywebsite.com/article/" + articleObject.getTitleOfArticle();
request.setAttribute("article", articleObject);
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", redirectUrl);
request.getRequestDispatcher("/article.jsp").forward(request, response);
}
}
如您所见,我正在尝试重定向到我的jsp文件,但使用的是新网址。但是发生的却是我收到404 not found错误。我在这里做错了什么?我似乎无法弄清楚。
我的问题不再是404错误。我意识到我的代码中有一段代码,如果无法从数据库中检索文章信息,它将发送404错误。我的真正问题是,在调用request.getRequestDispatcher("/article.jsp").forward(request, response)
并从浏览器请求URL之后,将调用ArticleServlet。这导致servlet中的代码再次运行,除了这次没有访问已设置的参数。我删除了404错误检查,仅允许Servlet无限运行。在没有这种情况的情况下如何实现我想要的?
答案 0 :(得分:0)
您只需使用sendRedirect
发送重定向。
使用指定的重定向位置URL将临时重定向响应发送到客户端,并清除缓冲区。用此方法将缓冲区替换为数据集。调用此方法会将状态代码设置为
SC_FOUND
302(已找到)。此方法可以接受相对URL; Servlet容器必须在将响应发送到客户端之前将相对URL转换为绝对URL。如果位置是相对的而没有前导“ /”,则容器会将其解释为相对于当前请求URI的相对位置。如果位置与前导“ /”相对,则容器将其解释为相对于servlet容器根。如果位置与两个前导“ /”相对,则容器会将其解释为网络路径引用。
@WebServlet(urlPatterns = {"/article/*"})
public class ArticleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect(articleObject.getTitleOfArticle());
}
}