jsps and servlets

mailApp Oracle:-


































DBIntializer.java
public interface DBIntializer {
String DRIVER = "oracle.jdbc.driver.OracleDriver";
String CON_STRING = "jdbc:oracle:thin:@localhost:1521:xe";
String USERNAME = "raghu";
String PASSWORD = "raghu";
}

GetCon.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class GetCon {
private GetCon() {
}

public static Connection con;
static {
try {
Class.forName(DBIntializer.DRIVER);
con = DriverManager.getConnection(DBIntializer.CON_STRING,
DBIntializer.USERNAME, DBIntializer.PASSWORD);
} catch (ClassNotFoundException e) {

e.printStackTrace();
} catch (SQLException e) {

System.out.println("Exception in GetCon");
}

}

public static Connection getCon() {
return con;
}
}

header.jsp
<!DOCTYPE HTML>

<html>
<head>
<title>Mail Services</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script src="css/5grid/viewport.js"></script>
<script src="css/5grid/ie.js"></script>
<link rel="stylesheet" href="css/5grid/core.css" />
<link rel="stylesheet" href="css/style.css" />
<!--[if IE 9]><link rel="stylesheet" href="css/style-ie9.css" /><![endif]-->
</head>
<body>
<!-- ********************************************************* -->
<div id="header-wrapper">
<div class="5grid">
<div class="12u-first">
<header id="header">
<h1><a href="#">Mail services</a></h1>
<nav>
<a href="home.jsp">Homepage</a>
<a href="compose.jsp">Compose Mail</a>
<a href="inbox.jsp">Inbox</a>
<a href="LogoutServlet">Logout</a>
<a href="contactus.jsp">Contact Us</a>
</nav>
</header>
</div>
</div>
</div>

footer.html
<div id="footer">
<div id="copyright">
<br> <h3>For more information Click here<a href="http://www.javatpoint.com"> javatpoint</a><br>
Something of interest
If you are interested in doing more projects and want to learn much more 
Kindly have a look of my website clicking the following link..
<br>&copy; Copyright 2012,All Rights reserved..Designed by<a href="http://javatpoint.com/">javatpoint</a> + <a href="http://www.cstpoint.com/">Cstpoint</a>.</h3>
</div>
<br>
</div>

Register.jsp
<!DOCTYPE HTML>


<html>
<head>
<title>Mail Services</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<!--5grid-->
<script src="css/5grid/viewport.js"></script>
<!--[if lt IE 9]><script src="css/5grid/ie.js"></script><![endif]-->
<link rel="stylesheet" href="css/5grid/core.css" />
<link rel="stylesheet" href="css/style.css" />
<!--[if IE 9]><link rel="stylesheet" href="css/style-ie9.css" /><![endif]-->
</head>
<body>
<!-- ********************************************************* -->
<div id="header-wrapper">
<div class="5grid">
<div class="12u-first">

<header id="header">
<h1>
<a href="#">Mail services</a>
</h1>

</header>

</div>
</div>
</div>

<div id="main">
<div class="5grid">
<div class="main-row">
<div class="4u-first">

<section>
<h2>Welcome to Mailservices!</h2>
<p>
Hi! This is <strong>Mail Services</strong>, a free service by <a
href="http://www.javatpoint.com/">javatpoint</a><br> for <a
href="http://www.cstpoint.com/">Mailing system</a>. You can
perform all email operation,Currently it stores the information
in database it's free of cost.Let's try it..
</p>

</section>

</div>
<div class="4u">

<section>

<ul class="small-image-list">
<li><a href="#"><img src="css/images/pic2.jpg" alt=""
class="left" /></a> <span>

<h3 style="color: #007897;">Registration Form</h3> <br>
<div>
<%
if (request.getAttribute("registererror") != null) {
String msg = (String) request.getAttribute("registererror");
out.print("<font style='color:red'>" + msg);
out.print("</font><br/>");
}
%>

<form action="RegisterServlet">
<table style="table-layout: fixed;">
<tr>
<td>EmailId:</td>
<td><input type="text" name="email" /><br /> <br /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /><br />
<br /></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name" /><br /> <br /></td>
</tr>
<tr>
<td>Gender:</td>
<td>Male<input type="radio" name="gender" value="male">Female<input
type="radio" name="gender" value="female" /><br /> <br /></td>
</tr>
<tr>
<td>Contact Number:</td>
<td><input type="text" name="mname" /><br /> <br /></td>
</tr>
<tr>
<td>Country:</td>
<td><input type="text" name="country" /><br /> <br /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</span></li>



</ul>
</section>

</div>
<div class="4u">

<section>
<h2>How about some links?</h2>
<div class="6u-first">
<ul class="link-list">
<li><a href="http://www.javatpoint.com">Java tutorial
and more projects</a></li>
<li><a href="http://www.cstpoint.com">Learn
C,C++,Php,Html and much more free of cost </a></li>

</ul>
</div>

</section>

</div>
</div>

</div>
</div>
</body>

<div id="footer">
<div id="copyright">
<br>
<h4>
For more information Click here<a href="http://www.javatpoint.com">
javatpoint</a><br> Something of interest If you are interested in
doing more projects and want to learn much more Kindly have a look of
my website clicking the following link..
</h4>

<h5>
&copy; Copyright 2012,All Rights reserved..Designed by <a
href="http://javatpoint.com/">javatpoint</a> + <a
href="http://www.cstpoint.com/">Cstpoint</a>.
</h5>

</div>
<br>

</div>

<!-- ********************************************************* -->

</html>

index.jsp
<!DOCTYPE HTML>


<html>
<head>
<title>Mail Services</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<!--5grid-->
<script src="css/5grid/viewport.js"></script>
<!--[if lt IE 9]><script src="css/5grid/ie.js"></script><![endif]-->
<link rel="stylesheet" href="css/5grid/core.css" />
<link rel="stylesheet" href="css/style.css" />
<!--[if IE 9]><link rel="stylesheet" href="css/style-ie9.css" /><![endif]-->
</head>
<body>
<!-- ********************************************************* -->
<div id="header-wrapper">
<div class="5grid">
<div class="12u-first">

<header id="header">
<h1>
<a href="#">Mail services</a>
</h1>

</header>

</div>
</div>
</div>

<div id="main">
<div class="5grid">
<div class="main-row">
<div class="4u-first">

<section>
<h2>Welcome to Mailservices!</h2>
<p>
Hi! This is <strong>Mail Services</strong>, a free service by <a
href="http://www.javatpoint.com/">javatpoint</a><br> for <a
href="http://www.cstpoint.com/">Mailing system</a>. You can
perform all email operation,Currently it stores the information
in database it's free of cost.Let's try it..
</p>

</section>

</div>
<div class="4u">

<section>

<ul class="small-image-list">
<li><a href="#"><img src="css/images/pic2.jpg" alt=""
class="left" /></a> <span>

<h3 style="color: #007897;">Login or Signup</h3> <br>
<div>
<%
if (request.getAttribute("Error") != null) {
String Error = (String) request.getAttribute("Error");
out.print("<font style='color:red'>" + Error + "</font>");
}

if (request.getAttribute("Error1") != null) {
System.out.print(request.getAttribute("Error1"));
String Error1 = (String) request.getAttribute("Error1");
out.print("<font style='color:red'>" + Error1 + "</font>");

}
if (request.getAttribute("register") != null) {
System.out.print(request.getAttribute("register"));
String register = (String) request.getAttribute("register");
out.print("<font style='color:navy'>" + register + "</font>");
}
if (request.getAttribute("logout") != null) {
System.out.print(request.getAttribute("logout"));
String logout = (String) request.getAttribute("logout");
out.print("<font style='color:navy'>" + logout + "</font>");
}
%>


<form action="LoginServlet" method="post">

<table style="table-layout: fixed">

<tr>
<td>Email id</td>
<td><input type="text" name="email"></br> <br></td>
</tr>

<tr>
<td>Password:</td>
<td><input type="password" name="password"></br> <br></td>
</tr>

<tr>
<td></td>
<td><input type="submit" value="Sign in">&nbsp
&nbsp &nbsp &nbsp &nbsp <a href="Register.jsp">Signup</a>
</td>
</table>
</form>
</span></li>



</ul>
</section>

</div>
<div class="4u">

