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!
Calling a Web Service in the Same Application If the target web service is part of the same application as the JSP or servlet, the short answer is that you shouldn't call the web service. The fact that you want to probably means that there is business logic in the web service that should instead be placed in a Java control.
1. Using HttpServletRequest 2. Redirect to JSP using query string 3. Passing Objects from servlet to JSP 4. Passing ArrayList from Servlet to JSP 5. Passing HashMap from Servlet to 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.
To access a servlet you need to send it an HTTP request in the form of either a GET or POST request (there are others like HEAD and DELETE but you wouldn't be explicitly using them in most circumstances). You could put a link (HREF) to the servlet and attach a querystring to the end to pass information. This is known as a GET request.
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
<jsp:include page="/HelloWorld"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With