Call jsp from servlet

I call JSP, displayItems.jsp from the servlet, DataPortal.java . At first I tried to do this using RequestDispatcher , like this,

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

well ... the control went to the JSP page, however it printed all the contents of the JSP file (including tags and all) instead of displaying as a web page. Then I tried to achieve this using response.sendRedirect(url); , and this time he gives me a blank page. What am I doing wrong here? JSP is as follows:

 <!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.

+4
source share
5 answers

The problem is resolved. Here's how: I had a DispatchServlet calling DataPortal, which in turn called displayItems.jsp. The reason dispatcher.forward did not work in DataPortal because I did dispatcher.include in DispatchServlet to call DataPortal. When I changed this to the fore, everything began to work. So thank you guys for your reply.

+1
source

try it

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

What about dispatcher.include(req, res) ? This is if you want to call jsp from a servlet.

0
source

forward simply redirects the request to the next page, where sendRedirect will first return to the page where it was generated, and redirect to the next page

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

Source: https://habr.com/ru/post/1346174/


All Articles