<section>
<h2>How about some links?</h2>
<div class="6u-first">
<ul class="link-list">
<li><a href="http://www.javatpoint.com">Java tutorial
and more projects</a></li>
<li><a href="http://www.cstpoint.com">Learn
C,C++,Php,Html and much more free of cost </a></li>

</ul>
</div>

</section>

</div>
</div>

</div>
</div>
</body>

<div id="footer">
<div id="copyright">
<br>
<h4>
For more information Click here<a href="http://www.javatpoint.com">
javatpoint</a><br> Something of interest If you are interested in
doing more projects and want to learn much more Kindly have a look of
my website clicking the following link..
</h4>

<h5>
&copy; Copyright 2012,All Rights reserved..Designed by <a
href="http://javatpoint.com/">javatpoint</a> + <a
href="http://www.cstpoint.com/">Cstpoint</a>.
</h5>

</div>
<br>

</div>

<!-- ********************************************************* -->

</html>

home.jsp
<jsp:include page="header.jsp"></jsp:include>
<div id="main">
<div class="5grid">
<div class="main-row">
<div class="4u-first">

<section>
<h2>Welcome to Mailservices!</h2>
<p>
Hi! This is <strong>Mail Services</strong>, a free service by <a
href="http://www.javatpoint.com/">javatpoint</a><br> for <a
href="http://www.cstpoint.com/">Mailing system</a>. You can
perform all email operation,Currently it stores the information in
database it's free of cost.Let's try it..
</p>

</section>

</div>
<div class="4u">

<section>

<ul class="small-image-list">

<li>
<div>
<%
if (session.getAttribute("username") != null) {
String username = (String) session.getAttribute("username");
out.print("<font style='color:navy'>Welcome " + username
+ "</font>");
} else {
request.setAttribute("Error1", "Plz Do login First");
%>
<jsp:forward page="index.jsp"></jsp:forward>
<%
}
%>
</div>

</li>

<li><marquee direction="up">
<font style="color: navy;"><h5>
Do any kind of operation related to <br> Mail Services
Such as Compose mail,<br> Inbox,And if you have Any Query
just<br> Contact Us ..by clicking above links ..
</h5></font>
</marquee></li>
</span>




</ul>
</section>

</div>
<div class="4u">

<section>
<h2>How about some links?</h2>
<div class="6u-first">
<ul class="link-list">
<li><a href="http://www.javatpoint.com">Java tutorial
and more projects</a></li>
<li><a href="http://www.cstpoint.com">Learn
C,C++,Php,Html and much more free of cost </a></li>

</ul>
</div>

</section>

</div>
</div>

</div>
</div>

<jsp:include page="footer.html"></jsp:include>

RegisterUser.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class RegisterUser {
static int status = 0;

public static int register(String email, String password, String name,
String gender, Double mname, String country) {
// public static int register(String email,String password,String
// gender,String country,String name){

Connection con = GetCon.getCon();
PreparedStatement ps;
try {
ps = con.prepareStatement("Insert into MAILCASTINGUSER values(?,?,?,?,?,?)");
ps.setString(1, email);
ps.setString(2, password);
ps.setString(3, name);
ps.setString(4, gender);
ps.setDouble(5, mname);
ps.setString(6, country);

status = ps.executeUpdate();

} catch (SQLException e) {

e.printStackTrace();
}
return status;

}
}

RegisterServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String email = request.getParameter("email");
String password = request.getParameter("password");
String name = request.getParameter("name");
String gender = request.getParameter("gender");

String num = request.getParameter("mname");
double mname = Double.parseDouble(num);
String country = request.getParameter("country");

int status = RegisterUser.register(email, password, name, gender,
mname, country);
if (status > 0) {
String register = "You are Successfully registered";
request.setAttribute("register", register);
RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.include(request, response);
} else {
String registererror = "Sorry,Registration failed. please try later";
request.setAttribute("registererror", registererror);
RequestDispatcher rd = request.getRequestDispatcher("Register.jsp");
rd.include(request, response);
}
out.close();
}

}

