Liferay : How to call a Servlet from a JSP Page - java

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.

Related

Java servlets: RequestDispatcher doesn't work doesn't redirect paths

I have a start.jsp, a UserInfo.java servlet and a view.jsp. The start.jsp has a form that takes a username input, send it to the servlet which, in turn, sends it to view.jsp. However, when I press the submit button on the form, no redirect happens. I suspect there's something wrong with my paths here, but can't figure out what's wrong. Here's my directory tree:
AppName
pages
projects
ProjectName
start.jsp
view.jsp
src
com
web
UserInfo.java
WEB-INF
classes
com
UserInfo.class
web.xml
UserInfo.java:
public class UserInfo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.getWriter().println("GET");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String userName = request.getParameter("username");
RequestDispatcher view= request.getRequestDispatcher("/projects/ProjectName/view.jsp");
view.forward(request, response);
}
}
web.xml:
<servlet-mapping>
<servlet-name>UserInfo</servlet-name>
<url-pattern>/User.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UserInfo</servlet-name>
<servlet-class>com.web.UserInfo</servlet-class>
</servlet>
start.jsp:
<form method="POST" action="User.do">
<div class="form-group">
<label for="usr">username:</label><br/><br/>
<input type="text" class="form-control"name="username"><br/><br/>
</div>
</form>
<button type="button" class="btn btn-primary" type="submit">
Get info
</button>
view.jsp:
<h3>Hello,
<%
out.println(request.getParameter("username"));
%>
</h3>
Here are couple of points to take note about the example posted:
(1) The Button:
(a) These define a clickable button - mostly used with JavaScript to activate a script. The following two are similar; one has a body and the other do not.
<INPUT TYPE="BUTTON" VALUE="Get Info">
<BUTTON TYPE="BUTTON">
Get Info
</BUTTON>
(b) To submit a form with its input, as in the case of this example, a submit button is to be clicked. The form is sent to the servlet (the server-side program) specified by the ACTION attribute of the FORM. The following two are similar; one has a body and the other do not.
<INPUT TYPE="SUBMIT" VALUE="Get Info">
<BUTTON TYPE="SUBMIT">
Get Info
</BUTTON>
(2) The Form:
All the inputs to be submitted (related to the form) are to be defined within that form - that includes the user name text input and the submit button. The corrected markup for start.jsp:
<form method="POST" action="User.do">
<div>
<label>username:</label><br/><br/>
<input type="text" name="username"><br/><br/>
</div>
<button type="submit">
Get info
</button>
</form>
(3) The Servlet:
UserInfo.java:
public class UserInfo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.getWriter().println("GET");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String userName = request.getParameter("username");
getServletContext().log("# User name: " + userName);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
}
}
(4) I have structured the directory tree little differently (for convenience):
servlet-1
start.jsp
view.jsp
src
com
web
UserInfo.java
WEB-INF
classes
com
web
UserInfo.class
web.xml
There is no other changes in the start.jsp, web.xml and view.jsp. The deployed web app was invoked using the URL (in this case deployed on Apache Tomcat web server): http://localhost:8080/servlet-1/start.jsp .
This shows the start.jsp in the browser. Enter the text "username" and click the "Get Info" button. The result will show in the view.jsp (I guess that's what was expected).
Finally, as already mentioned the RequestDispatcher is used to either forward to another resource or include content from another resource - its not a redirect. NOTE: The request dispatcher can be acquired either from ServletContext or from ServletRequest; note the difference between the two ways of getting the dispatcher.
Well, you don't say what does happen.
Does the forward work? i.e. does a new page appear? Because a forward is not a redirect.
A redirect sends an explicit response to the browser that then loads a new page, and is mostly obvious by the fact that the URL changes in the browser.
But a forward does not do that. Rather, it simply changes what page is output for the request currently sent. So, you don't really say in detail what is (or is not) happening here.
But taking your question at face value, you're not getting a redirect because forward does not redirect at all.
Keep the button inside form .
<form method="POST" action="User.do">
<div>
<label>username:</label><br/><br/>
<input type="text" name="username"><br/><br/>
</div>
<button type="submit">
Get info
</button>
</form>

JSP not getting request parameters

I have a JSP page which is not seeing any of the request parameter values when displayed. Originally I tried with passing the parameters from a Servlet, which did not work. Just as a test I also tried calling that JSP from a form on an html page.
What I do in Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sampleValue = sampleModel.getMyValue();
request.setAttribute("param", sampleValue);
RequestDispatcher view = request.getRequestDispatcher("samplePage.jsp");
view.forward(request, response);
}
How I call JSP from an HTML page through a form with hidden fields:
<div>
<form action="samplePage.jsp" method="post">
<input name="param" type="hidden" value="sampleValue"/>
<input type="submit" value="Update">
</form>
</div>
Finally what I have on the JSP:
<body>
<p>Some info: ${param}</p>
</body>
As I said the problem is the value of the request attribute "param" which is lets say "sampleValue", does not get rendered on the page.
I have seen lots of examples how this is done and I think my code is correct. Is there any other reason why this may not be working? I am running a maven project with Tomcat 8.5.
EDIT: What I have found out so far is that the problem is not that the Expression language is not working. The request attribute just has no value when it arrives at the JSP.
Please ensure that isELIgnored is false in your jsp page.use bellow tag at the top of your jsp.
<%# page isELIgnored="false" %>
also you can ensure this by ${2 * 4} output is print as 8 on JSP.
Your form is using method=post. Your Servlet code should be located on the doPost method instead of doGet.
For Servlet case, replace ${param} in your samplePage.jsp with
<%=request.getAttribute("param")%>
For JSP case, replace ${param} in your samplePage.jsp with
<%=request.getParameter("param")%>
First, check whether variable sampleValue is capturing the string that you are passing from JSP like below
String sampleValue = sampleModel.getMyValue();
System.out.println(sampleValue);

