Call multiple method of Servlet from jsp page - java

I have a jsp page from where I am calling my servlet named 'InsertServlet'. I have done my required work in the service method in my servlet. I have also created a user define method in my servlet named doSomething(). But now I am being failed to call the method doSomething() from my jsp page. Is it possible to do it or I have to create a single servlet for every single action ?!! Can anyone please help me on this please ???!!! Here are my codes below >>>
my jsp page ###
<form action="IbatisInsertServlet" method="POST">
First Name : <input type="text" name="firstName" value="" /><br/>
Last Name : <input type="text" name="lastName" value="" /><br/>
Salary : <input type="text" name="salary" value="" /><br/>
<input type="submit" value="Enter" /><input type="reset" value="Clear" /><br/>
</form>
my servlet's service method where I have done my work ###
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
...
...
} catch (Exception ex) {
System.out.println("Exception is :: " + ex.getMessage());
} finally {
out.close();
}
}
my servlet's doSomething method which I want to call ###
public void doSomething(){
System.out.println("working");
}

If the doSomething method is going to be called from a JSP (which is really just a servlet) then I suggest that you put this code in a separate class which can be instantiated from the JSP and/or the the servlet. This would assume that the logic ofdoSomething has got nothing to do with the request
The idea of calling a servlet is that you are interfacing through HTTP, so if in some cases (as part of the GET/POST) you want to call doSomething then consider adding a parameter informing the servlet to do this.
E.g
myWebApp/myServlet?action=doSomething

First you have to understand how Servlet Container works!
The whole thing stands on a idea, named "Don't call us, we'll call you" also known as "Inversion of Control".
So when we write a servlet, we simply provides the methods which may be called by the container when needed! As a result the method signatures are predefined for a servlet and its not in your hand to add any method if you want.
So the answer is no, you can not invoke your doSomething() of Servlet from jsp, in a straight way!

Try this example:
html
<form action="IbatisInsertServlet" method="POST">
...
<input type="hidden" value="save" name="cmd"/>
<input type="submit" value="Enter"/>
...
</form>
<form action="IbatisInsertServlet" method="POST">
...
<input type="hidden" value="edit" name="cmd"/>
<input type="submit" value="Edit"/>
...
</form>
servlet
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String cmd = request.getParameter();//<--
if("save".equals(cmd)) {
save();
}
else if("edit".equals(cmd)) {
edit();
}
} catch (Exception ex) {
System.out.println("Exception is :: " + ex.getMessage());
} finally {
out.close();
}
}
private void save() {
...
}
private void edit() {
...
}

If you can extend the JSP page from servlet (subclassing), there may be way. You can post the data to the same jsp page or servlet (based on your needs). You can call the method of the parent class, here it would be the servlet you are extending from.
Your JSP code
<%-- top of the page. extend the servlet --%>
<%# page extends="your.package.IbatisInsertServlet" %>
<form action="IbatisInsertServlet" method="POST">
First Name : <input type="text" name="firstName" value="" /><br/>
Last Name : <input type="text" name="lastName" value="" /><br/>
Salary : <input type="text" name="salary" value="" /><br/>
<input type="submit" value="Enter" /><input type="reset" value="Clear" /><br/>
</form>
<%-- to call the function --%>
<% doSomething() %>
Note that you can leave the action empty if you want to call the same JSP or redirect it to the server. Also note that the JSP servlet and the IbatisInsertServlet will be two separate instances. Make sure you call the super.service(...) as needed.
This should work for you

This is just a complement to ScaryWombat answer.
If you call your method doSomething, it should not be part of a servlet but of another class. This way, you separate the concerns :
servlets (including JSP) manage the interactions with forms, requests, responses, session
other classes do the real job
If you full application if less than 100 lines of code, it not much important, but if it grows, you get smaller classes with less dependances which are easier to write and test.
This domain classes can be instantiated by a servlet (or a JSP) if they do not last longer than a request. If not you should instantiate them in a ServletContextListener, put them in the ServletContext and use them from any servlet of JSP you want.

Related

Spring-MVC : two jsps into one controller with one requestMapping

