You are on page 1of 20

Advanced Java

Name: Abhishek S. Beloshe

Seat Number: 18-9603


Class: S.Y. Bsc CS
Roll No: 03
Subject: Advanced Java

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

Que-1: Write a servlet code that accepts user-name and car name. It should return a
Welcome message and price of car.

Ans –

Program:

NewServlet2.java -

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NewServlet2 extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

String user=request.getParameter("usr");

String Car=request.getParameter("car");

out.println("Welcome: " +user+ "<br>");

out.println("Car: "+Car+"<br>");

if(Car.equals("BMW"))

out.println("Price of Car: 25,00,000");

if(Car.equals("SUZUKI"))

out.println("Price of Car: 5,00,000");

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

if(Car.equals("FERRARI"))

out.println("Price of Car: 35,00,000");

if(Car.equals("LAMBORGHINI"))

out.println("Price of Car: 85,00,000");

if(Car.equals("MERCEDES"))

out.println("Price of Car: 65,00,000");

}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

return "Short description";


}

cars.html-

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form id="Form1" method="post" action="NewServlet2">
Name <input type="text" name="usr" > <br> <br>
Car <select name="car" ><br><br>
<option>BMW</option>
<option>SUZUKI</option>
<option>FERRARI</option>
<option>LAMBORGHINI</option>
<option>MERCEDES</option>
</select> <br> <br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Output:

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

Que-2: Explain the types of JDBC Driver.

Ans –
JDBC Driver :
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.

For example, using JDBC drivers enable you to open database connections and to interact with
it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementations are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.

JDBC Drivers Types:


JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below –

Type 1: JDBC - ODBC Bridge Driver

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when no
other alternative is available.

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC - Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.

If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: Java Network Protocol Driver

In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4: Java Database Protocol driver (Pure)

In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

Que-3: Write a servlet that accept user name and password sent from a html file. If the
password equals “admin” the servlet redirects the output of welcome.html or if the
password is wrong then it redirects the output of error.html file.

Ans-

Program:

NewServlet1.java -

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NewServlet1 extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {

String name = request.getParameter("user");

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

String pass = request.getParameter("pas");

if(name.equals("User") && pass.equals("admin"))


{
request.getRequestDispatcher("welcome.html").include(request,response);
}
else
{
request.getRequestDispatcher("error.html").include(request,response);
}
} finally {
out.close();
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}

login.html -

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

<form id="form1" method="post" action="NewServlet1">

UserName <input type="text" name="user"><br><br>

Password <Input type="password" name="pas"><br><br>

<input type="submit" value="submit">

</form>
</body>
</html>

welcome.html -

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Logged In Successfully</h1>
</body>
</html>

error.html -

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Invalid details</h1>
</body>
</html>

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

Output:

Que-4: Explain the life cycle of JSP.


Ans –
The key to understanding the low-level functionality of JSP is to understand the simple life
cycle they follow.

A JSP life cycle is defined as the process from its creation till the destruction. This is similar to
a servlet life cycle with an additional step which is required to compile a JSP into servlet.

The following are the paths followed by a JSP −


 Compilation
 Initialization
 Execution
 Cleanup

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four
phases have been described below −

1) JSP Compilation

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile
the page. If the page has never been compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.

The compilation process involves three steps −

 Parsing the JSP.


 Turning the JSP into a servlet.
 Compiling the servlet.

2) JSP Initialization

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If
you need to perform JSP-specific initialization, override the jspInit() method –

public void jspInit(){

// Initialization code...

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

Typically, initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the jspInit
method.

3) JSP Execution

This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its
parameters as follows –

void _jspService(HttpServletRequest request, HttpServletResponse response) {

// Service handling code...

The _jspService() method of a JSP is invoked on request basis. This is responsible for
generating the response for that request and this method is also responsible for generating
responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.

4) JSP Cleanup

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by
a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or
closing open files.

The jspDestroy() method has the following form –

public void jspDestroy() {


// Your cleanup code goes here.
}

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

Que-5: What is session tracking? How cookies are helpful in session tracking.
Ans –
Session Tracking:
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each
time user requests to the server, server treats the request as the new request. So we need to
maintain the state of an user to recognize to particular user.

