java servlet using the function of another java servlet? - java

Is it possible for a java servlet to call the function that is in another java servlet? And if it is possible, can you show me a simple example of how to do it?
Thank you in advance

Calling a servlet directly from another servlet is not recommended and considered bad practice because servlet instances are managed by the servlet container. You should follow the separation of concerns principle.
The servlets are responsible for the interface to clients only and shouldn't contain business logic. Put your business logic in a separate layer (e.g. classes in another package) and call it from the servlets only. So the business classes are responsible for the actual internal data and transformations and the servlets are responsible for different views to the outside.

Several options.
Making it static one way (I do not prefer).
Create a Class and supply required params and create instance in each servlet.

Somewhat hackish way:
RequestDispatcher dispatcher = request.getRequestDispatcher("/someServletOfYours");
dispatcher.forward(request, response);
Now, implement the method of yours in doPost of your "someServletOfYours" class. In case you need to pass parameters, call the setAttribute method of ServletRequest, and fetch parameters from the request in your next servlet. From "someServletOfYourrs" you can redirect back to your original servlet. It will imitate a method call by means of http.

Servlet1
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet1
*/
#WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Servlet2 s = new Servlet2();
s.CreateUser();
response.getWriter().append("Served at: ").append(request.getContextPath());
}
}
Servlet2
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet1
*/
#WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
public void CreateUser() throws FileNotFoundException{
System.out.println("Create Users...");
}
}
Output :

Related

Issue with servlet defaulting to index servlet. Tomcat 8.0.30 JDK 1.8

So I have a servlet listening on "/ajax/foo", and a servlet listening on "/". When I make a call to /ajax/foo, it initializes that servlet but doesn't call the get or post overridden methods it defaults to "/" for those, even thou I am not extending it, I am extending HttpServlet.
I am also using annotations to setup the servlet paths. I wonder if this can be causing it. I also checked all the methods and even copied over servlet doPost/doGet methods, that are working since I can verify it yet in this servlet still don't get called. Servlet doesn't write anything out, and is being called over ajax (jquery $.post).
Thank you for any help.
package ajax;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet("/ajax/foo")
public class FooAjaxServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ThreadAdminActionAjaxServlet() {
super();
System.out.println("LOADED");
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("GET")
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("POST");
}
}

Calling a servlet from Java code

I am currently trying to complete a login system using jsp and servlets.I have my register and login validation working.
I wish to link to a welcome page following login to display the user profile information.
I had, just for testing purposes, a response.sendRedirect(welcome.jsp) which redirected following a successful login by the login servlet.
Now, to display the profile info on this welcome page I was going to use a servlet to gather the info from the database and render it to the the browser using a printwriter.
How do I call this servlet successfully from the loginservlet to run the doPost() method?
Or is there a better way of doing it?
Thank you for your time.
(For simplicity, I was just trying to get a basic webpage to appear first to make sure this was working I will have no problem with the database side of things once I get this going)
LOGIN SERVLET:
package logon;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
System.out.println("In the Login Servlet");
User user = new User();
user.setEmail(request.getParameter("email"));
user.setPassword(request.getParameter("password"));
LoginDAO.login(user);
if(user.isValid())
{
HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser",user);
session.setAttribute("currentSessionUserEmail", user.getEmail());
response.sendRedirect("WelcomeServlet");
}else
response.sendRedirect("LoginFailure.html");
} catch (Throwable exc)
{
System.out.println(exc);
}
}
}
WELCOME SERVLET:
package logon;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WelcomeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<html>"+"<head>"+"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");
out.print("<title>Welcome</title>");
out.print("</head>"+"<body>");
out.print("Welcome to the welcome page!!!");
out.print("</body>"+"</html>");
}
}
You can't redirect using POST, only using GET. Since you're just displaying HTML in WelcomeServlet move the code from doPost to doGet, or make the one call the other, which simply makes them both do the same thing.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
Also, it would be better to use a JSP than to out.print a bunch of HTML inside a servlet. See the info page for servlets.
Plus, obviously your welcome page needs to read the attribute currentSessionUser from the session and make sure its not null to see if the user is really logged in or not. Otherwise if a user knows the address of the welcome page they can just bypass your login check as you have it now.
Your problem is that you have currently implemented your Servlet to respond to the wrong HTTP verb.
You'll notice that the servlet has as doPost and a doGet method. As you might expect these map onto HTTP GET and HTTP POST requests. Your current problem stems from the fact that you have implemented the doPost method in your WelcomeServlet therefore expecting a POST request, when it will actually be serving a GET request.
Speaking very crudely, you can think of GET requests as read operations and POST requests as write operations. So when you submit a form to save some data, this is typically handled a POST request. You are basically asking to write data to a database or session. When you load a web page, this is typically handled as a GET request. You are simply asking to read the data.
Again simplifying, but re-directs are typically GET requests. Therefore your Servlet will need to implement the doGet() method to respond to the browsers GET request after it is re-directed.

HTTP method GET is not supported by this URL