Can I use one request mapping for two jsps?
I am currently calling one request mapping from one controller but one of the jsps doesn't seem to be caught by the controller.
Both jsps have the same form action and same form method:
first.jsp look like this:
<form:form method="POST" action="/ShowroomNav/requestQuote" id="requestQuoteForm">
<input type="hidden" value=${product.productCode } name="productCodes" />
<input type="hidden" id="requestQuoteEmailAddress" name="requestQuoteEmailAddress" />
</form:form>
the second.jsp look like this:
<form:form method="POST" action="/ShowroomNav/requestQuote" id="requestQuoteForm">
<input type="hidden" id="requestQuoteEmailAddress" name="requestEmailAddress" />
<c:forEach var="product" items="${products}">
<input type="hidden" value=${product.productCode } name="productCodes" />
<div class="box">
<img
src="public/productImages/${product.productCode}/${product.productCode}A.jpg"
style="max-width: 100%"
onclick="productProfile('${product.productCode}')" /><br /> <label
class="name">${product.productName}</label>
</div>
</c:forEach>
</form:form>
both of them submits the function by a javascript call of :
$("#requestQuoteSubmitButton").one("click",function(){
$("#requestQuoteEmailAddress").val($("#requestQuoteEmailAddressModal").val());
alert($("#requestQuoteEmailAddress").val());
$("#requestQuoteForm").submit();
});
this is how the controller.java looks like:
#RequestMapping(value = "/requestQuote", method = RequestMethod.POST) // or GET
public String requestQuote(#RequestParam("requestQuoteEmailAddress") String requestQuoteEmailAddress, #RequestParam("productCodes") String[] productCodes) {
System.out.println(">>>> requesting quotes >>>>");
for(int i=0; i<productCodes.length; i++) {
System.out.println(" Product Codes : " + productCodes[i]);
}
System.out.println("requestQuoteEmailAddress : " + requestQuoteEmailAddress );
System.out.println("<<<<< requesting quotes <<<<");
return "productSearch";
}
So I don't know why the second.jsp cannot be caught by the controller as it always shows this error when I try to submit it.
HTTP Status 400 - The request sent by the client was syntactically incorrect.
Can somebody help please?
The problem is (a typo?) in your 2nd line of your second.jsp snippet:
<input type="hidden" id="requestQuoteEmailAddress" name="requestEmailAddress" />
The id attribute is mainly for client side reference, and doesn't matter when form is submitted (see HTML input - name vs. id). What's important is the name attribute. So when the POST request is sent to server, the request body looks like:
requestEmailAddress=...&productCodes=...&productCodes=...
Since you annotated the handler method parameter as #RequestParam("requestQuoteEmailAddress"), Spring MVC looks for requestQuoteEmailAddress instead of requestEmailAddress, thus the error (#RequestParam's required is true by default).

Hidden input in JSP produces null when passing it to the servlet

In my JSP I do the following :
<!-- Bank manager's permissions -->
<!--more stuff goes here -->
<fieldset>
<legend>To open a new account</legend>
<form action="blablabla">
<input type="hidden" name="hdField" value="myValue" /> // note I pass a "myValue" as string
Press here to continue
</form>
</fieldset>
And in my Servlet I grab the hidden input :
#WebServlet("/employeeTransaction1")
public class Employee1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String getHiddenValue=request.getParameter("hdField");
System.out.println("Hidden field Value :"+getHiddenValue);
// forwards to the page employeeOpenNewAccount.jsp
request.getRequestDispatcher("/WEB-INF/results/employeeOpenNewAccount.jsp").forward(request, response);
}
}
And System.out.println produces : null at the Console
Why do I get a null of not the actual value is I pass ?
Regards
EDIT:
After changing to :
<fieldset>
<legend>To open a new account</legend>
<form action="/employeeTransaction1" method="GET">
<input type="hidden" name="hdField" value="myValue"/>
Press here to continue
</form>
</fieldset>
A null is still presented at the console .
What you are trying to do is to send a form to the server. But, in fact, you don't do that. You just issue a GET request (when the user clicks your link: Press here to continue)
If you want to send the form make sure you set the attributes of the form tag properly and add a submit button to the form:
<form action="/employeeTransaction1" method="GET">
...
<input type="submit" value="Submit" />
...
</form>
Depending on your preferred way of sending the form, you can change the method="GET" paramater to method="POST" and make sure that in the servlet you handle the form in the doPost() method
Alternatively, if your purpose is not to send the from to the server but just to pass the value of the hidden input, you should add its value as a prameter encoded in the GET request. Something like:
/employeeTransaction1?hdField=myValue
To achieve this, you need some client processing, i.e. when the user clicks the link, the hidden input should be added to the get and then the request should be issued.
Using an href tag does not submit your form, i.e. it does not pass the parameters defined in the form to the request. You should use input type="submit" or button tags instead. Also make sure the form action matches your #WebServlet definition.
<fieldset>
<legend>To open a new account</legend>
<form action="/employeeTransaction1">
<input type="hidden" name="hdField" value="myValue" /> // note I pass a "myValue" as string
<input type="submit" value="Submit" />
</form>
</fieldset>

form values not submitted to the servlet

