Hi, I just wanna know, How to call a JSP page from a servlet and what are the various methods. Please do provide the proper syntax.I wud be thankful if anyone could explain it to me.I am a beginner to the servlets. TnR
There are different methods to call jsp from servlet or from anyother JSP. You can have a form in your servlet with will post data to the JSP. like in HTML <form method="POST" action="/somejsp.jsp"> //form elements </form> so when you submit the button it will post the data to that JSP. You can also have a link in your page like <a href="/somejsp.jsp">Click Here</a>. Now clicking on this link will take you to that specified JSP page. You can redirect to any jsp from your servlet using following code. response.sendRedirect("/somejsp.jsp"); You can also forward your request to anyother JSP using following code. RequestDispatcher rd = request.getRequestDispatcher("/somejsp.jsp"); rd.forward(request,response); It all depends on your requirement that how do you want to call the jsp.
posted 16 years ago
Hi Ali, Thanks a million for ur prompt reply and helping me on the same. BUt still I have some doubts poping in my mind. When u use sendRedirect, it executes on the browser and requestDispatcher.forward() executes on server. right?? Now when u do these whether request and response both gets passed on toi the called jsp??? Or when does request passed and when does the response. Thanks in advance
posted 16 years ago
Basically concept behind these two is that when you use response.sendRedirect() then a new object of request is created by the server. and when you use rd.forward() method then the existing request object will be passed to the jsp or servlet you are forwarding to. We use response.sendRedirect() method mostly in controller servlets which controls the flow. Like if you are going to login a user in your site then the request will be post to a controller servlet. that servlet will check whether the username and password exists in database. If yes then it will redirect to the main page otherwise it will redirect to the Error page. In this scenario we need response.sendRedirect() method because we are not concerned with the request object. And if you want to add some more elements in request object using request.setAttribute() for some case depending on any request field. i.e. if this then set the element in request and if that set different element. Then you forward that to another jsp. In this case you will use rd.forward method. I hope that you understood the different between these two. In case of any confusion you are welcome to ask.
I knew that guy would be trouble! Thanks tiny ad!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop