【问题标题】:how to redirect to a new page from servlet如何从 servlet 重定向到新页面
【发布时间】:2019-07-16 09:55:03
【问题描述】:

我正在使用 json 格式的 JQuery 从login.html 向 servlet 发送数据到 servlet,在匹配记录后,我想打开一个新页面 home.html,我还想将数据发送到 home.html

DTORegisteration dto=new DTORegisteration();
        public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String id = req.getParameter("id");

        String password = req.getParameter("password");
        System.out.println("id "+id);
        System.out.println("password  "+password);
        dto.setId(id);          
        dto.setPassword(password);
        String str=new ServiceRegisteration().getDetails(dto);
        JSONObject json=new JSONObject();
        if(str.equals("success")) {

           try { json.put("welcome", "welcome"); json.put("name",
           DAORegisteration.name); 
           }catch(JSONException e) { e.printStackTrace(); }
           pw.print(json);



        }
    }

【问题讨论】:

标签: html mysql database servlets servlet-3.0


【解决方案1】:

HttpServletResponse 接口的 sendRedirect() 方法可用于将响应重定向到另一个资源,可以是 servlet、jsp 或 html 文件。

 if(check your param values here) { // if its as expected
                res.sendRedirect("home.html");
    } 

其实 我们不能使用 sendRedirect() 方法发送 post 请求,因为根据标准重定向应该使用 get。

您可以使用RequestDispatcher类来转发()带参数的请求,

例如-

req.setAttribute("Greetings", "Greeting of day");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("url");
dispatcher.forward(req, res);

【讨论】:

  • 我想在重定向的时候发送用户相关数据,可以吗?
  • @shahbazusmani,因为它对您有用,请为答案投票
猜你喜欢
  • 2015-07-24
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
相关资源
最近更新 更多