关于Servlet里用sendRedirect 或 forward 来跳转到其它页面
1:新建工程:myServlet
2:新建WelcomeServlet.java:
package myServlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WelcomeServlet extends HttpServlet { @Override protected voiddoGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException { // TODOAuto-generated method stub java.io.PrintWriterout = resp.getWriter(); System.out.println("doGet"); //forward this.getServletContext().getRequestDispatcher("/welcome.html").forward(req,resp); //resp.sendRedirect //resp.sendRedirect("welcome.html"); } private static finallong serialVersionUID = 1L; }
3.修改xml
<servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/welcomeservlet</url-pattern> </servlet-mapping>
4.新建welcome.html / welcome.jsp 或者其它servlet
总结:
void sendRedirect(java.lang.String location)
Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.
resp.sendRedirect("url");就比较简单,简单地说就是服务器将这个url发给用户的浏览器,然后浏览器端自己跳转到这个url,最终url会显示在浏览器端
this.getServletContext().getRequestDispatcher("url").forward(req,resp);
void
forward(
ServletRequest request,
ServletResponse response)
Forwards a request from a servlet toanother resource (servlet, JSP file, or HTML file) on the server.
就是用于服务器端 servlet对象来跳转到其它 servlet ,JSP 或 HTML 页面的函数,
这个过程在服务器端然后,而用户的浏览器并不知道服务器端的servlet跳转了多少次、跳转到哪里,所以在用户的浏览器上并不会显示目标的url