29

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

例如:

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);
    }
}
4

3 回答 3

35

HttpServletResponse#sendRedirect(String location)方法。

将其用作:

response.sendRedirect(request.getContextPath() + "/welcome.jsp")

或者,看HttpServletResponse#setHeader(String name, String value)方法。

通过添加位置标头来设置重定向:

response.setHeader("Location", request.getContextPath() + "/welcome.jsp");
于 2012-11-29T09:13:38.407 回答
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页面路径进行更改。

于 2012-11-29T09:20:29.833 回答
3
    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();
        }
于 2014-02-25T16:56:41.840 回答