aspose file tools*
The moose likes Servlets and the fly likes dispatching to servlets and JSPs Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "dispatching to servlets and JSPs" Watch "dispatching to servlets and JSPs" New topic
Author

dispatching to servlets and JSPs

shaz baluch
Greenhorn

Joined: Dec 19, 2010
Posts: 9
How do we call a servlet from a servlet and also a jsp from a servlet
Kapil Dev Karma
Greenhorn

Joined: Jan 06, 2011
Posts: 1
Hi Shaz, RequestDispatcher is the solution to both of your problems.
Please use the following peace of code for making such calls from within doGet() or doPost() methods or any other method, which allows you to access the HttpServletRequest & HttpServletResponse inside your Servlet class:

Code Block: (1)



Code Block: (2)


where, pagePath is the path of the component you want to refer/call, in your case it could be a "your.jsp" or url-pattern of the servlet.

I hope it would help.
parampreet sethi
Greenhorn

Joined: Aug 03, 2009
Posts: 27

There are two ways to do that.

Using RequestDispatcher as mentioned in above post.
1. This will internally forward your request to jsp/servlet
2. user will get 301 response code
3. the url of the browser will not change.
4. The request object from original browser request will be forwarded to the called jsp/servlet.

Using response.sendRedirect method. (Its part of HttpServletResponse)
1. The request will go back to browser.
2. Browser will have the new url.
3. New request object will be created and sent to the called jsp/servlet. (This means older request object values will not be retained.)

Depending upon the situation one of the above two ways can be used.


Param
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60991
    
  65

Please be sure to take the time to compose descriptive subjects for your posts. You will attract people who will can give you better and faster answers when your posts have good, descriptive subjects. For more information, please click this link ⇒ UseAMeaningfulSubjectLine.

Using a title such as "web application" isn't best suited to attracting the attention of those who can best help you.

I have changed the subject to one that better reflects the content of the post.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
shaz baluch
Greenhorn

Joined: Dec 19, 2010
Posts: 9
Thanks for your help but i m still having problem
please kindly check out.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class InsertSNServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
try
{
PrintWriter out = response.getWriter();

out.println("<head><title>Insert Session</title></head><body bgcolor=#fadab9>");
out.println("<center><h2>Session</h2></center>");
out.println("<br><br>");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbcdbc:colConn");
PreparedStatement stmt = conn.prepareStatement("insert into Session values (?,?)");

String sessionId = request.getParameter("sessionId");
String session = request.getParameter("session");


stmt.setInt(1,Integer.parseInt(sessionId));
stmt.setString(2,session);

if(!sessionId.equals("") && !session.equals(""))
{
int x = stmt.executeUpdate();

if (x==1)
{
out.println("<center>");
out.println("Record has been successfully added!");
out.println("</center>");
}
else
out.println("Error adding record");
out.println("</body>");
stmt.close();
conn.close();
}

else
out.println("fill all the fields");
RequestDispatcher dispatcher = request.getRequestDispatcher(response.encodeURL("addSession.jsp"));
dispatcher.forward(request, response);
}
catch(Exception e)
{
System.out.println(e);
PrintWriter out = response.getWriter();
out.println(e.getMessage());
}

}
}

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60991
    
  65

Another tip: Please be sure to use code tags when posting code to the forums. Unformatted or unindented code is extremely hard to read and many people that might be able to help you will just move along to posts that are easier to read. Please click this link ⇒ UseCodeTags ⇐ for more information.

Properly indented and formatted code greatly increases the probability that your question will get quicker, better answers.

Also, you wrote:
Thanks for your help but i m still having problem

Exactly what problems are you having? You posted a lot of code, but didn't tell us what parts are giving you trouble. Please read ItDoesntWorkIsUseless and TellTheDetails.
T. Huy Nguyen
Ranch Hand

Joined: Nov 02, 2010
Posts: 57
Since you don't tell us what is your problem, I make a wild guess: IllegalStateException.

If it is, this may help: http://download.oracle.com/javaee/5/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse)


My material for SCJP (2008), SCWCD (2010), SCBCD (2010). About me
shaz baluch
Greenhorn

Joined: Dec 19, 2010
Posts: 9
Oh sorry for that!
Actually the problem which i m facing is that with empty text boxes when i press the submit button in jsp( that is for saving the data in database),the servlet forwards the exception as 'for input string:""'. what I want is as by pressing the button(with empty field) i should get the message "fill all the fields and request should again moves to same jsp (addSession)
and again ask to enter data.

I hope now it is clear to all
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3825

shaz baluch wrote:... what I want is as by pressing the button(with empty field) i should get the message "fill all the fields and request should again moves to same jsp (addSession)
and again ask to enter data.

You may validate the input data (from the Request object) in a servlet and forward the request to a JSP/servlet depending on the status. You could use RequestDispatcher to forward the request.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
T. Huy Nguyen
Ranch Hand

Joined: Nov 02, 2010
Posts: 57
shaz baluch wrote:Oh sorry for that!
Actually the problem which i m facing is that with empty text boxes when i press the submit button in jsp( that is for saving the data in database),the servlet forwards the exception as 'for input string:""'. what I want is as by pressing the button(with empty field) i should get the message "fill all the fields and request should again moves to same jsp (addSession)
and again ask to enter data.

I hope now it is clear to all

Is your error due to NumberFormatException? Because that exception could happen to this code:
shaz baluch
Greenhorn

Joined: Dec 19, 2010
Posts: 9
yah that is NumberFormatException.(input string:"")
Now to solve this?
dileep keely
Ranch Hand

Joined: Jun 28, 2010
Posts: 91
You know that you have an exception occurring due to empty String /null value passed.You can probably use the javascript to check (on submit), before values are passed as said earlier.
shaz baluch
Greenhorn

Joined: Dec 19, 2010
Posts: 9
thanks
but is there any way to resolve that by servlet?
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3825

shaz baluch wrote:...but is there any way to resolve that by servlet?

You could do the same test for null or empty String ("") in the servlet too... But looking at the code you posted earlier, you seems to be writing the validation error in to System.out? Which would not seen by the user at all... Without having code tags it's hard to see any other issues in the code.
shaz baluch
Greenhorn

Joined: Dec 19, 2010
Posts: 9



please kindly check it out
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3825

I assume this is just for testing purpose, otherwise you should not write HTML inside servlets rather they should be in JSP/HTML files.
You may need to practice how to indent your code properly so that it is more readable .. What issue you face now (if any)?

And you are writing the error in to the out object which I thought you are not in the first place...
Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3051
    
  36

If you are still looking for implementing not-null validation from the servlet, the instructions for that has already pointed by Vijitha. I can't see any single statement in your code that you might have tried to get it done.


Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
T. Huy Nguyen
Ranch Hand

Joined: Nov 02, 2010
Posts: 57
I think he did include the checking, but it's weak checking and is at the wrong location.

Now, a simple fix would be to move


inside


Of course, you may have to watch out for null and blank (contain only space) sessionId, session.
shaz baluch
Greenhorn

Joined: Dec 19, 2010
Posts: 9
ok means that if i m using the catch block and displaying the exception then i would not be able to redirect to the jsp (addSession)?
Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3051
    
  36

shaz baluch wrote:ok means that if i m using the catch block and displaying the exception.....

Displaying in what way? As already pointed out System.out.println is not a way to display the exceptions thrown. You should log the exceptions and probably show a custom error page.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: dispatching to servlets and JSPs