Servlet 中 RequestDispacher 请求与分发

Posted 蓬鹏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet 中 RequestDispacher 请求与分发相关的知识,希望对你有一定的参考价值。

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 {

    }
}

 

以上是关于Servlet 中 RequestDispacher 请求与分发的主要内容,如果未能解决你的问题,请参考以下文章

javaWeb中servlet开发——Servlet生命周期

servlet中能够相互传值吗

Servlet 工程 web.xml 中的 servlet 和 servlet-mapping 标签

Servlet基础

在servlet中怎样上传文件?

servlet如何配置?