VerifyLogin.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class VerifyLogin {

public static boolean checkLogin(String email, String password) {
boolean status = false;
Connection con = GetCon.getCon();
try {
// PreparedStatement
// ps=con.prepareStatement("Select * from MAILCASTINGUSER where EMAILADD = ? and PASSWORD =?");
PreparedStatement ps = con
.prepareStatement("Select * from MAILCASTINGUSER where email = ? and password =?");

ps.setString(1, email);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
status = rs.next();

} catch (SQLException e) {
e.printStackTrace();
}
return status;
}
}

LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uname = request.getParameter("email");
String password = request.getParameter("password");
boolean status = VerifyLogin.checkLogin(uname, password);
if (status == true) {
HttpSession session = request.getSession();
session.setAttribute("username", uname);
out.print("Wel  " + uname);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.include(request, response);
} else {
String Error = "Please check your EMail and Password";
request.setAttribute("Error", Error);

RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);

}
out.close();
}

}

LogoutServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LogoutServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession(false);
session.invalidate();
request.setAttribute("logout","You have been sucessfully logged out");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}

}

<!----------- This is jsps and servlets project overview ---------->



Calling doPost () inside doGet (), Logical mapping & Default HTTP method

<body>

                <form action=”processFirstServlet”>

                                Enter first Name: <input type=”text” name=”fname” /><br/>

                                Enter last Name: <input type=”text” name=”lname” /><br/>

                <input type=”submit” value=”Submit/>”

                </form>

</body>

 

//The parameters are aapende to the URL.

So, it should be HTTP Get method.

 

FirstServlet.java

public class FirstServlet extends HttpServlet {

                //doGet

                //doPost

 

                @Override

                protected void doGet (HttpServletRequest req,  resp) throws                                   ServletException, IOException {

                                doPost(req, resp);

                }//doGet ()

 

                @Override

                protected void doPost (HttpServletRequest req,  resp) throws                                  ServletException, IOException {

                                String firstName=req.getParameter(“fname”);

                                String lastName=req.getParameter(“lname”);

                                String fullName=firstName+lastName;

System.out.println(“My Name is ” + fullName);

               

                }//doGet ()

 

 

}//class servlet

 

See o/p in console:-

--------======--------

 

 

 

 

 

 

 

web.xml

<web-app>

                <servlet>

                                <servlet-name></servlet-name>

                                <servlet-class></servlet-class>

                </servlet>

 

                <servlet-mapping>

                                <servlet-name></servlet-name>

                                <url-pattern></url-pattern>

                </servlet-mapping>

 

</web-app>

 

Where,

 

/ ----> represents the root of the application.

/projName --à represents the name of the appln.

 

/processFirstServlet ---à represents the logical name of the servlet, it’s not the actual name of the     

                                                     servlet class.

 

Printing a message using PrintWriter () in Browser:-

1.       In order, to print a message in a browser, we need a PrintWriter object.

2.       So, How do we getPrintWriter object?

Remember:-

3.       Is responsible for writing the data to a browser.

4.       Contains a method called getWriter ().

5.       And getWriter () gives us the PrintWriter object.

6.       So, let’s call the getWriter() on the  object.

 

Code:-

PrintWriter pw=resp.getWriter (); // This will give the PrintWriter object

pw.println (“My Name is ” + fullName);  keep form method=”POST

Using this PrintWriter object, we call the println() method.

 

Modify the Code:-

//Luckily, this  println() method accepts the html tags.

pw.println (“<html><body><h1>My Name is + “+fullName+”</h1></body></html>”);

1.       Writing the html tags in pw.println () is problem.

2.       To solve the problem we use jsp.

3.       Jsp contains html code as well as Java Code.

4.       We simply tell a servlet, to pass this HttpServletRequest,  and that jsp will take care of Everything.

 

Redirecting the response using sendRedirect():-

The client sends a request, the Web Container hand over’s the request to the server.

The Servlet process that request and once the processing is done, we have2 options:-

(1).Redirect the response to specific ‘URL’.

(2).We can dispatch the request to another component in the application.

Ex: JSP (or) JSF etc…..!!!!!

 

1.       To redirect the response to a different URL, we need a redirect() method.

2.       So, this HttpResponse contains a special method called sendRedirect() method.

3.       This will take a String as argument and we will pass the URL as a String.

 

Code:-

