如何在Servlet中向JSP页面发送重定向?

29

当我在servlet中处理完并且结果合法时,我需要将响应重定向到另一个JSP页面,比如web内容文件夹中的welcome.jsp。我该怎么做呢?

例如:

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

         // Some processing code here ...

         // How do I redirect to another JSP here when I'm ready?

    } catch (Exception e) {
        throw new ServletException(e);
    }
}
3个回答

37

22
请勿发布无效语法的示例。sendRedirect() 方法不是静态方法。setHeader() 也是如此。 - DSoa
3
在你的doPost方法中,用response变量替换HttpServletResponse即可。没什么大不了的。 - HFR1994

3
请使用下面的代码并让我知道。
try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp 是你的 jsp 页面的相对路径。因此,根据你的 jsp 页面路径进行更改。


2
    String u = request.getParameter("username");
    String p = request.getParameter("password");

    try {
        st = con.createStatement();
        String sql;
        sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
                + p + "'";
        ResultSet rs = st.executeQuery(sql);
        if (rs.next()) {
            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/home.jsp");
            requestDispatcher.forward(request, response);
        } else {

            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/invalidLogin.jsp");
            requestDispatcher.forward(request, response);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    finally{
        try {
            rs.close();
            ps.close();
            con.close();
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

6
你可以在代码中添加一些注释或解释你正在做什么,而不只是发布代码,这样可以提高你的回答质量。 - mathielo
3
请不要散布SQL注入易受攻击的代码,即使是作为示例。 - Trevor Harrison
2
@TrevorHarrison 你说得对。示例是常见安全漏洞仍然存在的主要原因。 - asgs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接