Servlet之间的跳转

来源:互联网 发布:矩阵论导教导学导考 编辑:程序博客网 时间:2024/06/06 09:58

Servlet之间可以互相跳转,比如在MVC框架中,使用Servlet实现各个层的业务之后互相跳转。这里有两种跳转,一种为Forward, 一种为Redirect。两者的区别为第一种是一次请求,多次跳转;第二种则是多次请求,多次跳转,即跳转时会重新请求服务器资源。还有一种是refresh。这里有个属性可以设置时间,这样就可以实现一段时间自动跳转。对于类似股市刷新可使用这个跳转,若设置时间为0,就是第二种跳转了。

①Forward:

package com.test.forward;import java.io.IOException;import java.io.PrintWriter;import javax.annotation.Resource;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class TwoServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        //Forward跳转的实现是通过RequestDispatcher对象的forward方法来实现的,方法有两个参数,一个为HttpServletRequest,一个为HttpServletResponse。        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/index.jsp");        //然后启动跳转,如果不启动,则不会跳转        dispatcher.forward(request, response);    }    @Override    protected long getLastModified(HttpServletRequest req) {        return super.getLastModified(req);    }    @Override    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {    }}
②Redirect:直接使用HttpServletResponse的sendRedirect(String location)方法即可实现重定向。

③Refresh:使用HttpServletResponse的setHeader("refresh","500; URL=http://127.0.0.1:8080/servlet/index.html")即可,其中的地址和时间可改变。时间单位为毫秒。

0 0
原创粉丝点击