4 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

1 |M.

sc sem I OOPs USING JAVA

UNIT IV Servlet, Java Beans and JNDI


(1) What is Servlet Deploying a Servlet
There are given 6 steps to create a servlet example. These steps are required for all the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific method
such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:Hello Java Program
for Beginners

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

1)Create a directory structures


The directory structure defines that where to put the different types of files so that web container may
get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the
directory structure that must be followed to create the servlet.
2 |M.sc sem I OOPs USING JAVA

As you can see that the servlet class file must be in the classes folder. The web.xml file must be under the
WEB-INF folder.

2)Create a Servlet
There are three ways to create the servlet.

1. By implementing the Servlet interface


2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such
as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inheriting
the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the
default request.

DemoServlet.java

1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
3 |M.sc sem I OOPs USING JAVA

7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10.
11. //writing html in the stream
12. pw.println("<html><body>");
13. pw.println("Welcome to servlet");
14. pw.println("</body></html>");
15.
16. pw.close();//closing the stream
17. }}

3)Compile the servlet


For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:

Jar file Server

1) servlet-api.jar Apache Tomcat

2) weblogic.jar Weblogic

3) javaee.jar Glassfish

4) javaee.jar JBoss

Two ways to load the jar file

1. set classpath
2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-
INF/classes directory.

4)Create the deployment descriptor (web.xml file)


The deployment descriptor is an xml file, from which Web Container gets the information about the servet
to be invoked.
4 |M.sc sem I OOPs USING JAVA

The web container uses the Parser to get the information from the web.xml file. There are many xml parsers
such as SAX, DOM and Pull.

There are many elements in the web.xml file. Here is given some necessary elements to run the simple
servlet program.

web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>

Description of the elements of web.xml file


There are too many elements in the web.xml file. Here is the illustration of some elements that is used in
the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.

5)Start the Server and deploy the project


To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.
5 |M.sc sem I OOPs USING JAVA

One Time Configuration for Apache Tomcat Server


You need to perform 2 tasks:

1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).


2. Change the port number of tomcat (optional). It is required if another server is running on same port (8080).

1) How to set JAVA_HOME in environment variable?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on the new
tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable
value -> ok -> ok -> ok.

Go to My Computer properties:

Click on advanced system settings tab then environment variables:

Click on the new tab of user variable or system variable:

Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:

There must not be semicolon (;) at the end of the path.

After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.

Note: There are two types of tomcat available:

1. Apache tomcat that needs to extract only (no need to install)


2. Apache tomcat that needs to install

It is the example of apache tomcat that needs to extract only.

Now server is started successfully.

2) How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same system with same
port number.Suppose you have installed oracle, you need to change the port number of apache tomcat
because both have the default port number 8080.

Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change the
Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it by
9999 and save this file.
6 |M.sc sem I OOPs USING JAVA

5) How to deploy the servlet project


Copy the project and paste it in the webapps folder under apache tomcat.

But there are several ways to deploy the project. They are as follows:

o By copying the context(project) folder into the webapps directory


o By copying the war folder into the webapps directory
o By selecting the folder path from the server
o By selecting the war file from the server

Here, we are using the first approach.

You can also create war file, and paste it inside the webapps directory. To do so, you need to use jar tool
to create the war file. Go inside the project directory (before the WEB-INF), then write:.

(2) Installing Glassfish Plugin for Eclipse


Installing Glassfish tools

First of all, follow the following steps to install Eclipse Glassfish Tools plugin into Eclipse IDE.

1. Open Eclipse Marketplace from Help-> Eclipse Marketplace menu.


2. Type Glassfish in the search box to filter Glassfish plugins.
3. In the search result, find Glassfish tools , click the Install button to install it.
4. After it is installed, restart Eclipse IDE to apply the plugin.

Next let’s create a Glassfish Server instance.

Adding a Glassfish Server instance

If the Servers view is not opened, try to open it first. Click Windows->Show Views -
> Servers from Eclipse main menu.

Alternatively try to open the Java EE Perspective, click Windows-> Perspective->Open


Perspective-> Other… from the main menu, and find the Java EE perspective in the
popup Perspective window, it will open a series of views for this perspective, including
the Servers view.

In the Servers view, right click on the blank area, select New->Server in the context menu. It
starts a New Server wizard to set up a server instance.

In the New Server wizard, the first step is Define a New Server, select Glassfish in the server
type tree, and click Next button.

