Calling a Servlet from Jsp File on Page Load

How to call servlet on jsp page load


Solution 1

Steps to follow:

  • use jsp:include to call the Servlet from the JSP that will include the response of the Servlet in the JSP at runtime
  • set the attribute in the request in Servlet and then simply read it in JSP

Sample code:

JSP:

<body>
<jsp:include page="/latest_products.jsp" />
<c:out value="${message }"></c:out>
</body>

Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("message", "hello");
}

EDIT

but i don't want to display the name of servlet in url.

Simply define a different and meaningful url-pattern for the Servlet in the web.xml such as as shown below that look like a JSP page but internally it's a Servlet.

web.xml:

<servlet>
<servlet-name>LatestProductsServlet</servlet-name>
<servlet-class>com.x.y.LatestProductsServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LatestProductsServlet</servlet-name>
<url-pattern>/latest_products.jsp</url-pattern>
</servlet-mapping>

Solution 2

Steps to follow:

  • first call to the the Servlet
  • process the latest products
  • set the list in the request attribute
  • forward the request to the JSP where it can be accessed easily in JSP using JSTL

Sample code:

Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("message", "hello");
RequestDispatcher view=request.getRequestDispatcher("index.jsp");
view.forward(request,response);
}

index.jsp:

<body>      
<c:out value="${message }"></c:out>
</body>

hit the URL: scheme://domain:port/latest_products.jsp that will call the Servlet's doGet() method.

Calling a servlet from JSP file on 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"

Submitting variable from jsp to servlet on page load

that is where you need the ajax.

change your submit button into a html button and the onclick function, do a ajax call to your servlet and do the stuff there, and pass the output to the jsp through the print stream.

<input type="button" onClick="loadInbox();" value="inbox"/>

and your loadInbox() function will do the ajax:

function loadInbox(){
$.ajax({
type: "POST",
data: { "userId": userId },
url: 'YourServletName',
dataType: 'json',
"success": function (data) {
if (data != null) {
var vdata = JSON.parse(data);
console.log("output from server" + vdata);
},
"error": function (data) {
console.log("error "+ data);
}
});

}

and in your servlet (YourServletName) class, you do your logic stuff and pass the output to print stream:

void doPost(...... request, ... response){
PrintWriter out = response.getWriter();

// get the userId from request:
String userId = request.getParameter("userId");

// do your logic stuff :
// get the output and print it to output stream:
String yourOutput = "{ 'output': 'This is an example output'}";

out.print(yourOutput);
out.flush();
out.close();
}

That is all you have to do. and the out.println(yourOutput); will pass the response of your logic/result in to the "success" method of the ajax call if it is ok. check your web console in developer mode to verify the response set from the servlet is what you get as json string/object.

remember to add jquery library to your javascript libraries!

hope this will guide you...Happy Ajax !

Calling servlet from JSP

You need to open the page by requesting the servlet URL instead of the JSP URL. This will call the doGet() method.

Placing JSP in /WEB-INF effectively prevents the enduser from directly opening it without involvement of the doGet() method of the servlet. Files in /WEB-INF are namely not public accessible. So if the preprocessing of the servlet is mandatory, then you need to do so. Put the JSP in /WEB-INF folder and change the requestdispatcher to point to it.

request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);

But you need to change all existing links to point to the servlet URL instead of the JSP URL.

See also:

  • Servlets info page

How to call servlet through a JSP page

You could use <jsp:include> for this.

<jsp:include page="/servletURL" />

It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet() method.

request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

and in /WEB-INF/result.jsp

<p>The result is ${result}</p>

Now call the Servlet by the URL which matches its <url-pattern> in web.xml, e.g. http://example.com/contextname/servletURL.

Do note that the JSP file is explicitly placed in /WEB-INF folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.


If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action.

<form action="servletURL" method="post">

Its doPost() method will then be called.



See also:

  • Servlets info page - Contains a hello world
  • How to call servlet class from HTML form
  • How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
  • Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
  • Design Patterns web based applications

Is there any way to call servlet from JSP page without using form action tags?

If you do not want to use AJAX and JavaScript then you can call servlet first, set data calculated in servlet as request or session attributes and redirect to JSP. And in JSP extract data from request or session and show it or process it somehow.



Related Topics



Leave a reply



Submit