The servlet can maintain a session in different ways as:

1. Cookies.
2. Hidden Form Field.
3. URL Rewriting.
4. HttpSession.

Cookies:

Cookies is named value pair of information, sent by the server to the client browser that gets
saved at the client computer which can be used for session tracking.

Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. Java Servlets transparently supports HTTP cookies.

There are three steps involved in identifying returning users −


 Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.

Servlet Cookies Methods:


Following is the list of useful methods which you can use while manipulating cookies in servlet.

Sr.No. Method & Description

public void setDomain(String pattern)


1 This method sets the domain to which cookie applies, for example
tutorialspoint.com.

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

public String getDomain()


2 This method gets the domain to which cookie applies, for example
tutorialspoint.com.

public void setMaxAge(int expiry)


3 This method sets how much time (in seconds) should elapse before the cookie
expires. If you don't set this, the cookie will last only for the current session.

public int getMaxAge()


4 This method returns the maximum age of the cookie, specified in seconds, By
default, -1 indicating the cookie will persist until browser shutdown.

public String getName()


5 This method returns the name of the cookie. The name cannot be changed after
creation.

public void setValue(String newValue)


6
This method sets the value associated with the cookie

public String getValue()


7
This method gets the value associated with the cookie.

public void setPath(String uri)


8 This method sets the path to which this cookie applies. If you don't specify a
path, the cookie is returned for all URLs in the same directory as the current page
as well as all subdirectories.

public String getPath()


9
This method gets the path to which this cookie applies.

Creating a Cookie object –


You call the Cookie constructor with a cookie name and a cookie value, both of which are
strings.
Cookie c1 = new Cookie("key","value");

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

Example:
Cookie c1 = new Cookie("user","XYZ"); //creating cookie object
response.addCookie(c1); //adding cookie in the response

Que-6: Write a note on JSON.


Ans –
JSON:

JSON is an open standard for exchanging data on the web. It supports data structures like object
and array. So it is easy to write and read data from JSON.

o JSON stands for JavaScript Object Notation.


o JSON is an open standard data-interchange format.
o JSON is lightweight and self describing.
o JSON is originated from JavaScript.
o JSON is easy to read and write.
o JSON is language independent.
o JSON supports data structures such as array and objects.
o It has been extended from the JavaScript scripting language.
o The filename extension is .json.

Uses of JSON :
 It is used while writing JavaScript based applications that includes browser extensions
and websites.
 JSON format is used for serializing and transmitting structured data over network
connection.
 It is primarily used to transmit data between a server and web applications.
 Web services and APIs use JSON format to provide public data.
 It can be used with modern programming languages.

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

Syntax:

JSON syntax is basically considered as a subset of JavaScript syntax; it includes the following −
 Data is represented in name/value pairs.
 Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs
are separated by , (comma).
 Square brackets hold arrays and values are separated by ,(comma).

Example:

{
"book": [

{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},

{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}

]
}

This is an example that shows creation of an object in javascript using JSON, save the below
code as json_object.htm –
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "XYZ", "year" : 2018 };

document.write("<h1>JSON with JavaScript example</h1>");


document.write("<br>");
document.write("<h3>Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

</script>
</head>

<body>
</body>
</html>

Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces
the following result −

JSON with JavaScript example


Name = XYZ

Year = 2018

Que-7: What are the classes required for creating Menu. Explain with proper example.
Ans-

The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.

The object of JMenu class is a pull down menu component which is displayed from the menu
bar. It inherits the JMenuItem class.

The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.

JPopupMenu can be dynamically popped up at a specified position within a component.

JMenuBar class declaration:


public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration:


public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration:


public class JMenuItem extends AbstractButton implements Accessible, MenuElement

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

JPopupMenu class declaration:


public class JPopupMenu extends JComponent implements MenuElement, Accessible

JMenu and JMenuItem Example:

import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}

Name: Abhishek S. Beloshe


Seat No: 18-9603
Advanced Java

Output:

Name: Abhishek S. Beloshe


Seat No: 18-9603

You might also like