In the Glassfish runtime properties step, you can name the server instance, select the Glassfish
location from local machine, and choose a JDK 8 to run Glassfish, click Next button.
7 |M.sc sem I OOPs USING JAVA

In the Glassfish Application Server properties step, it allows you to setup domain info and the
administration properties, let’s use the default values, click Finish button.

There is a new node will be appeared in the Servers view.

It is easy to control the application server in the Servers view, such as start, stop, restart, deploy
and undeploy, etc.

Start and Stop Glassfish Server

Right click the Glassfish node, and select Start to start Glassfish server. After it is started
successfully, under the Glassfish node, it will include the resources in the Glassfish server.

To stop Glassfish Server, just click Stop in the context menu, or select Glassfish node, and click
the stop button in the toolbar of the Servers view.

Deploy and undeploy applications

Ok, let’s try to run our sample application on the Glassish server.

In the Project or Packages view, right click the project node, and click Run As…-> Run on
Server in the context menu.

In the Run on Server dialog, select Glassfish, and click Finish button. Wait for seconds, it will
build, package and deploy the application into Glassfish server.

When it is done, you will see there is a Deployed Applications under the Glassfish node in
the Servers view. Expand this node, there is a jakartaee8-starter node, it is our application
running on the Glassfish server.

(3) creating servlet with Eclipse


Creating Servlet Example in Eclipse
Eclipse is an open-source ide for developing JavaSE and JavaEE (J2EE) applications. You can download the
eclipse ide from the eclipse website http://www.eclipse.org/downloads/.

You need to download the eclipse ide for JavaEE developers.

Creating servlet example in eclipse ide, saves a lot of work to be done. It is easy and simple to create a
servlet example. Let's see the steps, you need to follow to create the first servlet example.

o Create a Dynamic web project


o create a servlet
o add servlet-api.jar file
o Run the servlet
8 |M.sc sem I OOPs USING JAVA

1) Create the dynamic web project:


For creating a dynamic web project click on File Menu -> New -> Project..-> Web -> dynamic web
project -> write your project name e.g. first -> Finish.

2) Create the servlet in eclipse IDE:


For creating a servlet, explore the project by clicking the + icon -> explore the Java Resources -> right
click on src -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all the checkboxes
except doGet() -> next -> Finish.

3) add jar file in eclipse IDE:


For adding a jar file, right click on your project -> Build Path -> Configure Build Path -> click on Libraries tab
in Java Build Path -> click on Add External JARs button -> select the servlet-api.jar file under tomcat/lib ->
ok.

4) Start the server and deploy the project:


For starting the server and deploying the project in one step, Right click on your project -> Run As ->
Run on Server -> choose tomcat server -> next -> addAll -> finish.

Now tomcat server has been started and project is deployed. To access the servlet write the url pattern
name in the URL bar of the browser. In this case Hello then enter.

How to configure tomcat server in Eclipse ? (One time Requirement)


If you are using Eclipse IDE first time, you need to configure the tomcat server First.

For configuring the tomcat server in eclipse IDE, click on servers tab at the bottom side of the IDE ->
right click on blank area -> New -> Servers -> choose tomcat then its version -> next -> click on
Browse button -> select the apache tomcat root folder previous to bin -> next -> addAll -> Finish.

***Creating Servlet in myeclipse IDE


You need to follow the following steps to create the servlet in the myeclipse IDE. The steps are as follows:

o Create a web project


o create a html file
o create a servlet
o start myeclipse tomcat server and deploy project

1) Create the web project:


9 |M.sc sem I OOPs USING JAVA

For creating a web project click on File Menu -> New -> web project -> write your project name e.g. first -> Finish.

2) Create the html file:


As you can see that a project is created named first. Now let's explore this project.

For creating a html file, right click on WebRoot -> New -> html -> write your html file name e.g. MyHtml.html ->
Finish.

3) Create the servlet:


For creating a servlet click on File Menu -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all the
checkboxes except doGet() -> next -> Finish.

As you can see that a servlet file is created named Hello.java. Now let's write the servlet code here.

Now let's make the MyHtml.html file as the default page of our project. For this, open web.xml file and change the
welcome file name as MyHtml.html in place of index.jsp.

Now change the welcome file as MyHtml.html in place of index.jsp.

4) Start the server and deploy the project:


For starting the server and deploying the project in one step Right click on your project -> Run As -> MyEclipse
server application.