How to call a method when a link is clicked in Java Servlet

I'm implementing a web application written in Java working on the Apache Tomcat server (6.0.4).
What I currently want to do is calling a method when the following link is clicked.
response.getWriter().println("Next");
For JavaScript, onClick works, however it seems no to work for Java.
Do you have any tips?
===More details===
I'm implementing Java servlet for a web application.
Once a link is clicked, a user goes to the next servlet.
Before moving to the next servlet (once a link is clicked), the program should call a method which registers some input values by a user to a database.
I would not like to use JavaScript.
You will have to use a form in the following way:
(I am assuming we are starting from scratch)
A. define your servlet in your web.xml file under Web-Inf:
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>cs336.servlets.LoginServlet</servlet-class>
<servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
B. In your .jsp page, you need to somehow point to this servlet on action, you do it in the following way:
<form class="LoginHeader" method="POST" action="Login">
<span>
<input type="text" name="user_name" placeholder="User Name / Email" required>
<input type="password" name="password" placeholder="Password" required>
<br>
<span id="loginError"></span>
<input type="submit" value="Log in" class="buttonWhite" id="loginButton"> <br>
<input type="submit" id="forgotPassword" value="I forgot my password...">
</span>
<a id="createAccount" href="index.html">Register</a>
</form>
C. In your servlet, you need to handle this event with the proper method, in this case:
protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { ... }
This is as much I can tell you with the little background you gave. Pretty much, you have to do a POST to call the servlet, intercept it with the servlet method, do what you have to do, and then you could:
response.sendRedirect(...)
I hope this helps.
You would have to create a servlet or use a struts framework or something like that.
If you use jsp you might be able to call another jsp page that calls a java function.
Next
NextPage.jsp:
<%
somejavafunction();
%>

Call multiple method of Servlet from jsp page

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.

how can i use servlet in jsp page?

<body>
<form action="testServlet.java">
<TABLE border="0" align="center">
<TR height="40">
<TD width="40"><a href="Hoda/testServlet?direction=b"><img
src=<%=request.getAttribute("imgSrc")%> width="40" height="40" /></a>
</TD>
</form>
</body>
SERVLET:
#WebServlet("/testServlet")
public class testServlet extends HttpServlet {
String imgSrc = "red.png";
protected void service(HttpServletRequest reques,HttpServletResponse response) throws ServletException, IOException {
String str = request.getParameter("direction");
if (str.startsWith("b")) {
imgSrc = "black.png";
}
request.setAttribute("imgSrc", imgSrc);
}
}
In my JSP page, I created a cell whose image source I want to get from servlet. I put the link tag to ask servlet for imgSrc, but it does not work . Please show me how to change the imgSrc in JSP page using servlet. I want the JSP to merely show the result, not a dispatch to another page.
here is my code :
You'll have to use the Servlet API's RequestDispatcher to forward from the Servlet to the JSP so that the processing occurs on the same request, otherwise the attribute won't be set. You could probably also use some custom include logic, but typically you'd use the servlet as a "front" and then use the JSP to render the content. Hopefully this makes sense, you should be able to track the APIs down in the Servlet JavaDoc.
Please refer this post may be can help you.
http://ajax911.com/dynamically-display-images-java-servlet-tomcat/

Categories