JSP & Servlet
Servlet
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.
We can implement 2 types of interface.
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
Life Cycle of Servlet
- First servlet is constructed, and initialized with init method.
- Any calls from clients to the
service
method are handled. - When servlet is out of service, then destroy method is called for garbage collection.
Methods of Servlet
- void destroy()- Used to indicate a servlet is taken out of service.
- ServletConfig getServletConfig()- Returns object of ServletConfig which contains initialization and startup parameter.
- java.lang.String getServletInfo()- Returns author, version and copyright of server.
- void init(ServletConfig config)- Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
- void service(ServletRequest req, ServletResponse res)- Called by the servlet container to allow the servlet to respond to a request.
Example:-
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
res.setContentType(“text/html”);//setting the content typePrintWriter pw=res.getWriter();//get the stream to write data
pw.println(“<html><body>”);
pw.println(“Welcome to servlet”);
pw.println(“</body></html>”);
pw.close();//closing the stream
}}<web-app>
<servlet>
<servlet-name>Bhuvi</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Bhuvi</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
JSP
A JSP page is a text document that contains two types of text.
- Static data, which can be expressed in any text-based format (such as HTML, SVG, WML, and XML).
- JSP elements, which construct dynamic content.
JSP Tags
- Declaration Tag:- Used to declare variables.
<%! int var=10; %>
2. Java Scriplets:- Used to add any type of java code.
<%
String s="Kamesh";
System.out.println(s);
%>
3. JSP Expression:- Evaluates and convert the expression to a string.
<% num1=num1+num2 %>
4. Comments:- Used to add comment in code.
<% -- JSP Comments %>
JSP Life Cycle
- Internally JSP page is converted into a servlet.
- Compilation of JSP page.
- Class loading means jsp.java file is converted into class file.
- Instantiation means object of generated servlet class is created.
- Initialization menas jsp init() method is invoked by container.
- Request Processing means jsp service() method is invoked by container.
- Destroy method is called for garbage collection.
Example:-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="admin.jsp"%>
<%@ page import="com.ContactPage.ConnectionProvider"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DashBoard</title>
</head>
<body>
<hr/>
<form action="Archieve.jsp" method="post">
<%
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
if (session.getAttribute("session") == null) {
response.sendRedirect("login.jsp");
}
try {
Connection connection = ConnectionProvider.getConnection();
Statement statement = connection.createStatement();
String query = "Select * from contactus where isactive=true ORDER BY timestamp";
ResultSet resultset = statement.executeQuery(query);
%>
<h1>Active Requests</h1>
<table border="1">
<tr>
<td>Full Name</td>
<td>E-Mail</td>
<td>Message</td>
<td>Time Zone</td>
</tr>
<%
while (resultset.next()) {
%>
<tr>
<td><%=resultset.getString(1)%></td>
<td><%=resultset.getString(2)%></td>
<td><%=resultset.getString(3)%></td>
<td><%=resultset.getString(4)%></td>
<td><input type="submit" value="Archieve"> <input
type="hidden" value=<%="Archieve" + resultset.getInt(6)%>
name="Archieve"></td>
<%
}
} catch (Exception exception) {
out.println(exception);
}
%>
</table>
</form>
<br>
<hr />
<h1>Archive Requests</h1>
<form action="UnArchieve.jsp" method="post">
<%
try {
Connection connection = ConnectionProvider.getConnection();
Statement statement = connection.createStatement();
String query = "Select * from contactus where isactive='false' ORDER BY timestamp";
ResultSet resultset = statement.executeQuery(query);
%>
<table border="1">
<tr>
<td>Full Name</td>
<td>E-Mail</td>
<td>Message</td>
<td>Time Zone</td>
</tr>
<%
while (resultset.next()) {
%>
<tr>
<td><%=resultset.getString(1)%></td>
<td><%=resultset.getString(2)%></td>
<td><%=resultset.getString(3)%></td>
<td><%=resultset.getString(4)%></td>
<td><input type="submit" value="UnArchieve"> <input
type="hidden" value=<%="UnArchieve" + resultset.getInt(6)%>
name="unArchieve"></td>
</tr>
<%
}
} catch (Exception exception) {
out.println(exception);
}
%>
</table>
</form>
</body>
</html>
Output:-
Conclusion
When ever we compile JSP it is converted into servlet. So there is no real time difference. But usually there is a tradition to use servletes for controllers and JSPs for views. Controllers are like java classes so we can get full tool support from our favorate IDEs.