The default port of myeclipse tomcat is 8080, if you have installed oracle on your system, the port no. will conflict
so let's first change the port number of myeclipse tomcat server. For changing the port number click on the start
server icon at the left hand side of browser icon -> myeclipse tomcat -> Configure server connector -> change the
port number as 8888 in place of 8080 -> apply -> ok.

Now change the port number as 8888 in place of 8080 -> apply -> ok.

Now port number have been changed. For starting the server Right click on your project -> Run As -> MyEclipse
server application.

As you can see that default page of your project is open, write your name -> go.

(4) Browser-servtet Data Flow


The servlet processes the incoming data and orchestrates a response by generating
content. Once the content is generated, the servlet creates a response page, usually by forwarding the content to
a JSP. The response is sent back to the client, which sets up the next user interaction.
10 |M.sc sem I OOPs USING JAVA

Servlet Data Flow

When a user clicks a Submit button, information entered in a display page is sent to a servlet. The
servlet processes the incoming data and orchestrates a response by generating content. Once the
content is generated, the servlet creates a response page, usually by forwarding the content to a JSP.
The response is sent back to the client, which sets up the next user interaction.

The following illustration shows the information flow to and from the servlet.

To show the servlet data flow

1. The servlet processes the client request.


2. The servlet generates content.
3. The servlet creates a response and either:
a. Sends it back directly to the client

- or -

b. Dispatches the task to a JSP

The servlet remains in memory, available to process another request.

Figure 2–1 Servlet Data Flow Steps

URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We
can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from
another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value
pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter
value.
11 |M.sc sem I OOPs USING JAVA

Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser independent).


2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information.

Example of using URL Rewriting


In this example, we are maintaning the state of the user using link. For this purpose, we are appending the
name of the user in the query string and getting the value from the query string in another page.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
12 |M.sc sem I OOPs USING JAVA

(5) HTTP Get and post Request


HTTP Requests
The request sent by the computer to a web server, contains all sorts of potentially interesting information;
it is known as HTTP requests.

The HTTP client sends the request to the server in the form of request message which includes following
information:

o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header

The HTTP request method indicates the method to be performed on the resource identified by
the Requested URI (Uniform Resource Identifier). This method is case-sensitive and should be used in
uppercase.

The HTTP request methods are:

HTTP Description
Request

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with extra info sent with
the request.

HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.


13 |M.sc sem I OOPs USING JAVA

OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond

Get vs. Post


There are many differences between the Get and Post request. Let's see these differences:

GET POST

1) In case of Get request, only limited amount of data can In case of post request, large amount of data can
be sent because data is sent in header. be sent because data is sent in body.

2) Get request is not secured because data is exposed in Post request is secured because data is not
URL bar. exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second request will Post request is non-idempotent.
be ignored until response of first request is delivered

5) Get request is more efficient and used more than Post. Post request is less efficient and used less than
get.

***GET and POST***


Two common methods for the request-response between a server and client are:

o GET- It requests the data from a specified resource


o POST- It submits the processed data to a specified resource

Anatomy of Get Request


The query string (name/value pairs) is sent inside the URL of a GET request:

1. GET/RegisterDao.jsp?name1=value1&name2=value2

As we know that data is sent in request header in case of get request. It is the default request type. Let's

see what information is sent to the server.


14 |M.sc sem I OOPs USING JAVA

Some other features of GET requests are:

o It remains in the browser history


o It can be bookmarked
o It can be cached
o It have length restrictions
o It should never be used when dealing with sensitive data
o It should only be used for retrieving the data

Anatomy of Post Request


The query string (name/value pairs) is sent in HTTP message body for a POST request:

1. POST/RegisterDao.jsp HTTP/1.1
2. Host: www. javatpoint.com
3. name1=value1&name2=value2

As we know, in case of post request original data is sent in message body. Let's see how information is
passed to the server in case of post request.
15 |M.sc sem I OOPs USING JAVA

Some other features of POST requests are:

o This requests cannot be bookmarked


o This requests have no restrictions on length of data
o This requests are never cached
o This requests do not retain in the browser history

(6) cookies
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.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie with response
from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user,
cookie is added with request by default. Thus, we recognize the user as the old user.
16 |M.sc sem I OOPs USING JAVA

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.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.


17 |M.sc sem I OOPs USING JAVA

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot be changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They
are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in


response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from
the browser.

How to create Cookie?


Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
18 |M.sc sem I OOPs USING JAVA

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.

1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing it in another servlet.
As we know well that session corresponds to the particular user. So if you access it from too many browsers
with different values, you will get the different value.

