从servlet调用jsp

时间:2011-04-01 05:49:54

标签: jsp servlets redirect forward

我从servlet displayItems.jsp调用JSP DataPortal.java。首先,我尝试使用RequestDispatcher这样做,

String url = "/displayItems.jsp";
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(toDo);
dispatcher.forward(req, res);

嗯......控件确实进入了JSP页面,但它打印了JSP文件的全部内容(包括标签和所有内容),而不是显示为网页。接下来,我尝试使用response.sendRedirect(url);实现此目的,这次它给了我一个空页面。我在这做错了什么? JSP就像这样,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="expires" content="0" />        
<meta http-equiv="Content-Style-Type" content="text/css" />
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.js" type="text/javascript"></script>
</head>
    <body>
    <div>i am in display category</div>
    </body>
</html>

感谢任何帮助。

7 个答案:

答案 0 :(得分:3)

试试这个

RequestDispatcher RequetsDispatcherObj =request.getRequestDispatcher("/displayItems.jsp");
RequetsDispatcherObj.forward(request, response);

答案 1 :(得分:1)

问题解决了。这是如此:我有一个DispatchServlet调用DataPortal,而DataPortal又调用displayItems.jsp。 dispatcher.forward在DataPortal中工作的原因是因为我在DispatchServlet中执行dispatcher.include来调用DataPortal。当我把它改为前进时,事情就开始起作用了。谢谢你们,感谢您的回复。

答案 2 :(得分:0)

dispatcher.include(req, res)怎么样?这是你想从servlet调用一个jsp。

答案 3 :(得分:0)

转发只是将请求转发到下一页,因为sendRedirect将首先返回到生成它并重定向到下一页的页面

答案 4 :(得分:0)

RequestDispatcher dispatcher = getRequestDispatcher("URL to jsp");
dispatcher.forward(request, response);

答案 5 :(得分:0)

RequestDispatcher调度程序= getRequestDispatcher(request.getContextPath()+“ /”); dispatcher.forward(请求,响应);

答案 6 :(得分:0)

有一种从Servlet调用.JSP文件的简便方法。

您甚至不需要在web.xml中创建标签。

只需输入:

  1. 使用doGet方法创建Servlet;
  2. 调用方法sendRedirect;

受保护的void doGet(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException { response.sendRedirect(“ index.jsp”); }

index.jsp应该是您的.JSP文件名。请注意,您不要键入/预先指示.JSP文件名!