如何通过JSP中的RequestDispatcher调用类

时间:2014-10-03 11:09:14

标签: java jsp servlets forward

我创建了一个类RedirectManager,它有一个方法doRedirect(request, response, url),它的作用是使用RequestDispatcher方法forward()转发到指定的url(一个String参数)。我希望点击JSP页面上的链接,(考虑现有的)RedirectManager调用doRedirect(url)对象。

如何在点击链接时调用此方法?

1 个答案:

答案 0 :(得分:0)

嗯,一种方法(我猜)是从你的链接发送一个http GET请求,就像这样

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<a href="./MyJspAction?targetUrl=page.html">click here</a>
</body>
</html>

此JSP将向servlet发送请求

package mypackage;

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;

/**
 * Servlet implementation class MyJspAction
 */
@WebServlet("/MyJspAction")
public class MyJspAction extends HttpServlet {
    private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String targetUrl = request.getParameter("targetUrl");
        new RedirectManager().doRedirect(request,response,targetUrl);
    }
}

然后servlet调用你的RedirectManager对象

package mypackage;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RedirectManager {

    public void doRedirect(HttpServletRequest request,
            HttpServletResponse response, String targetUrl) throws ServletException, IOException {

        request.getRequestDispatcher(targetUrl).forward(request, response);

    }

}

将请求发送到page.html

<html>
Hello
</html>

请注意forward and redirect are different things