index.html

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
19 |M.sc sem I OOPs USING JAVA

3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }

(7) server-side http session


In this section, we will talk about server-side attacks. Server-side attacks don't require user
interaction. These attacks can be used with the web servers. We can also use them against a normal
computer that people use every day. To do these attacks, we are going to be targeting our Metasploitable
device. The reason why we are going to be using it against our Melasploitable device is that if our target
uses a personal computer, and if they are not on the same network as us, then even if we manage to get
their IP address, their IP address is going to be behind a router. They will probably be connecting through
a router, and therefore, if we use the IP to try and determine what applications are installed and what
operating system run on it, we will not get much useful information because we are only going to be
getting information about the router and not about the person. The person will be hiding behind the router.

When we are targeting a web server, then the server will have an IP address, and we can access that IP
address directly on the internet. This attack will work if the person has a real IP and if the person is on the
same network. If we can ping the person, even if it's a personal computer, then we can run all of the attacks
and all of the information-gathering methods that we're going to learn about.
20 |M.sc sem I OOPs USING JAVA

We are going to be targeting our Metasploitable device. Before we start working on it, we will just check
the network settings. Just to verify it, it is set to NAT, and it is on the same network as the Kali machine.
This Kali machine is going to be our attacking machine. If we do ifconfig on the Metasploitable machine,
we will be able to see the IP address of it as shown in the following screenshot:

In the above screenshot, we can see that 10.0.2.4 is the IP of Metasploitable device. Now, if we go to Kali
machine, we should be able to ping it. In the following screenshot, we can see that when we ping on the
IP, we are getting responses back from the machine. Now, we can try and test its security as shown with

the next screenshot:

Again, we can use these attacks and these approaches against any computer that we can ping. Server-side
attacks work against a normal computer, websites, web servers, people, as long as we can ping them. Just
to convey this idea, we will see the Metasploitable machine. It is just a normal virtual machine that we can
use right here to do anything we want. Using the -ls command, we can list it, and we can even install a
graphical interface. Then we will be able to use it in the way we use in Kali machine. But it has a web server.
If we try to navigate to the server, we will see that it has websites that we can actually read and browse.
We're going to have a look at these websites and see how we can pen test them in the later chapters as
we can see in the following screenshot:

is a computer, and if we can ping the IP, we can use server-side attacks. These attacks mostly work against
server because server always has real IPs. If the person is in the same network as we are, then we can ping
them to do all of these attacks as well

**Http Session **
In such case, container creates a session id for each user.The container uses this id to identify the particular
user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.
21 |M.sc sem I OOPs USING JAVA

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this request, or if the request
does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this
request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface

1. public String getId():Returns a string containing the unique identifier value.


2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this
session, as the number of milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession


In this example, we are setting the attribute in the session scope in one servlet and getting that value from
the session scope in another servlet. To set the attribute in the session scope, we have used the
setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute
method.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
22 |M.sc sem I OOPs USING JAVA

9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. HttpSession session=request.getSession();
18. session.setAttribute("uname",n);
19.
20. out.print("<a href='servlet2'>visit</a>");
21.
22. out.close();
23.
24. }catch(Exception e){System.out.println(e);}
25. }
26.
27. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. HttpSession session=request.getSession(false);
14. String n=(String)session.getAttribute("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
23 |M.sc sem I OOPs USING JAVA

20. }
21.
22.
23. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

(8) Declarations
When we encounter declarations, we need to lay out storage for the declared variables.

For every local name in a procedure, we create a ST(Symbol Table) entry containing:

1. The type of the name


2. How much storage the name requires

The production:
24 |M.sc sem I OOPs USING JAVA

1. D → integer, id
2. D → real, id
3. D → D1, id

A suitable transition scheme for declarations would be:

Production rule Semantic action

D → integer, id ENTER (id.PLACE, integer)


D.ATTR = integer

D → real, id ENTER (id.PLACE, real)


D.ATTR = real

D → D1, id ENTER (id.PLACE, D1.ATTR)


D.ATTR = D1.ATTR

ENTER is used to make the entry into symbol table and ATTR is used to trace the data type.

***Expressions****

Expressions
An expression is a formula in which operands are linked to each other by the use of operators to compute
a value. An operand can be a function reference, a variable, an array element or a constant.

Let's see an example:

1. a-b;

In the above expression, minus character (-) is an operator, and a, and b are the two operands.

There are four types of expressions exist in

