如何重定向html按钮 - > Servlet - >另一个HTML页面?

时间:2016-01-24 11:49:07

标签: servlets forward requestdispatcher

我有一个带有2个具有相同表单操作的按钮的html页面(当用户按下按钮时,表单将其重定向到servlet然后在该servlet中,我希望它根据按钮重定向到另一个html页面在html页面中按下)。

Html页面

<form action ="ManageEmployeeRedirect" method = "post"> 
<input type="submit" value="Create New Employee Account" name="ID1"> 
<br>
<br>
<input type="submit" value="Update Existing Employee Account" name="ID2"> 
</form>
</div>
</body>
</html>

的Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class ManageEmployeeRedirect extends HttpServlet { 

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String name = request.getParameter("ID1");
        String name2 = request.getParameter("ID2"); 

        if("ID1".equals(name)){
            RequestDispatcher rs = request.getRequestDispatcher("index.html");
            rs.forward(request, response);
        }
        else if("ID2".equals(name2)){ 
            RequestDispatcher rs = request.getRequestDispatcher("changePassAdmin.html"); 
            rs.forward(request, response);
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
               processRequest(request, response);
          }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
               processRequest(request, response);
    }
}

2 个答案:

答案 0 :(得分:0)

  1. 在第二个“if”中你错过了“名字”,我建议你使用“ID1”.equals(name)格式。
  2. 检查您的表单方法是否与servlet的方法doPost()相对应。
  3. 建议:在java中,您可以使用JSP技术。它是扩展的html格式,里面包含了implict java-servlet。

答案 1 :(得分:0)

 String button1 = request.getParameter("ID1");
        String button2 = request.getParameter("ID2"); 

        if(button1 != null) {
            RequestDispatcher rs = request.getRequestDispatcher("index.html"); 
            rs.forward(request, response);
        }
        else if(button2 != null) { 
            RequestDispatcher rs = request.getRequestDispatcher("changePassAdmin.html"); 
            rs.forward(request, response);
        }