带参数问题的servlet url模式

时间:2017-12-12 20:07:41

标签: java jsp servlets

当我访问“http://localhost:8080/project/Song”时,不会出现任何错误,它会在页面中列出一些歌曲。当我点击一首歌时,我会转到一个网址“http://localhost:8080/SongPage?name=A+Tribe&id=201”,但此处显示404错误,可能是因为该网址有参数,访问此网址时出现错误:

HTTP状态404 - 未找到

描述源服务器没有找到目标资源的当前表示,或者不愿意透露该目标资源是否存在。

你知道为什么吗?

也许是因为下面这个urlPattern:

@WebServlet(name =“SongPage”,urlPatterns = {“/ SongPage”})

我在下面有这个servlet:

@WebServlet(name ="Song", urlPatterns = {"/Song"})
public class Song extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        QueryManager qm = new QueryManager();
        ArrayList<ArrayList<String>> result = qm.Songs();
        qm.closeConnections();

        request.setAttribute("result", result.get(0));
        request.setAttribute("id", result.get(1));
        RequestDispatcher view=request.getRequestDispatcher("songList.jsp");
        view.forward(request,response);    

    }
}

在songList.jsp中我有这个:

<c:forEach items="${result}" var="item" varStatus="status">
  <a href="/SongPage?name=${result[status.index].replace(" ","+")}&id=${id[status.index]}"> ${result[status.index]} </a> <br />
</c:forEach>

SongPage.java:

@WebServlet(name ="SongPage", urlPatterns = {"/SongPage"})
public class SongPage extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name").replace("+"," ");

    ...
 }

1 个答案:

答案 0 :(得分:1)

您原来的网址&#34; http://localhost:8080/project/Song&#34;有&#34;项目&#34;作为基本路径,但另一个网址&#34; http://localhost:8080/SongPage?name=A+Tribe&id=201&#34;没有那条路。您很可能需要更新JSP以将其包含在&#34; href&#34;标记为快速修复:

<a href="project/SongPage?name=${result[status.index].replace(" ","+")}&id=${id[status.index]}"> ${result[status.index]} </a> <br />

或者很可能,如果它实际上是一个上下文路径:

<a href="${pageContext.request.contextPath}/SongPage?name=${result[status.index].replace(" ","+")}&id=${id[status.index]}"> ${result[status.index]} </a> <br />