I am trying to submit the text field value and print it using the servlet. The index.jsp is my main page and I am using jsp:include to include the form which reside in another page which is login.html.
here is the code i have for login.html
<form id="f1" action="ControllerServlet" method="GET">
<p>username
<input class ="text-input" type="text" id="txtusername" />
</p>
<p>
<input type="submit" value="submit" />
</p>
the index.jsp
<div id="col3_content" class="clearfix">
<h1>H1 Heading</h1>
<jsp:include page="login.html"></jsp:include>
</div>
the controller servlet
String usrname = request.getParameter("txtusername").toString();
out.print(usrname);
The problem is this is throwing a null pointer exception. what am I doing wrong here ? any help appreciated. thanks
Please use name not id
<input class ="text-input" type="text" name="txtusername" />
The id is not used to identify the name of the input parameter. The right attribute for the parameter is name, currently you are using an input without a name. So use
<input class ="text-input" type="text" name="txtusername" id="txtusername" />
You need to define name attribute of input tag to get it in Servlet by name.
<input class ="text-input" type="text" id="txtusername" name="txtusername" />
Also make sure you are writing code in doGet or service method of servlet as you have GET as action in form tag.
Code for Login.html
<form action="ControllerServlet" method="GET">
<p>username :
<input type ="text" name="txtusername" /></p>
<p><input type="submit" value="submit" /> </p>
</form>
ControllerServlet.java
public void service(ServletRequest request, ServletResponse response)
{
String username = request.getParameter("txtusername");
PrintWriter out = response.getWriter();
out.println("User Name " + username)
I faced a similar situation, when I checked front end, the form seems to have all the value populated correctly. However, after form.submit, from server side using request.getParameter("the parameter") does not return the value populated. After tuning on the network traffic tab in browser, I see the parameter was there, but there was a typo.
Hopefully could save you some time if same thing happens to you.

Liferay : How to call a Servlet from a JSP Page

This is my first Portlet. I am not getting values inside my servlet. Please, see the program. Inside my custom portlet Java class doView() method, I show a JSP page
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
include(viewJSP, renderRequest, renderResponse);
}
Inside the view.jsp page, I refer to a servlet to receive the values:
<form action="formServlet" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="login"><br>
Password: <input type="password" name="password"><br>
<input type=submit value="Login">
</form>
Inside web.xml file:
<servlet>
<servlet-name>formServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>formServlet</servlet-name>
<url-pattern>formServlet</url-pattern>
</servlet-mapping>
Inside my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = (String)request.getParameter("login");
System.out.println("The Name is "+name);
}
But I don't know why the servlet is not being called.
NOTE: This is an answer to a somewhat complicated question. If you are trying to learn the basics of portlet creation, I posted a better answer in another question.
You are submitting a form using the POST method but your servlet just implements doGet(), which serves the GET method. You should either submit your form using GET or implement the doPost() method (which would be preferable in other situations).
Also, it is necessary to precede the <url-pattern> content by a slash if it is an absolute pattern. That is, it should be
<url-pattern>/formServlet</url-pattern>
instead of
<url-pattern>formServlet</url-pattern>
That said, forget servlets now!
You are doing it in one of the worst ways. It is really a bad idea to write a portlet which calls a servlet. After a long time working with Liferay I can imagine situations where it would be more or less reasonable, but it is not here and will not be most of the times.
So, what should you do? You should submit your form to an action URL. To do it, first include the portlet taglib in your JSP:
<%# taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
Now, replace the action of your form by the <portlet:actionURL />. This tag will be replaced by a special URL generated by the portal. Also, precede each input name with the tag <portlet:namespace />; your <input type="text" name="login"> should become <input type="text" name="<portlet:namespace />login"> then. This tag will be replaced by a string which is associated with only your portlet; since you can have a lot of portlets in a page, each input should specify from what portlet it comes from. This is the final result:
<form action="<portlet:actionURL />" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="<portlet:namespace />login"><br>
Password: <input type="password" name="<portlet:namespace />password"><br>
<input type=submit value="Login">
</form>
Now you are going to submit your data correctly - but how to get the submitted data? It certainly is not necessary to use a servlet! Instead, add to your custom portlet class a method called processAction(). This method should return void and receive two parameters, of the time javax.portlet.ActionRequest and javax.portlet.ActionResponse. This is an example of an empty processAction():
public void processAction(ActionRequest request, ActionResponse response) {
// Nothing to be done for now.
}
When a request to an action URL (as the one generated by <portlet:actionURL />) is sent to the server, it is firstly processed by the processAction() method and then by doView(). Therefore, the code you would write in your servlet should be put in your processAction(). The result should be then:
public void processAction(ActionRequest request, ActionResponse response) {
String name = (String)request.getParameter("login");
System.out.println("The Name is "+name);
}
Try it and you will see that it will work well.
yyy - Here's the answer to your comment:
In your JSP page you'll need to add the following for each of the actions you want that portlet to perform:
<portlet:actionURL var="addUserURL">
<portlet:param name="<%= ActionRequest.ACTION_NAME %>" value="addUser" />
</portlet:actionURL>
<form method="post" action="<%= addUserURL %>">
Then in your com.test.Greeting portlet you'd have for each of these:
public void addUser (ActionRequest actionRequest, ActionResponse actionResponse) {}
Does this answer your question?
Also it's usually best to start a new question rather than adding a comment.