o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
25 |M.sc sem I OOPs USING JAVA

Each type of expression takes certain types of operands and uses a specific set of operators. Evaluation of
a particular expression produces a specific value.

For example:

1. x = 9/2 + a-b;

The entire above line is a statement, not an expression. The portion after the equal is an expression.

Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic operators. An arithmetic
expression computes a value of type int, float or double.

When an expression contains only integral operands, then it is known as pure integer expression when it
contains only real operands, it is known as pure real expression, and when it contains both integral and
real operands, it is known as mixed mode expression.

Evaluation of Arithmetic Expressions

The expressions are evaluated by performing one operation at a time. The precedence and associativity of
operators decide the order of the evaluation of individual operations.

When individual operations are performed, the following cases can be happened:

o When both the operands are of type integer, then arithmetic will be performed, and the result of the
operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the result of the operation
would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed arithmetic will be
performed. In this case, the first operand is converted into a real operand, and then arithmetic is performed
26 |M.sc sem I OOPs USING JAVA

to produce the real value. For example, 6/2.0 will yield 3.0 as the first value of 6 is converted into 6.0 and then
arithmetic is performed to produce 3.0.

Let's understand through an example.

6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.

6*2/8 + 8 * 2 8 is divided by 4, giving value 2.

12/8 +8 * 2 6 is multiplied by 2, giving value 12.

1+8*2 12 is divided by 8, giving value 1.

1 + 16 8 is multiplied by 2, giving value 16.

17 1 is added to 16, giving value 17.

Relational Expressions
o A relational expression is an expression used to compare two operands.
o It is a condition which is used to decide whether the action should be taken or not.
o In relational expressions, a numeric value cannot be compared with the string value.
o The result of the relational expression can be either zero or non-zero value. Here, the zero value is equivalent
to a false and non-zero value is equivalent to true.

Relational Description
Expression

x%2 = = 0 This condition is used to check whether the x is an even number or not. The relational
expression results in value 1 if x is an even number otherwise results in value 0.
27 |M.sc sem I OOPs USING JAVA

a!=b It is used to check whether a is not equal to b. This relational expression results in 1 if a is
not equal to b otherwise 0.

a+b = = x+y It is used to check whether the expression "a+b" is equal to the expression "x+y".

a>=9 It is used to check whether the value of a is greater than or equal to 9.

Let's see a simple example:

1. #include <stdio.h>
2. int main()
3. {
4.
5. int x=4;
6. if(x%2==0)
7. {
8. printf("The number x is even");
9. }
10. else
11. printf("The number x is not even");
12. return 0;
13. }

Output

Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero value.
o It is a complex test condition to take a decision.

Let's see some example of the logical expressions.

Logical Description
Expressions

( x > 4 ) && ( x < 6 It is a test condition to check whether the x is greater than 4 and x is less than 6. The result
) of the condition is true only when both the conditions are true.

x > 10 || y <11 It is a test condition used to check whether x is greater than 10 or y is less than 11. The
result of the test condition is true if either of the conditions holds true value.
28 |M.sc sem I OOPs USING JAVA

! ( x > 10 ) && ( y = It is a test condition used to check whether x is not greater than 10 and y is equal to 2. The
=2) result of the condition is true if both the conditions are true.

Let's see a simple program of "&&" operator.

1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 10;
6. if ( (x <10) && (y>5))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }

Output

Let's see a simple example of "| |" operator

1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 9;
6. if ( (x <6) || (y>10))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }

Output

Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
29 |M.sc sem I OOPs USING JAVA

o A conditional operator is also known as a ternary operator.

The Syntax of Conditional operator

Suppose exp1, exp2 and exp3 are three expressions.

exp1 ? exp2 : exp3

The above expression is a conditional expression which is evaluated on the basis of the value of the exp1
expression. If the condition of the expression exp1 holds true, then the final conditional expression is
represented by exp2 otherwise represented by exp3.

Let's understand through a simple example.

1. #include<stdio.h>
2. #include<string.h>
3. int main()
4. {
5. int age = 25;
6. char status;
7. status = (age>22) ? 'M': 'U';
8. if(status == 'M')
9. printf("Married");
10. else
11. printf("Unmarried");
12. return 0;
13. }

Output

**JSTL (JSP Standard Tag Library)**

The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.

Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.
30 |M.sc sem I OOPs USING JAVA

JSTL Tags
There JSTL mainly provides five types of tags:

Tag Name Description

