Server-Side Technologies
There are many techniques for writing server-side programs to enable client interaction. In the Java world, however, the fundamental technique is using Servlet Technology.
What is a Servlet?
A Servlet is an interface provided by the Java API in the javax.servlet package. This interface is implemented by three classes, of which the HttpServlet class is the most commonly used.
Typically, developers create their own servlet by extending the HttpServlet class. Once a servlet is compiled to bytecode and deployed on a web server like Tomcat or JBoss, clients (browsers, other programs) can start connecting with the servlet to have a conversation with the application server through HTTP request-response cycles.
A servlet is the glue that makes communication happen between clients and the application server.
Here is an example of a simple HelloWorld servlet:
package com.mbcc.servlets;
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;
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Hi there. You used the Get method to contact me!");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Hi there. You used the Post method to contact me!");
}
}
Once the above servlet is deployed on an application server, open a browser and navigate to http://localhost/[project]/HelloWorld. You will see that the servlet's doGet method is invoked, and the content that is appended to the response object is written to the browser.
The user's request information is available in the request object of both methods. Whatever you want to send to the user, you can write to the response object, and that will be delivered to the client. Browsers parse that and display the content.
Forwarding the Request
You can also forward the request to another servlet or HTML/JSP page upon certain conditions. Here is an example of login functionality that checks the login information and forwards the request to the appropriate pages based on login success or failure:
package com.mbcc.servlets;
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;
@WebServlet("/auth")
public class AuthServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("user_name");
String password = request.getParameter("password");
if (password.equals("jravi") && name.equals("jravi")) {
this.getServletContext().getRequestDispatcher("/welcome.html").forward(request, response);
return;
}
this.getServletContext().getRequestDispatcher("/loginfailed.html").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
To forward the request to any other page or servlet, you need to get a handle on the RequestDispatcher through the ServletContext object.
You have to send the received request and response objects to the forwarded entity.
Create three HTML files (login.html, welcome.html, and loginFailed.html) inside the WebContent folder and try out a successful and a failed login.
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="auth" method="post">
<label for="name">User name:</label>
<input type="text" id="username"
name="user_name"> <br> <br>
<label for="mail">Password:</label>
<input type="password" id="password" name="password"> <br>
<br> <input type="submit" />
</form>
</body>
</html>
loginfailed.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Failed</title>
</head>
<body>Hey your login failed! Please try again by hitting the back
button
</body>
</html>
welcome.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome!</title>
</head>
<body>
Hey your authentication was successful! Welcome
</body>
</html>
- Extend the
HttpServletclass to create your ownHttpServlet. - Override the superclass's
doGetordoPostmethods to handle GET or POST HTTP requests. - The superclass's
doGetanddoPostmethods do nothing. - Client request information can be obtained from the
HttpServletRequestobject given as a parameter in bothdoGetanddoPostmethods. - To send data back to the client, use the
HttpServletResponseobject given as a parameter in bothdoGetanddoPostmethods. - From Servlet 3.0 onwards, you can add the
@WebServletannotation to specify the servlet path on the server. - Prior to Servlet 3.0, you are required to add the servlet definitions in the deployment descriptor (
web.xml) file. - Query parameters or POST parameters can be retrieved using the
request.getParameter()method. - To send attributes from one servlet to another, use the
setAttribute()method, and in the receiving servlet, use thegetAttribute()method. - There is no
setParameter()method. - To forward your request to another page/servlet (e.g.,
/welcome.html), usegetServletContext().getRequestDispatcher("/welcome.html").forward(request, response).