//Takes String as arg OK:-

resp.sendRedirect (“http://www.google.com”);

 

// Now, redirect the URL as part of the application.

Web Content:-

Test.html

<body>

                <h1>This is a test file. </h1>

</body>

 

Servlet Code change as:-

1.       resp.sendRedirect (“test.html”); // Yes the URL is re-directed to specific component in the application.

 

2.       But, redirecting the response to a specific URL’s doesn’t make sense.

 

3.       Because, we are not sending any data along with it.

 

4.       sendRedirect() works at client side, using which we cannot send any data.

 

5.       We will use if the client wants to perform further action.

 

Dispatch the Request using getRequestDispatcher():-

Web Content:-

Output.jsp

<body>

                <h1>This is a output file.</h1>

</body>

 

 

1.       In order to dispatch the request to another component, we need a request dispatcher object.

2.       This HttpServetRequest contains a special method called getRequestDispatcher () method.

3.       This will gives us the request dispatcher object and this method will takes the String as the argument and we will pass the jsp filename.

4.       So, that will gives us the request dispatcher object

 

Servlet code:-

RequestDispatcher rd=req.getRequestDispatcher(“/output.jsp”); // /--..> If you are in WEB-INF

rd.forward(req, resp);

Now, we need to forward this dispathcher to the client.

So, for that we will call the forward method on this object OK.

 

This will take two args:-

1.ServletRequest and

2.ServletResponse

 

These two are Servlet Interfaces.

Which are parent to HttpServletRequest and HttpServletResponse respectively.

 

 

Accessing the Java Object in JSP:-

1.       To Access the fullName inside the output.jsp, first we need to send that object to output.jsp.

2.       We are dispatching the object and forwarding the(req, resp) object to a output.jsp

 

3.       How do we send the object along with the request object?

Well, the request object contains a special method called setAttribute ().

 

This will take 2 args:-

setAttribute (name, value);

name----à Is the String, which will be used to access a value inside the jsp and this name should be                       unique.

value----àIs the Object, we are going to send.

 

Anytime, if you want to access a value we will access with the help of this name only.

 

Servlet Code:-

req.setAttribute (name”, fullName); // key, value (as Object OK)

RequestDispatcher rd=req.getRequestDispatcher (“/output.jsp”);

rd.forward (req, resp);

 

Now, Inside jsp we have to access this req, resp object:-

Jsp Code:-

<% // Java Code %>

 

1.       By default, req and resp objects are available in jsp.

2.       To get the value from request object, we will call a getAttribute () on the request object.

3.       This will take the String as the argument.

Ex:- getAttribute(name);

 

4.       And we will pass a key to which value we have to access OK.

 

Jsp Code:-

<% request.getAttribute (“name”); %>

5.       We have to specify the same name (as  Key) in the servlet while setting up the attribute.

 

6.       This will print a fullName in the Browser.

 

Name

Writing Java Code using Jsp Expression:-

name

Writing Java Code using Jsp Scriptlets:-

name

Writing Java method using JSP Declaration

How we write method inside the jsp Declarations:-
<%!
int callLength (String string) {
   return string.length();
}
%>
<!—we can call this method inside the same jsp -->
//Using the jsp expressions:-
<p>The length of the string  is <%= callLength(“B.Tech”) %> </p>
Save it.
The length of the string is ______. (Based on User Input Given will be calculated)

There are 3 ways to write Java Code inside the jsp:-
1. Jsp Expressions: - one line java code.
2. Jsp Scriptlets: - more than one line of java code.
3. Jsp Declarations: - If you want to write any method then we can use Jsp Declarations.

High Level Overview of Servlet Life Cycle

1.       When a client sends the request the browser creates two objects HttpRequest and HttpResponse.
2.       These are Http Objects not Java Objects.
3.       The container takes that request read the web.xml depending upon the URL a servlet object will be loaded to the memory.
4.       Now, The container will create the servlet Object but invoking the constructor object, Once the Object is created a special method will be called which is a init() method.
5.       init () method is a part of the life-cycle method of a servlet which will be called only in the once Entire life cycle of a servlet.
6.       This init () will be called as soon as the servlet Object will be created.
7.       Once the init () method is called back with another life cycle method will be called which is the service method.
This service method will take the two args:-
1.       The container takes two Http Objects and converts it into a Java Objects.
Because, the servlet can only understand java, so the container will convert those Http Objects into Java Objects which is nothing but HttpServletRequest and pass it to a service method.

2.       So, the service method takes that two Objects and depending upon the Http method a
doGet() (or) a doPost() method will be called.

A.      This service method will be called each and every time when we make a request and service method will call doGet (or) doPost method.

B.      Once, the processing is done, the container will convert those objects into Http Objects and send it back to a client.

C.      And, Finally a destroy method will be called.
D.      The destroy) method will be called before shtdowning the appln or just before shutting down the container.
E.       Once, the destroy method is called servlet object will be removed from the container.
This is the High Level Overview of the Servlet.





