calling a jsp from a servlet
I'm calling开发者_如何学JAVA a JSP, displayItems.jsp
from a servlet, DataPortal.java
. First I tried to do this using the RequestDispatcher
like this,
String url = "/displayItems.jsp";
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(toDo);
dispatcher.forward(req, res);
well... the control did go to the JSP page, however it printed the entire contents of the JSP file (including tags and everything) instead of displaying as a webpage. Next I tried to achieve this by using response.sendRedirect(url);
and this time it gives me an empty page. What am I doing wrong here? The JSP is like this,
<!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>
Any help is appreciated.
try this
RequestDispatcher RequetsDispatcherObj =request.getRequestDispatcher("/displayItems.jsp");
RequetsDispatcherObj.forward(request, response);
The problem is solved. This is how: I had a DispatchServlet calling the DataPortal which in turn was calling the displayItems.jsp. The reason dispatcher.forward was not working in DataPortal was because i was doing dispatcher.include in DispatchServlet to call the DataPortal. When i changed this to forward, things started working. So thank you guys, for your response.
What about dispatcher.include(req, res)
? This is if you want to call a jsp from servlet.
forward will just forward the request to next page where as sendRedirect will first come back to the page where its been generated and the redirect to next page
RequestDispatcher dispatcher = getRequestDispatcher("URL to jsp");
dispatcher.forward(request, response);
RequestDispatcher dispatcher = getRequestDispatcher(request.getContextPath()+"/"); dispatcher.forward(request, response);
There is an easier way to call a .JSP File from a Servlet.
You do not even need to create tags in web.xml.
Just type:
- Create a Servlet with a doGet method;
- Call a method sendRedirect;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.sendRedirect("index.jsp");}
index.jsp should be your .JSP file name. Please note you do not type / prior indicating .JSP file name!
精彩评论