Core tags The JSTL core tag provide variable support, URL management, flow control, etc. The URL for the
core tag is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c.

Function The functions tags provide support for string manipulation and string length. The URL for the
tags functions tags is http://java.sun.com/jsp/jstl/functions and prefix is fn.

Formatting The Formatting tags provide support for message formatting, number and date formatting, etc.
tags The URL for the Formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

XML tags The XML tags provide flow control, transformation, etc. The URL for the XML tags
is http://java.sun.com/jsp/jstl/xml and prefix is x.

SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.

For creating JSTL application, you need to load the jstl.jar file.

JSTL Core Tags


The JSTL core tag provides variable support, URL management, flow control etc. The syntax used for
including JSTL core library in your JSP is:

JSTL Core Tags List


Tags Description

c:out It display the result of an expression, similar to the way <%=...%> tag work.

c:import It Retrives relative or an absolute URL and display the contents to either a String in
'var',a Reader in 'varReader' or the page.

c:set It sets the result of an expression under evaluation in a 'scope' variable.

c:remove It is used for removing the specified scoped variable from a particular scope.
31 |M.sc sem I OOPs USING JAVA

c:catch It is used for Catches any Throwable exceptions that occurs in the body.

c:if It is conditional tag used for testing the condition and display the body content only if
the expression evaluates is true.

c:choose, c:when, It is the simple conditional tag that includes its body content if the evaluated condition
c:otherwise is true.

c:forEach It is the basic iteration tag. It repeats the nested body content for fixed number of times
or over collection.

c:forTokens It iterates over tokens which is separated by the supplied delimeters.

c:param It adds a parameter in a containing 'import' tag's URL.

c:redirect It redirects the browser to a new URL and supports the context-relative URLs.

c:url It creates a URL with optional query parameters.

**JDK: Java Development Kit


JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop java applications and applets. It physically exists. It contains JRE +
development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) etc. to
complete the development of a Java Application.
32 |M.sc sem I OOPs USING JAVA

Components of JDK
Following is a list of primary components of JDK:

appletviewer: This tool is used to run and debug Java applets without a web browser.

apt: It is an annotation-processing tool.

extcheck: it is a utility that detects JAR file conflicts.

idlj: An IDL-to-Java compiler. This utility generates Java bindings from a given Java IDL file.

jabswitch: It is a Java Access Bridge. Exposes assistive technologies on Microsoft Windows systems.

java: The loader for Java applications. This tool is an interpreter and can interpret the class files
generated by the javac compiler. Now a single launcher is used for both development and
deployment. The old deployment launcher, jre, no longer comes with Sun JDK, and instead it
has been replaced by this new java loader.

javac: It specifies the Java compiler, which converts source code into Java bytecode.

javadoc: The documentation generator, which automatically generates documentation from source
code comments

jar: The specifies the archiver, which packages related class libraries into a single JAR file. This tool
also helps manage JAR files.

javafxpackager: It is a tool to package and sign JavaFX applications.

jarsigner: the jar signing and verification tool.

javah: the C header and stub generator, used to write native methods.

javap: the class file disassembler.

javaws: the Java Web Start launcher for JNLP applications.

JConsole: Java Monitoring and Management Console.

jdb: the debugger.


33 |M.sc sem I OOPs USING JAVA

jhat: Java Heap Analysis Tool (experimental).

jinfo: This utility gets configuration information from a running Java process or crash dump.

jmap: Oracle jmap - Memory Map- This utility outputs the memory map for Java and can print shared
object memory maps or heap memory details of a given process or core dump.

jmc: Java Mission Control

jps: Java Virtual Machine Process Status Tool lists the instrumented HotSpot Java Virtual Machines
(JVMs) on the target system.

jrunscript: Java command-line script shell.

jstack: It is a utility that prints Java stack traces of Java threads (experimental).

jstat: Java Virtual Machine statistics monitoring tool (experimental).

jstatd: jstat daemon (experimental).

keytool: It is a tool for manipulating the keystore.

pack200: JAR compression tool.

Policytool: It specifies the policy creation and management tool, which can determine policy for a Java
runtime, specifying which permissions are available for code from various sources.

VisualVM: It is a visual tool integrating several command-line JDK tools and lightweight [clarification
needed] performance and memory profiling capabilities

wsimport: It generates portable JAX-WS artifacts for invoking a web service.

xjc: It is the part of the Java API for XML Binding (JAXB) API. It accepts an XML schema and
generates Java classes.

You might also like