I like to run a servlet on a tomcat server but it gives the error as above.Also when i put ajax request on the servlet it did not working through index.jsp.Please help me friends.
also explain briefly because I am at the starting level of servlet.
import java.sql.Connection;
java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
import java.util.Arrays;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySQLAccess extends HttpServlet
{
public void getRows(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
{
String a="";
PrintWriter out = response.getWriter();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sankar?" + "user=root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement
.executeQuery("SELECT * FROM sankar.datas");
a=resultSet.getString("name");
}
catch (Exception e)
{
e.printStackTrace();
}
out.println(a);
}
}
In order to accept the GET request, you need to override the doGet method in your MySQLAccess servlet class. Considering the code, you may just have to replace the name of your getRows method to doGet. From javadocs
HttpServlet class provides an abstract class to be subclassed to
create an HTTP servlet suitable for a Web site. A subclass of
HttpServlet must override at least one method, usually one of these:
doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
You need the doGet-Method like so:
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// your code
}
This method is called from the server (tomcat container more specifically) when a GET request is sent to the servlet.
If you wish to use POST you need to implement the doPost(...)method, btw.

Servlet communication between web-apps

using the ServletContext to enable communication between Servlets within the same Application is quite nice and I wonder if there's a comparable way to enable communication between servlets from different apps (which are deployed on the same Servlet-Container?
The background is that I've two applications which could be distributed to multiple servers. In that case they're supposed to communicate via SOAP - but in case they're both hosted in the same server (and Servlet-Container) I'd like to avoid the SOAP overhead and have direct communication.
Any suggestions?
Cheers
Such API existed in the first version of Servlet API. You could find other servlets from servlet context and call them. I doubt you could call servlets from other web applications.
Anyway this API was deprecated and is not supported more. The reason is that EJBs were introduced. Servlets play role of a web front-end only. They should not implement business logic and therefore should not communicate with each other.
The modern way to perform communication among different application is either using web services or EJB or if you are using Spring - their remote mechanisms or messaging.
I am not sure about different servlet container. But it works for same container by using
getServletContext().getContext() method.
First you need to make changes in below file
(Windows) C:\Program Files\Apache Software Foundation\Tomcat 7.0\conf\context.xml
Set value of crossContext to true.
context.xml
<Context crossContext="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
Please note that crossContext="true".
Suppose you have two web applications with name InterServletComm1 and InterServletComm2
having servlets Servlet1 and Servlet1 in each web application respectively. Then the code in each servlets goes as follows:
Servlet1.java
package interServletComm1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet1
*/
#WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
request.setAttribute("name", "WebApp1");
ServletContext context = getServletContext().getContext("/InterServletComm2");
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Servlet2.java
package interServletComm2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet2
*/
#WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = (String) request.getAttribute("name");
pw.println("This is web application 2.");
pw.println("<br>The value received from web application one is: " + name);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Above code sends attribute name from InterServletComm1 and it is received in InterServletComm2.
Please let me know if this answer is not clear.

Communication between two web application in same server

All,
I have 2 web applications, Web1 and Web2, deployed on my tomcat server. I want classes in Web1 to call methods on classes in Web2. One way to do this is using webservice. Is there any other way similar to calling a method on class on same web application ?.
Thanks.
Yes. It is possible. It tried for same servlet container by using
getServletContext().getContext() method.
First you need to make changes in below file
(Windows) C:\Program Files\Apache Software Foundation\Tomcat 7.0\conf\context.xml
Set value of crossContext to true.
context.xml
<Context crossContext="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
Please note that crossContext="true".
Suppose you have two web applications with name InterServletComm1 and InterServletComm2
having servlets Servlet1 and Servlet1 in each web application respectively. Then the code in each servlets goes as follows:
Servlet1.java
package interServletComm1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet1
*/
#WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
request.setAttribute("name", "WebApp1");
ServletContext context = getServletContext().getContext("/InterServletComm2");
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Servlet2.java
package interServletComm2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet2
*/
#WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = (String) request.getAttribute("name");
pw.println("This is web application 2.");
pw.println("<br>The value received from web application one is: " + name);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Above code sends attribute name from InterServletComm1 and it is received in InterServletComm2.
Please let me know if this answer is not clear.
Just searched around some articles and the above scenario is certainly possible using CrossContext switching in Tomcat.
Set the following element in context.xml in <Context crossContext="true">
And then getServletContext().getContext("/Web2");.
Haven't tried yet, though.
Yes you can do it using javax.servlet.ServletContext and javax.servlet.RequestDispatcher API's. Here it is how it can be done from Web1:
ServletContext otherContext = servletContext.getContex("/Web2");
RequestDispatcher dispathcer = otherContext.getRequestDispatcher("/a/b.jsp");
dispatcher.forward(request, response);
//or
dispatcher.include(request, response);
Package the classes you want to share between web applications into a separate jar. Put them under common/lib so that the common classloader will load the classes and would be available to both web applications. Then expose the instance in web2 using jndi, look up them from web1 and invoke the methods.
Pretty much it is not that simple. You can share and import classes from your app1 into app2, but maybe they're all linked with other classes. So the idea is not so good except of small services like beans which are used to make calculations for example. There is a reason ppl are using web services so much ;).

Categories

Resources