Unit Ii-Servlet
Unit Ii-Servlet
What is a Servlet?
As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet performs all the
tasks. When the web container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when
the first request for the servlet is received by the web container.
Apache tomcat
If you are a little familiar with the websites or have some basic knowledge about the
websites, you must have heard about the HTTP protocol or may also know what
actually are they. If you want to provide any web-services such as you want to provide
a simple static content possibly by using HTML (or Hypertext Markup Language), or
maybe you just want to send data from a server to point you, so you necessarily need
a server and that server is HTTP(HyperText transfer protocol). So, as we all know that
if anyone wants to make a simple, static website, he definitely requires an HTTP server,
but if he wants to make website dynamic, he has to use servlet. We use the HTTP server
if we want to send simple data. If we want to send dynamic data or to make our website
dynamic, we need to use the servlet. Hence, we need an HTTP server and what else we
need is a container where we will run or servlet, so when we combine the HTTP server
and the servlet (or we can say servlet container), they both combine to become a single
server know as tomcat server.
There are many versions of the Tomcat available with different features on its website.
You can choose the version according to your requirements, but we suggest you
download the latest stable version.
Step 1. Open the Google Chrome or any of your web browser and type "download
Tomcat for windows" in the search box. You can also go directly on Tomcat's website
by clicking on this https://tomcat.apache.org/download-90.cgi#9.0.38
Step 2. Go to Download and click on the downloaded file and wait for little until the
installation process starts.
Step 3. Once the installation process gets started, click on the "Next" button, as
shown below:
Step 6. Enter the user name and password and click on the " Next" button, as shown
below:
Step 7. Then click on the "Next" button again
Step 9. Now click on the "Finish" button, here the installation of Tomcat is completed.
It may ask you to restart your system, so restart your system.Now you can start the
Tomcat by clicking on its icon, and you can start and stop the server.
Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.
The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible
for http requests only.
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Handling http request and response with HTTPGET and
HTTPPOST.
HTTPGET
The GET method is used to retrieve information from the given
server using a given URI. Requests using GET should only
retrieve data and should have no other effect on the data.
Follow the steps given below to send a HTTP POST request using
HttpClient library.
The HttpPost class represents the HTTP POST request. This sends
required data and retrieves the information of the given server
using a URI.
HTTP is stateless that means each request is considered as the new request. It is shown
in the figure given below:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the
browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain
than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tags, etc.
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of
the Servlet in JSP. In addition to, we can use implicit objects, predefined tags,
expression language and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the
presentation logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces
the code. Moreover, we can use EL, implicit objects, etc.
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the help of
JSP translator. The JSP translator is a part of the web server which is responsible for
translating the JSP page into Servlet. After that, Servlet page is compiled by the
compiler and gets converted into the class file. Moreover, all the processes that happen
in Servlet are performed on JSP later like initialization, committing response to the
browser and destroy.
JSP tags
There are main 3 types of tags
o scriptlet tag
o expression tag
o declaration tag
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
In this example, we have created two files index.html and welcome.jsp. The index.html
file gets the username from the user and the welcome.jsp file prints the username with
the welcome message.
File: index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
JSP expression tag
The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print the
values of variable or method.
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting
the instance of Calendar class by the getInstance() method.
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP Declaration Tag
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method
of auto generated servlet.
In this example of JSP declaration tag, we are declaring the field and printing the value
of the declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
<%--
Document : newjsp
Author : hp
--%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script
src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<div class="row">
<div class="card">
<div class="card_content">
<div class="btn">
<span>File</span>
</div>
<div class="file-path-wrapper">
</div>
</div>
</form>
</div>
<div class="circle"></div>
</div><div class="gap-patch">
<div class="circle"></div>
<div class="circle"></div>
</div>
</div>
</div>
<div class="circle"></div>
</div><div class="gap-patch">
<div class="circle"></div>
<div class="circle"></div>
</div>
</div>
</div>
<div class="preloader-wrapper small active">
<div class="circle"></div>
</div><div class="gap-patch">
<div class="circle"></div>
<div class="circle"></div>
</div>
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-migrate-3.4.0.js"
integrity="sha256-0Nkb10Hnhm4EJZ0QDpvInc3bRp77wQIbIQmWYH3Y7Vw="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
console.log("page is ready")
$("#myform").on('submit',function (Event){
Event.preventDefault();
// var f = $(this).serialize();
console.log(f);
$(".loader").show();
$(".form").hide();
$.ajax({
url: "Register",
data: f,
type: 'POST',
console.log(data);
console.log("succes..........")
$(".loader").hide();
$(".form").show();
if(data.trim()==='done')
$('#msg').html("Successfully Registered")
$('#msg').addclass('green_text')
}else
$('#msg').addclass('red_text')
},
console.log(data);
console.log("error.....")
$(".loader").hide();
$(".form").show();
processData:false,
contentType:false
})
</script>
</body>
</html>
Register.servlet
/*
*/
package com.user;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* @author hp
*/
@MultipartConfig
/**
* methods.
*/
response.setContentType("text/html;charset=UTF-8");
// out.println("<!DOCTYPE html>");
//out.println("<html>");
//out.println("<head>");
//out.println("<title>Servlet Register</title>");
//out.println("</head>");
//out.println("<body>");
// out.println(filename);
// out.println(name);
//out.println(password);
//out.println(email);
//connection
try
Thread.sleep(3000);
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");
PreparedStatement pst=con.prepareStatement(q);
pst.setString(1,name);
pst.setString(2,password);
pst.setString(3,email);
pst.setString(4,"fileName");
// pst.setString(4,fileName);
pst.executeUpdate();
// InputStream is = part.getInputStream();
// byte[]data=new byte[is.avalable];
// is.read(data);
// String path=request.getRealPath("/")+"image"+File.separator+filename;
// out.println(path);
//fos.write(data);
// fos.close();
}catch(Exception e){
e.printStackTrace();
out.println("<h1>error.......</h1>");
//out.println("</body>");
//out.println("</html>");
/**
*/
@Override
try {
processRequest(request, response);
/**
*/
@Override
try {
processRequest(request, response);
/**
*/
@Override
}// </editor-fold>