Can I call a servlet from JSP file without using a HTML form?
For example, to show results from database in a HTML table during page load.
You can use the doGet() method of the servlet to preprocess a request and forward the request to the JSP. Then just point the servlet URL instead of JSP URL in links and browser address bar.
E.g.
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
#EJB
private ProductService productService;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productService.list();
request.setAttribute("products", products);
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
Note that the JSP file is placed inside /WEB-INF folder to prevent users from accessing it directly without calling the servlet.
Also note that #WebServlet is only available since Servlet 3.0 (Tomcat 7, etc), see also #WebServlet annotation with Tomcat 7. If you can't upgrade, or when you for some reason need to use a web.xml which is not compatible with Servlet 3.0, then you'd need to manually register the servlet the old fashioned way in web.xml as below instead of using the annotation:
<servlet>
<servlet-name>productsServlet</servlet-name>
<servlet-class>com.example.ProductsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>productsServlet</servlet-name>
<url-pattern>/products</url-pattern>
</servlet-mapping>
Once having properly registered the servlet by annotation or XML, now you can open it by http://localhost:8080/context/products where /context is the webapp's deployed context path and /products is the servlet's URL pattern. If you happen to have any HTML <form> inside it, then just let it POST to the current URL like so <form method="post"> and add a doPost() to the very same servlet to perform the postprocessing job. Continue the below links for more concrete examples on that.
See also
Our Servlets wiki page
doGet and doPost in Servlets
How to avoid Java code in JSP
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
You will need to use RequestDispatcher's Methods forward/include depending on your requirement to achieve same.
In JSP you need to use following tags:
jsp:include :
The element allows you
to include either a static or dynamic
file in a JSP file. The results of
including static and dynamic files are
quite different. If the file is
static, its content is included in the
calling JSP file. If the file is
dynamic, it acts on a request and
sends back a result that is included
in the JSP page. When the include
action is finished, the JSP container
continues processing the remainder of
the JSP file.
e.g.
<jsp:include page="/HandlerServlet" flush="true">
jsp:forward :
The element forwards the
request object containing the client
request information from one JSP file
to another file. The target file can
be an HTML file, another JSP file, or
a servlet, as long as it is in the
same application context as the
forwarding JSP file. The lines in the
source JSP file after the
element are not
processed.
e.g.
<jsp:forward page="/servlet/ServletCallingJsp" />
Check Advanced JSP Sample : JSP-Servlet Communication:
http://www.oracle.com/technology/sample_code/tech/java/jsps/ojsp/jspservlet.html
Sure you can, simply include it in your action in the form. But you have to write the correct doPost or doGet to handle the request!
If you want to call a particular servlet method than you also use Expression Language. For example, you can do something like:
Servlet
ForexTest forexObject = new ForexTest();
request.setAttribute("forex", forexObject);
JSP
<body bgcolor="#D2E9FF">
Current date : ${forex.rate}
</body>
Related
For context I have a jsp called "withdraw.jsp" that calls a servlet that processes a withdrawal. In this servlet I would like to pass a string message if the transaction is successful or not and I would like to send this message to the same jsp that called the servlet (which is still "withdraw.jsp". Here is what I did so far
//In the servlet
RequestDispatcher view = request.getRequestDispatcher("registeredUser/withdraw.jsp");
String error = (String)ex.getMessage();
request.setAttribute("errorMessage", error);
view.include(request,response); // i also tried forward here
//In the jsp
<% if(request.getParameter("errorMessage") != null){ %>
<p> <%=(String)request.getParameter("errorMessage")%> </p>
<% } %>
If I run this code, the jsp wouldn't retrieve the errorMessage since it is null despite being set as an attribute by the servlet. Any help?
You are confusing attributes with parameters.
The message is always null in your JSP because you have set an attribute in you servlet, but in your JSP you are looking for a parameter. They are different things.
Things to do:
.forward(...) to your JSP using the RequestDispatcher;
make sure you retrieve an attribute in your JSP;
do not use scriptlets. Depending on your JSP version you can use EL expressions or JSTL.
I am new to servlets and i have developed a html page which has a submit button that triggers
my servlet.Everything is working fine .But now i want to use GET method as my html page is not posting anything.Hence i made the following changes:
1)In my page.html file, i replaced method="POST" with method="GET".
2)I changed doPost with doGet in my servlet.
But i'm getting error message that "GET not allowed here".Why is it so?
Here are the original files which work correctly(prior to making changes):
My page.html page:
<html>
<head>
<title>A simple revision of servlets</title>
</head>
<body>
<form method="POST" action="Idiot">
<input type="SUBMIT">
</form>
</body>
</html>
My Deployment Descriptor:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>TangoCharlie</servlet-name>
<servlet-class>Revise</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TangoCharlie</servlet-name>
<url-pattern>/Idiot</url-pattern>
</servlet-mapping>
</web-app>
And finally my servlet file named Revise.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Revise extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html><body><h3>Hello India</h3></body></html>");
out.println("Hello");
}
}
I don't want to add any input fields.My aim is just to run the servlet without a single button on html page that too called using "POST" method.
Just do the job in doGet() method (don't forget to properly rebuild/redeploy/restart the project after editing servlet code, otherwise you will still face a "HTTP 405: method not allowed" error) and invoke the URL of the servlet directly instead of the URL of the JSP in the browser's address bar.
So, the URL in browser address bar should be
http://example.com/contextname/Idiot
instead of
http://example.com/contextname/page.html
Unrelated to the concrete problem, emitting HTML in a servlet is bad design. It should be done by a JSP. You can use RequestDispatcher#forward() to forward the request to a JSP after finishing the doGet() business logic. Further, packageless classes are also a bad design. You should always put publicly reuseable Java classes in a package. Packageless servlets will only work on certain combinations of Tomcat + JVM versions.
See also:
Our servlets wiki page - contains concrete (and properly designed) Hello World examples
This question already has answers here:
Calling a servlet from JSP file on page load
(4 answers)
Closed 6 years ago.
I have below servlet. I would like to call the servlet on jsp page load. How can I do that?
servlet: SomeServlet.java
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
How can I write corresponding jsp to invoke the servlet on jsp page load. Also I need to get the result from servlet and display in the same jsp. Can I send result back to jsp?
Thanks!
You should do it the other way round. Call the servlet by its URL and let it present the JSP. That's also the normal MVC approach (servlet is the controller and JSP is the view).
First put the JSP file in /WEB-INF folder so that the enduser can never "accidently" open it by directly entering its URL in browser address bar without invoking the servlet. Then change the servlet's doGet() accordingly that it forwards the request to the JSP.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
Open it by
http://localhost:8080/contextname/HelloServlet
Note that you can of course change the URL pattern in servlet mapping to something like /hello so that you can use a more representative URL:
http://localhost:8080/contextname/hello
See also:
Our Servlets tag info page
<jsp:include page="/HelloWorld"/>
Call a servlet instead get result in request attribute and forward the request to jsp
or make an ajax call to servlet on load and render the response using javascript
In JSP paage you can forward the request to the Servlet
response.sendRedirect(request.getContextPath()+"/SomeServlet");
I have a java class which performs some operations on files. Since the java code is huge I don't want to write this code in jsp. I want to call the methods in jsp whenever required.
Please tell me the path where I need to keep this file. Also some example code how to use it would be helpful.
In the servlet (which runs before the JSP):
Person p = new Person(); // instantiate business object
p.init(...); // init it or something
request.setAttribute("person", p); // make it available to the template as 'person'
In the template you can use this:
your age is: ${person.age} <%-- calls person.getAge() --%>
I think the question is, how do you make Java code available to a JSP? You would make it available like any other Java code, which means it needs to be compiled into a .class file and put on the classpath.
In web applications, this means the class file must exist under WEB-INF/classes in the application's .war file or directory, in the usual directory structure matching its package. So, compile and deploy this code along with all of your other application Java code, and it should be in the right place.
Note you will need to import your class in the JSP, or use the fully-qualified class name, but otherwise you can write whatever Java code you like using the <% %> syntax.
You could also declare a method in some other utility JSP, using <%! %> syntax (note the !), import the JSP, and then call the method declared in such a block. This is bad style though.
Depending on the kind of action you'd like to call, there you normally use taglibs, EL functions or servlets for. Java code really, really doesn't belong in JSP files, but in Java classes.
If you want to preprocess a request, use the Servlet doGet() method. E.g.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request here.
doYourThingHere();
// And forward to JSP to display data.
request.getRequestDispatcher("page.jsp").forward(request, response);
}
If you want to postprocess a request after some form submit, use the Servlet doPost() method instead.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request here.
doYourThingHere();
// And forward to JSP to display results.
request.getRequestDispatcher("page.jsp").forward(request, response);
}
If you want to control the page flow and/or HTML output, use a taglib like JSTL core taglib or create custom tags.
If you want to execute static/helper functions, use EL functions like JSTL fn taglib or create custom functions.
Although I'll not advice you to do any java calls in JSP, you can do this inside your JSP:
<%
//Your java code here (like you do in normal java class file.
%>
<!-- HTML/JSP tags here -->
In case you're wondering, the <% ... %> section is called scriptlet :-)
Actually, jsp is not the right place to 'performs some operations on files'. Did you hear about MVC pattern?
If you still interested in calling java method from jsp you can do it, for example:
1. <% MyUtils.performOperation("delete") %> (scriptlet)
2. <my-utils:perform operation="delete"/> (custom tag)
Anyway I recomend you to google about scriptlets, jsp custom tags and MVC pattern.
Best Regards, Gedevan
I have a doubt regarding the use of servlets.
In the application I'm building I use Html pages to ask the user for info.
Imagine a Html page that lets the user request to see on the screen the content of a data base. What I'm doing is:
1.- From the Html page I'm calling a servlet that will open a connection with the database.
2.- The servlet builds the web page that the user will see.
My question is: is there any other way of doing this? Do I have to build the web page in the servlet or is there any way of sending the information contained in the database to an .html file which will build the web page (in my case I need to show on the screen a table containing all the information) ?
Thanks
Servlets are meant to control, preprocess and/or postprocess requests, not to present the data. There the JSP is for as being a view technology providing a template to write HTML/CSS/JS in. You can control the page flow with help of taglibs like JSTL and access any scoped attributes using EL.
First create a SearchServlet and map it on an url-pattern of /search and implement doGet() and doPost() as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request here and finally send request to JSP for display.
request.getRequestDispatcher("/WEB-INF/search.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request here. Get results from your DAO and store in request scope.
String search = request.getParameter("search");
List<Result> results = searchDAO.find(search);
request.setAttribute("results", results);
request.getRequestDispatcher("/WEB-INF/search.jsp").forward(request, response);
}
Here's how the JSP /WEB-INF/search.jsp would look like, it makes use of JSTL (just drop JAR in /WEB-INF/lib) to control the page flow.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<form action="search" method="post">
<input type="text" name="search">
<input type="submit" value="search">
</form>
<c:if test="${not empty results}">
<p>There are ${fn:length(results)} results.</p>
<table>
<c:forEach items="${results}" var="result">
<tr>
<td>${result.id}</td>
<td>${result.name}</td>
<td>${result.value}</td>
</tr>
</c:forEach>
</table>
</c:if>
Note that JSP is placed in /WEB-INF to prevent users from direct access by URL. They are forced to use the servlet for that by http://example.com/contextname/search.
To learn more about JSP/Servlets, I can recommend Marty Hall's Coreservlets.com tutorials. To learn more about the logic behind searchDAO, I can recommend this basic DAO tutorial.
To go a step further, you could always consider to make use of a MVC framework which is built on top of the Servlet API, such as Sun JSF, Apache Struts, Spring MVC, etcetera so that you basically end up with only Javabeans and JSP/XHTML files. The average MVC frameworks will take care about gathering request parameters, valitate/convert them, update Javabeans with those values, invoke some Javabean action method to process them, etcetera. This makes the servlet "superfluous" (which is however still used as being the core processor of the framework).
In addition to Servlets, Java has JSP pages, which are a mix of HTML and custom tags (including the Java Standard Tag Library or JSTL) which are eventually compiled into Servlets.
There are other technologies for making web applications, including things like Java Server Faces (JSF), Apache Struts, Spring, etc... Spring in particular is very widely used in modern web application development.
Ultimately, though, it's like Brian Agnew said... you have to communicate back and forth from the browser to the server. These are just various technologies to facilitate that.
Ultimately the browser has to send a request to the server for the database info. You can do this in many ways:
build the whole page in the servlet (perhaps the simplest)
build a page in the servlet containing (say) XML data, and the browser renders it into HTML (via XSL/Javascript etc.). That may be suitable if you want the browser to control the formatting and presentation.
build a page containing AJAX requests to go back to the server and get the data. That may be more suitable for data that updates regularly, or more interactive applications.
There are numerous ways to skin this cat. I suspect you're doing the simplest one, which is fine. I would tend towards this without explicit requirements that mean I need to do something else. Further requirements that complicate matters may include paging the data if there's too much to fit on the screen. All the solutions above can be made to incorporate this in some fashion.
My java is rusty but...
in your Data Access layer, iterate over the result set and build a custom object and insert it into an ArrayList;
class DataAccess {
public ArrayList foo() {
// Connect to DB
// Execute Query
// Populate resultSet
ArrayList result = new ArrayList();
while (resultSet.hasNext()) {
CustomObject o = new CustomObject();
o.setProperty1(resultSet.getInt(1));
o.setProperty2(resultSet.getString(2));
// and so on
result.add(o);
}
return result;
}
}
Call this method from your Servlet. After you have populated the ArrayList, put it on the Request object and forward on to your .jsp page
ArrayList results = DataAccessClass.foo();
Request.setAttribute("Results", results);
In your jsp, build your markup using scriptlets
<% foreach (CustomObject o in Request.getAttribute("Results"))
{%>
<td><%= o.getProperty1()</td>
<td><%= o.getProperty2()</td>
<% } %>
Good luck