我创建了一个类RedirectManager
,它有一个方法doRedirect(request, response, url)
,它的作用是使用RequestDispatcher
方法forward()
转发到指定的url(一个String参数)。我希望点击JSP页面上的链接,(考虑现有的)RedirectManager
调用doRedirect(url)
对象。
如何在点击链接时调用此方法?
答案 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>