RequestDispacher 请求与分发使用HttpServletRequest的getRequestDispatcher()方法取得
Login.java页面
package control; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 实现请求后在请求然后再相应(请求LoginCheck后LoginCheck再请求ResultView,ResultView在响应) */ @WebServlet("/LoginCheck") public class LoginCheck extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String user=request.getParameter("user"); String pwd=request.getParameter("pwd"); if (user.equals("admin")&&pwd.equals("123")){ request.setAttribute("state","成功");//请求设置带参数 } else request.setAttribute("state","失败"); request.getRequestDispatcher("ResultView").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
ResultView.java页面
package control; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/ResultView") public class ResultView extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String jg = (String) request.getAttribute("state"); PrintWriter out = response.getWriter(); out.write(jg); out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }