如何在doGet()或doPost()中更改URL

时间:2014-10-23 14:29:43

标签: java jsp

我需要让url成为我从数据库返回的电影的标题。 mywebsite.com/movie_name

问题是它无限循环并且从不显示我的页面index.jsp

我知道它不会,因为我需要在某处指定它,但我不知道在哪里。我试过了  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("index.jsp/"+movieName)但是它不起作用或者保持循环。另外,我不希望我的网址中包含'index.jsp'

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

    String movieName="movie";
    try {
        movieName = putMovieInSession(request);
    } catch (Exception e) {
        throw new ServletException(e);
    }
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+movieName);

    dispatcher.forward(request, response);
}


<servlet>
        <servlet-name>movie</servlet-name>
        <servlet-class>package.MovietServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>movie</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    ...

3 个答案:

答案 0 :(得分:0)

如果您想更改浏览器中的网址,则必须perform a redirect

另见the difference between forward and redirect

答案 1 :(得分:0)

检查以下行,你必须以正确的方式追加。

RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("index.jsp?movieName="+movieName);

并在index.jsp中从请求对象中获取movieName并显示您想要显示的位置。希望这有助于..

答案 2 :(得分:0)

"/"是您的容器根目录,它是您的catalina home目录而不是您的webapp directory。尝试将其更改为以下内容:

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(movieName);

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(request.getContextPath()+movieName);