servlets connectivity & running on tomcat

How can I use this path: "file:///E:/apache-tomcat-7.0.10/webapps/examples/WEB-INF/match.html" ? Is this correct?
This is my html file:
<html>
<form method=post action="../classes/match1">
<body bgcolor="powderblue">
<center><h1>MATCH</h1>
<hr/>
MATCH NO <input type="text" name="op1"/><br/><pre>
DATE <input type="text" name="op2"/><br/><pre>
CITY <input type="text" name="op3"/><br/><pre>
TEAM1 <input type="text" name="op4"/><br/><pre>
TEAM2 <input type="text" name="op5"/><br/><pre>
STADIUM <input type="text" name="op6"/><br/><pre>
WINNER <input type="text" name="op7"/><br/><pre>
MAN OF THE MATCH <input type="text" name="op8"/><br/><pre>
<input type="submit" value="submit"/>&nbsp
<input type="reset" value="reset"/>
</body>
</html>
My servlet code:
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.sql.Date.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class match1 extends HttpServlet {
Connection con;
PreparedStatement pst;
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException {
try {
PrintWriter out=res.getWriter();
con=null;
pst=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:odbc:gan","scott","tiger");
int count=0;
String op1=req.getParameter("op1");
String op2=req.getParameter("op2");
String op3=req.getParameter("op3");
String op4=req.getParameter("op4");
String op5=req.getParameter("op5");
String op6=req.getParameter("op6");
String op7=req.getParameter("op7");
String op8=req.getParameter("op8");
pst=con.prepareStatement("insert into matchdetails values(?,?,?,?,?,?,?,?)");
pst.setString(1,op1);
pst.setString(2,op2);
pst.setString(3,op3);
pst.setString(4,op4);
pst.setString(5,op5);
pst.setString(6,op6);
pst.setString(7,op7);
pst.setString(8,op8);
out.println("<html><center><body>matched</body></center></html>");
int count1=pst.executeUpdate();
if(count1==0) {
out.println("<html><center><body>ENTER ALL FIELD VALUES</body></center></html>");
} else {
out.println("<html><center><body>INSERTION SUCCESFUL</body></center></html>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (con!=null) con.close();
} catch(Exception e) {
System.out.println("error");
}
}
}
}
How can I use this path: "file:///E:/apache-tomcat-7.0.10/webapps/examples/WEB-INF/match.html" ? Is this correct?
You mean, how to access it by a webbrowser? No, that path is not correct. Tomcat listens on HTTP requests only. When started properly, it by default listens on http://localhost:8080. All webapps get their own context name which defaults to the webapp folder name. So your webapp is accessible by http://localhost:8080/examples. However, files in /WEB-INF folder are not directly accessible. You need to move the match.html one level up, in the /examples folder. Then you'll be able to access it by http://localhost:8080/examples/match.html.
Unrelated to the concrete problem, declaring connection and statement as instance variable of the servlet is a poor practice. This is not threadsafe. You need to declare them inside the method block, right before the try statement. Your HTML has also some syntax errors. Use http://validator.w3.org to learn about them. Finally, emitting raw HTML in servlets is also a poor practice, there you normally use JSPs for. But maybe you're currently just learning. Just to let you know :) Already using preparedstatements and closing the connection in finally is very good for a starter.
As to learning JSP/Servlets, I'd suggest to read our info/wiki pages as well.
JSP info page
Servlets info page
First, your html need to be a little
cleaner (see below).
Second, if you
want match.html, don't use match1
in the form action.
Third, put the
match.html file under the war
folder, not web-inf.
Fourth, you
will need to set up the web.xml
configuration file.
I did not even look yet at the servlet class, but I would suggest first to test some System.out.println() output to make sure it is even executed.
<html>
<body bgcolor="powderblue">
<center>
<h1>MATCH</h1>
<form method="post" action="/match.html">
<pre>MATCH NO <input type="text" name="op1"/></pre>
<pre>DATE <input type="text" name="op2"/></pre>
<pre>CITY <input type="text" name="op3"/></pre>
<pre>TEAM1 <input type="text" name="op4"/></pre>
<pre>TEAM2 <input type="text" name="op5"/></pre>
<pre>STADIUM <input type="text" name="op6"/></pre>
<pre>WINNER <input type="text" name="op7"/></pre>
<pre>MAN OF THE MATCH <input type="text" name="op8"/></pre>
<pre><input type="submit" value="submit"/></pre>
<input type="reset" value="reset"/>
</form>
</center>
</body>
</html>

Categories