Overview of Servlet Life Cycle:-





1.       The servlet object will be created, invoking the no-arg constructor.
2.       But with init () method will be called only once in the entire life cycle of a servlet.
3.       Back with service () method will be called.
4.       For this the container will pass the Http Objects converted into Java Objects and it will give to a service () method.
5.       The service method will call doGet () or doPost () depending on the Http method
6.       Finally destroy () method will be called, again the destroy () method will be called only once in the Entire Life Cycle of a servlet just before shutting down the application or the container.

When we will call these life cycle methods, at what point of time we call this life cycle methods?
Is it necessary to override all these methods?
Ans:-

More About Servlet Life Cycle Methods
public void init() throws  ServletException {
                super.init();
                System.out.println (“Inside the init():::::::”);
}// init ()
//I’m going to override service ():-
@Override
Public void service (HttpServletRequest req, HttpServlerttResponse resp) throws ServletException, IOException {
                super.service (req, resp);
                System.out.println (“Inside the service () :::::::::”);
}// service ()
//Finally, I’m going to override destroy ():-
public void destroy () {
                super.destroy ();
                System.out.println (“Inside the destroy () :::::::::”);
}
So, the Question Is when we will Override this init () method?
Ø  99% off the time we don’t Override the init () method.
Ø  Get the Database Connection then inside this init () will do that OK.
Ø  So, this will be called any request we are going to send the server the init () method will be called as soon as the object will be created.
Ø  So, if you want any Database Connection or register the Driver class inside this init () method we will do that.

Ø  So, this will be called in the Entire Life Cycle of a Servlet.

Service ():-
Ø  We should not Override service () method, because we always implement the super class implementation, so if you go to HttpServlet (Ctrl + spacebar) it will take you to the class implementation of HttpServlet.
Ø  Press ctrl + o, and type service and you can see always pickups up the superclass implementation.
Ø  So here the container will pass the HttpServletRequest and HttpServletResponse



Ø  So, now the service method will call the get () method on this request object to get the Http method.
Ø  So, depending on the Http ‘GET’ method, doGet () or doPost () method will be called.
Ø  Our job is to get Override doGet () or doPost () OK.
Ø  The service () always picks up the implementation of super class and that will call the doGet () or doPost () method.
Ø  So, we should not Override the service () method.



1.       So, that is why here I’m calling super class service ().
2.       That will take care of the doGet () and doPost () method.


1.       Finally the destroy () method again we should not override this destroy () method most of the times.
2.       But, in your application you want to free up the database resources then you will call the destroy () method.
3.       Inside this destroy () method we will free up those resources.
4.       When, we make the first request the object will be created.

See console:-



