转发和重定向 l 转发:forward <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <form action="ForwordServlet" method="post"> 用户名:<input type="text" name="name"> <br /> 密码:<input type="text" name="pwd" /> <input type="submit" value="提交" /> </form> </body> </html> 转发:forward(ForwordServlet.java) //导入必需的 java 库 import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ForwordServlet") //扩展 HttpServlet 类 public class ForwordServlet extends HttpServlet { // 处理 GET 方法请求的方法 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ } // 处理 POST 方法请求的方法 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 处理POST请求 req.setCharacterEncoding("UTF-8"); // String name = req.getParameter("name"); // String pwd = req.getParameter("pwd"); req.getRequestDispatcher("success.jsp").forward(req, resp); // 跳转 } } 转发:forward(success.jsp) <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> 登录成功 </body> </html> l 重定向:redirect 重定向:redirect(PageRedirect.java) import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/PageRedirect") public class PageRedirect extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); // 要重定向的新位置 String site = new String("login.jsp"); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); } } |
|