1.       First the constructor will be called; I’m meant that servlet object will be created by calling the no constructor argument as soon as the constructor is called.
2.       init () method will be called, this will be called only in the entire life cycle of a servlet, he init( method is called as soon as the object is created, as soon as the init() method is called.
3.       A service () method will be called, this service () method will be called each time when you make a request so, let’s try it out. Go to browser:-

If you make one more request again:-


Go to the console: - Again service () method is called.
 1.It will not call the cons or init () method because the object will be called once and the init () method will be called once when we make request the service () method will be called inside the service () method: - doGet () or doPost () method will be called.
2. Inside the doGet () method if we write any message it will not print.
      3.So, finally destroy () method will be called before shutting down the application or shutting down the container, destroy () method will be called.



1.       The destroy () method will be called inside the destroy () method.
2.       So, if you make any changes in the servlet automatically the container or the application will get shutdown to just before shutting down the application the destroy() method will be called.
3.       In your application you want free up the resources like jdbc connection object then you can write in the destroy () method.
4.       So, this is how servlet object will be created and servlet object will be destroyed.
5.       As soon as we send the new request a servlet object will be created using no-cons arg, as soon as the constructor is called and init() method will be called and service() method will be called back with init() method .
6.       The service () method will be called each time when you make the request and the service () method will call doGet () or doPost () method.
7.       We should not override the service () method it will always pickups up the super class implementation that will take care of doGet () or doPost () method.
8.       So, this is the life cycle of a servlet, we understood that when actually the servlet object will be created and actually the servlet class will be destroyed and when we have to Override the servlet life cycle methods.

Know About Handling Multiple Requests
How the container handle multiple requests?
Ø  The client A will send the request to the server the server takes that request convert the Http objects into java objects and hand over it to a service() method.
Ø  A service () method will call the doGet () or doPost () method depending upon the Http method.
Ø  Assume that client A is sending get() method so the service() method will call the doGet() method while processing the doGet() method, the client B is sending the request now what will happen?
Ø  Whether the container will stops the execution of the client A and it will give the chance to client B. or the container first completes the containers A‘s request and then picks up the client’s B ‘s request.
Ø  It means the container handles the both the requests.
Ø  Which means the container executes the both the requests simultaneously.
Ø  Because the client A is already occupied the request and response objects.
Ø Remember:-
1.       Each request will be run in a separate thread, which means the container will allows or creates the new request.
2.       So, each time when we make a request the container will create the two special objects HttpServletRequest and HttpServletResponse in a separate thread.
3.       So, those two objects will be passed to a service () method, the service () method will take those two objects then it will call doGet() or doPost() method depending upon the Http method  and completes its execution, those two objects will be destroyed or it is available for Garbage Collection.
4.       So, this is how the container will handle the multiple requests.
5.       The container will allocates or creates a new thread for each request and inside the thread the request will be processed.
6.       Each time when we make the requests the container will create the request and response objects.
7.       Once everything is done those two objects is eligible for Garbage Collection.
8.       The most important thing is each time when we make the request a separate object will not be created only servlet object is created once but each time when we make a request HttpRequest and HttpResponse are created.
9.       Those two objects will be created not the servlet object.
10.   This is the High Level Overview of Handling the multiple requests by the container.

Introduction to EL Expression
Ø  Here we are accessing the simple attribute in jsp.
Ø  Using the El Expressions we can access the java objects without touching the java code.
Ø  Simply, it looks like a html code.
Ø  All you need to do is specify a dollar symbol open the curly ${2+2} //mathematical expression, ternary expressions and some logical expressions, reload the web page to see changes.




Ø  Access these java objects inside our jsp without writing the java code.

Dive deeper into EL Expression
Way of writing the conditional operators
We have added this fullName to the request object

And attribute name is a name.
You just have to specify the attribute name b/w the curly braces like this:-

You can write conditional operators inside the Expressions

In this case it is false because we have given the space b/w the names.




Out.jsp

Ø  And I’m accessing  the property using EL Expressions
Ø  If we have to access the Student property we have to access the Student object.
Ø  Add the student to the Student object inside our servlet.
Ø  So let’s access the student object with the attribute name which is a student.
Ø  Or followed by a period we have to specify the property that we areas going to access
Reload the web page or restart the server.
Ø  This is how we can access the java objects inside the jsp.

Assignment:-
Ø  You have to create one more tag h3 tag and you have to write an msg my name is your Name and I am your age and I am from your location.
Ø  You have to access this your Name and Your Age and Your Location through the El Expressions
Ø  So inside the Student.java you have to create the two more properties which is age property and location property and you have to create Setters and Getters.
Ø  So, inside the FirstServlet.java we have to set the age and location to the student object and inside the out.jsp you have to create the h3 tag and you have to access those name property, age property and location property through the El Expressions .
Ø  Go ahead and complete the assignment.







We can use jstl tags to perform what we are doing using the scriptlet tag.












No comments:

Post a Comment