0% found this document useful (0 votes)
8 views16 pages

See Answers

The document provides an overview of Java Server Pages (JSP), servlets, and object-oriented programming concepts. It details JSP directives, servlet life cycle, exception handling, JDBC drivers, and various programming examples including method overriding and overloading. Additionally, it discusses the benefits of JSP and the structure of servlets, along with the importance of response headers in servlets.

Uploaded by

white Devil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views16 pages

See Answers

The document provides an overview of Java Server Pages (JSP), servlets, and object-oriented programming concepts. It details JSP directives, servlet life cycle, exception handling, JDBC drivers, and various programming examples including method overriding and overloading. Additionally, it discusses the benefits of JSP and the structure of servlets, along with the importance of response headers in servlets.

Uploaded by

white Devil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 16

The JSP page Directive:

Three types of directives: page, include, and taglib.


-page directive:
Control the structure of the servlet by importing classes, customizing the servlet
superclass, setting the content type
Can be placed anywhere within the document
case-sensitive attributes: import, contentType, isThreadSafe, session, buffer,
autoflush, extends, info, errorPage, isErrorPage, and language.
-include:
insert a file into the servlet class at the time the JSP file is translated into a
servlet
should be placed in the document at the point at which the file is to be inserted
-taglib:
used to define custom markup tags
===================================================================================
==============
Benefits of JSP:
*JSP technically can do anything that servlets do.
*The process of making JavaServer Pages accessible on the Web is much simpler than
that for servlets
*Separates the (Java) code that creates the content from the (HTML) code that
presents it.
===================================================================================
===
The Servlet Life Cycle:
*init method: put one-time setup code.
*service method: each user request results in a thread that calls the service
method of the previously created instance.
-Multiple concurrent requests normally result in multiple threads calling service
simultaneously
-The service method then calls doGet, doPost, or another doXxx method
*destroy method: when the server decides to unload a servlet
===================================================================================
========
Reading Request Headers from Servlets:
-Accept,
-Accept-Encoding,
-Connection,
-Cookie,
-Host,
-Referer, and
-User-Agen
===================================================================================
====
Steps To Execute An SQL Statement And
Get Data From Database
• Load the driver (Only performed once)
• Obtain a Connection to the database (Save for later use)
• Obtain a Statement object from the Connection
• Use the Statement object to execute SQL.
• Selects return a ResultSet
• Updates, inserts and deletes return Boolean.
• Navigate ResultSet, using data as required
• Close ResultSet
• Close Statement
===================================================================================
====
what is object oriented programming? outline java buzzwords in details.
answer1:
What is object-oriented programming?
Object-oriented programming (OOP) is a programming paradigm that uses "objects" to
design software.
An object is a data structure that contains data and methods to work on that data.
In OOP, computer
programs are designed by making them out of objects that interact with one another.

What are the Java buzzwords?


-Java buzzwords are terms or concepts that are often used in Java-related
discussions, programming
tutorials, or job postings. Some of the common Java buzzwords are:

-Class: A class is a blueprint for creating objects (a specific data structure),


providing initial
values for state (member variables or attributes), and implementations of behavior
(member functions
or methods).

-Object: An object is an instance of a class. It contains member variables that


hold the state of
the object and member functions that define the behavior of the object.

-Inheritance: Inheritance is one of the four fundamental OOP concepts, where a


class can inherit the
properties and behaviors of another class. It promotes the reuse of code and
prevents the redundancy
of code.

-Encapsulation: Encapsulation is the hiding of data or details of an underlying


implementation. In
Java, encapsulation can be achieved by declaring variables as private and
providing public getter
and setter methods.

-Polymorphism: Polymorphism allows methods to be used across classes if they share


the same method
signature. It simplifies the code and reduces complexity.
===================================================================================
==========================
what is overriding? Demonstrate the method overriding with simple java program.
answer2:

Overriding is a mechanism that allows a subclass to provide a different


implementation of a method
that is already provided by its superclass.

In Java, the override keyword is not necessary. If a subclass has the same method
signature as the
superclass, then it is assumed to be overriding.

Here is a simple Java program that demonstrates method overriding:


class Animal {
void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
myAnimal.makeSound();
myDog.makeSound();
}
}
===================================================================================
=====================
what are exceptions? Explain the keyword to handle the exception in java.
answer3:
Exceptions are events that occur during the execution of a program, which disrupt
the normal flow of
instructions. In Java, exceptions can occur in various ways such as errors made by
the programmer,
exceptions in the code being executed, and system failures like running out of
memory.

To handle these exceptions, Java provides a mechanism using keywords like try,
catch, finally, and throw.

-try: The code block in which an exception can occur is enclosed in the try block.

-catch: This block is used to catch the exceptions that occur in the try block. The
catch block is used
after the try block and is used to catch exceptions of different types.

-finally: The finally block is executed whether an exception is caught or not. This
block is optional.

-throw: The throw keyword is used to throw an exception explicitly.

For example, here's how you can handle exceptions using the keywords:

public class ExceptionHandling {


public static void main(String[] args) {
try {
int num = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e);
} finally {
System.out.println("This block will be executed no matter an exception
occurs or not.");
}
}
}
===================================================================================
========================
Define servlet. Outline the role of servlets along with servlet structure.
answer4:
Servlets are server-side components in a Java web application that handle requests
and generate responses.
They act as an intermediary between the client (browser) and the server, enabling
the client to interact
with the server-side resources.
Basic Servlet Structure
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletTemplate extends HttpServlet {
public void doGet(HttpServletRequest rq, HttpServletResponse rs)
throws ServletException, IOException
{
PrintWriter out = rs.getWriter();
}
}

Servlet structure consists of the following:


*Service method: The main method that the servlet container calls to handle a
request. The method can accept
any request and return any response.
*DoGet method: Handles HTTP GET requests.
*DoPost method: Handles HTTP POST requests.
*HTTPServlet class: A base class that implements the HttpServlet interface and
provides the basic support
for servlets.
*ServletConfig interface: An object that contains the configuration and
initialization parameters of the
servlet.
*ServletContext interface: An object that provides a way for the servlet to
communicate with the servlet
container and access resources in the container.

The role of servlets is to:

-Process client requests.


-Interact with server-side resources, such as databases, enterprise applications,
or other services.
-Generate dynamic responses and return them to the client.
-Support various communication protocols and data formats.
===================================================================================
=======================
What are response headers? Summarize any five methods to set the response headers
from the servlets.
answer5:
Response headers are a collection of metadata sent from the server to the client.
They provide the client
with additional information about the server's response, such as the server's
version, content type, or
length of the content.

In Java servlets, response headers can be set using the following methods:

->setHeader(String name, String value): This method sets a response header with the
specified name and value.
If the header with the specified name already exists, it overwrites the previous
value.
->addHeader(String name, String value): This method adds a response header with the
specified name and value.
If the header with the same name already exists, the new header value will be
appended to the previous value.
->setDateHeader(String name, long date): This method sets a response header with
the specified name and the
value represented by the date. The date is formatted as the number of
milliseconds since January 1, 1970, GMT.
->addDateHeader(String name, long date): This method adds a response header with
the specified name and the
value represented by the date. The date is formatted as the number of
milliseconds since January 1, 1970, GMT.
->setIntHeader(String name, int value): This method sets a response header with the
specified name and the value
represented by the integer.
===================================================================================
==============================
Define Java Server Pages(JSP) along with benefits. Also explain the scripting
elements of JSPs.
answer6:
Java Server Pages (JSP) is a technology that enables the creation of dynamic web
pages using Java code.
It provides a way to combine static HTML code with dynamic Java code to generate
HTML pages that can interact
with the client and the server.

Benefits of JSP include:

1)Java-based Technology: JSP leverages the robustness and versatility of the Java
programming language, which
has a vast community and a wide range of libraries and frameworks.

2)Platform Independence: JSP is designed to be platform-independent, allowing


developers to write code once and
deploy it on any server that supports JSP.

3)Enhanced Performance: JSP allows developers to cache portions of a web page and
include reusable components,
improving overall application performance.

4)Seamless Integration with Java EE: JSP can be used in conjunction with other Java
EE technologies, such as
servlets, EJBs, and web services, to create sophisticated, multi-tiered
applications.

5)Server-side Caching: JSP can cache generated HTML code on the server, reducing
the load on the server and
improving the response time for client requests.

Scripting elements of JSPS include:

->Scriptlet: A Java code snippet enclosed within <% and %> delimiters. Scriptlets
are used to embed Java code
within the JSP page.
->Expression: A Java expression enclosed within <%= and %> delimiters. Expressions
are used to evaluate a Java
expression and output the result to the client
->Declaration: A Java code block enclosed within <%! and %> delimiters.
Declarations are used to define global
variables, methods, and classes within the JSP page.
===================================================================================
==============================
Outline the types of JDBC drivers in details:
answer7:
JDBC Driver
• JDBC Driver is required to process SQL requests and generate result.
The following are the different types of driver available in JDBC.
• Type-1 Driver or JDBC-ODBC bridge
• Type-2 Driver or Native API Partly Java Driver
• Type-3 Driver or Network Protocol Driver
• Type-4 Driver or Thin Driver

Type 1: JDBC-ODBC Bridge Driver


Description: This driver acts as a bridge between JDBC and ODBC (Open Database
Connectivity). It uses
native ODBC drivers to connect to the database.
-Advantages:
Platform independence as ODBC drivers are available for various operating systems.
Easy to install and configure.
-Disadvantages:
Performance overhead due to the additional layer (ODBC).
Limited to systems where ODBC is available.

Type 2: Native-API Driver


Description: This driver uses a database-specific native API to communicate with
the database. It converts
JDBC calls into calls to the database-specific API.
-Advantages:
Better performance compared to Type 1.
Direct interaction with the database API.
-Disadvantages:
Database-specific, requiring different drivers for different databases.
Not entirely platform-independent.

Type 3: Network Protocol Driver (Middleware Driver)


Description: This driver uses a middleware component to translate JDBC calls into a
database-independent
network protocol. The middleware server then communicates with the database.
-Advantages:
Database independence.
The middleware component can provide additional features like connection pooling
and caching.
-Disadvantages:
Additional layer (middleware) introduces some performance overhead.
Configuration and maintenance of middleware can be complex.

Type 4: Thin or Direct-to-Database Driver


Description: This driver is a pure Java implementation that communicates directly
with the database using
a vendor-specific protocol. It doesn't require any additional native libraries or
middleware.
-Advantages:
Fully written in Java, making it platform-independent.
No client-side installation required.
Better performance compared to Type 1, 2, and 3.
-Disadvantages:
Vendor-specific, requiring a different driver for each database.
May not provide some advanced features offered by the database.
===================================================================================
===================
Model a class with the instance variables id,title,price and quantity.The objects
are instatiated with
default values and dynamic values that are read from console. Compute the total
cost of books and display
the book details:
answer8:

public class Book {


private int id;
private String title;
private double price;
private int quantity;
public Book(int id, String title, double price, int quantity) {
this.id = id;
this.title = title;
this.price = price;
this.quantity = quantity;
}
public double calculateTotalCost() {
return this.price * this.quantity;
}
public void displayBookDetails() {
System.out.println("Book ID: " + id);
System.out.println("Book Title: " + title);
System.out.println("Book Price: " + price);
System.out.println("Book Quantity: " + quantity);
System.out.println("Total Cost: " + calculateTotalCost());
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book(1, "Harry Potter", 10.0, 5);
book1.displayBookDetails();
Book book2 = new Book(2, "Outliers", 15.0, 3);
book2.displayBookDetails();
}
}
===================================================================================
========================
Construct a java program to deonstrate method overloading that computes the area of
a circle, rectangle and
triangle with three sides of triangles as input:
answer9:

public class Main {


public static void main(String[] args) {
System.out.println("Area of circle with radius 5: " + calculateArea(5));
System.out.println("Area of rectangle with length 10 and width 5: " +
calculateArea(10, 5));
System.out.println("Area of triangle with sides 3, 1 and 3: " +
calculateArea(3, 1, 3));
}
public static double calculateArea(double radius) {
return Math.PI * radius * radius;
}
public static double calculateArea(double length, double width) {
return length * width;
}
public static double calculateArea(double s1, double s2, double s3) {
double s = (s1 + s2 + s3) / 2;
return Math.sqrt(s * (s - s1) * (s - s2) * (s - s3));
}
}
===================================================================================
===================
Construct a Shape class by defining the method read and display. Define an absract
method called compute.
This class must be inherited by the rectangle class where the abstract method
compute is defined to compute
the area of rectangle
answer10:

import java.util.Scanner;
public abstract class Shape {
protected double area;
public abstract void compute();
public void read() {
Scanner s = new Scanner(System.in);
System.out.print("Enter length of the rectangle: ");
l = s.nextDouble();
System.out.print("Enter width of the rectangle: ");
w = s.nextDouble();
}
public void display() {
System.out.println("Rectangle Details:");
System.out.println("Length: " + l);
System.out.println("Width: " + w);
System.out.println("Area: " + compute());
}
}
public class Rectangle extends Shape {
private double l;
private double w;
public Rectangle() {
super();
}
public void compute() {
area = l * w;
}
}
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle(0, 0);
r.read();
r.display();
}
}

===================================================================================
=================================
Build java program that reads three numbers from command prompt. Compute the ratio
between three consicative
numbers. example read a,b,c compute a/b,b/c,c/a Handle all the runtime exceptions
for all type of exception
individually using multiple catch. Also display a message "Good Bye" at the end of
the excecution.
answer11:

import java.util.InputMismatchException;
import java.util.Scanner;
public class ConsecutiveRatioCalculator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter three consecutive numbers: ");
try {
double a = s.nextDouble();
double b = s.nextDouble();
double c = s.nextDouble();
System.out.println("The ratios are: ");
System.out.println("a / b: " + (a / b));
System.out.println("b / c: " + (b / c));
System.out.println("c / a: " + (c / a));
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid numbers.");
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception: " + e);
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e);
} finally {
System.out.println("Good bye");
}
s.close();
}
===================================================================================
=====================================================
Develop a web application with html page that reads user_name,user_id,password and
confirm_password. Read
the form data in servlet. Check if the password and confirm_password match. If
match save the user_nameas a
cookie to identify the user when he logs_in again
answer12:

index.html

<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body><h2>User Registration</h2>
<form action="RegisterServlet" method="post">
<label>Username:</label><input type="text" name="uname" required><br>
<label>User ID:</label><input type="text" name="uid" required><br>
<label>Password:</label><input type="pass" name="password" required><br>
<label>Confirm Password:</label><input type="password" name="cPass"
required><br>
<input type="submit" value="Register">
</form></body>
</html>

RegistrationServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest rq, HttpServletResponse rs)
throws ServletException, IOException {
String uname = request.getParameter("username");
String uid = rq.getParameter("userid");
String pass = rq.getParameter("password");
String cPass = rq.getParameter("confirmPassword");
PrintWriter out = rs.getWriter();
if(pass.equals(cpass)) {
Cookie c1 = new Cookie("user_name", uname);
rs.addCookie(c1);
out.println("<html><body><h2>Registration
Successful!</h2></body></html>");
} else {
out.println("<html><body><h2>Passwords do not
match!</h2></body></html>");
}
}
===================================================================================
==========================================

answer13:

<!DOCTYPE html>
<html>
<head>
<title>Image Download</title>
</head>
<body>
<h2>Image Download</h2>
<form action="DownloadImageServlet" method="get">
<label for="format">Choose Image Format:</label>
<select id="format" name="format">
<option value="png">PNG</option>
<option value="jpg">JPG</option>
</select><br>
<input type="submit" value="Download">
</form></body>
</html>

RegisterServlet.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest rq, HttpServletResponse rs)
throws ServletException, IOException {
String format = rq.getParameter("format");
rs.setContentType("image/" + format);
InputStream iStream =
getServletContext().getResourceAsStream("/WEB-INF/sample." + imageFormat);
int contentLength = iStream.available();
rs.setContentLength(contentLength);
rs.setHeader("Content-Disposition", "attachment;
filename=\"downloaded_image." + imageFormat + "\"");
OutputStream out = rs.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = iStream.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
iStream.close();
out.close();
}
}
===================================================================================
====================================
answer14:

<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<h2>Simple Calculator</h2>
<p>Current Date: <%= getCurrentDate() %></p>
<form action="CalculatorServlet" method="post">
<label>Number 1:</label><input type="text" name="num1" required><br>
<label>Number 2:</label><input type="text" name="num2" required><br>
<label>Operation:</label><select id="operation" name="operation">
<option value="add">Addition</option>
<option value="sub">Subtraction</option>
<option value="mult">Multiplication</option>
<option value="div">Division</option>
</select><br>
<input type="submit" value="Calculate">
</form>
<p>
<%
String result = (String)rq.getParameter("result");
if (result != null) {
out.println("Result: " + result);
}
String e = (String)rq.getParameter("errorMessage");
if (errorMessage != null) {
out.println("Error: " + e);
}
%>
</p></body>
</html>

CalculatorServlet.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest rq, HttpServletResponse rs)
throws ServletException, IOException {
try {
double num1 = Double.parseDouble(rq.getParameter("num1"));
double num2 = Double.parseDouble(rq.getParameter("num2"));
String operation = rq.getParameter("operation");
double result = Calculate(num1, num2, operation);
rq.setParameter("result", Double.toString(result));
} catch (NumberFormatException e) {
out.println("Invalid number format. Please enter valid numbers." +e);
} catch (ArithmeticException e) {
out.println("errorMessage", "Error: Division by zero is not allowed."
+e);
} catch (Exception e) {
out.println("errorMessage", "An unexpected error occurred." +e);
}
request.getRequestDispatcher("Calculator.jsp").forward(rq, rs);
}
private double Calculate(double num1, double num2, String operation) {
switch (operation) {
case "add":return num1 + num2;
case "sub":return num1 - num2;
case "mult":return num1 * num2;
case "div":if (num2 == 0) {
throw new ArithmeticException("Division by zero");
}
return num1 / num2;
default:throw new IllegalArgumentException("Invalid operation");
}
}
}

===================================================================================
=========================
answer15:
termwork-6
===================================================================================
===========================
answer16:
termwork-8
===================================================================================
=========================
answer17:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Employee Information</title>
</head>
<body>
<%@ page import="java.sql.*" %>
<%
String url = "jdbc:mysql://localhost:3306/employee";
String username = "root";
String password = "password";
Connection con = DriverManager.getConnection(url, username, password);
Statement stmt = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM employee");
%>
<table border="1">
<tr><th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Height</th>
<th>Basic Salary</th>
</tr>
<%
while (rs.next()) {
%>
<tr><td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("email") %></td>
<td><%= rs.getFloat("height") %></td>
<td><%= rs.getInt("basic_sal") %></td>
</tr>
<%
}
%>
</table>
<%
rs.close();
st.close();
con.close();
%>
</body>
</html>
=================================================================================
answer18a:
import java.security.Key;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class CredentialManager {
private static final String SECRET_KEY = "your-secret-key";
private static final String ALGORITHM = "AES";
public static String encrypt(String value) throws Exception {
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedValue = cipher.doFinal(value.getBytes());
return Base64.getEncoder().encodeToString(encryptedValue);
}
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedValue =
cipher.doFinal(Base64.getDecoder().decode(encryptedValue));
return new String(decryptedValue);
}
private static Key generateKey() {
return new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
}
public static void main(String[] args) {
try {
String gmailId = "[email protected]";
String password = "user_password";
String encryptedGmailId = encrypt(gmailId);
String encryptedPassword = encrypt(password);
System.out.println("Encrypted Gmail ID: " + encryptedGmailId);
System.out.println("Encrypted Password: " + encryptedPassword);
String decryptedGmailId = decrypt(encryptedGmailId);
String decryptedPassword = decrypt(encryptedPassword);
System.out.println("Decrypted Gmail ID: " + decryptedGmailId);
System.out.println("Decrypted Password: " + decryptedPassword);

} catch (Exception e) {
e.printStackTrace();
}
}
}
===================================================================================
========
answer18b:
<%@ page import="java.lang.NumberFormatException" %>
<DCOTYPE html>
<html>
<body>
<form action="performDivision.jsp" method="post">
First Number: <input type="text" name="num1" required><br>
Second Number: <input type="text" name="num2" required><br>
<input type="submit" value="Divide">
</form>
<%
try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
if (num2 == 0) {
throw new ArithmeticException("Division by Zero is not allowed");
}
double result = (double) num1 / num2;
out.println("The division result is: " + result);
} catch (NumberFormatException e) {
out.println("Error: Both inputs should be valid integers");
} catch (ArithmeticException e) {
out.println("Error: " + e.getMessage());
}
%>
</body>
<html>
===================================================================================
=========
answer19a:
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/customer";
String user = "root";
String password = "password";

try {
Connection con = DriverManager.getConnection(url, user, password);
String query1 = "CREATE TABLE orders (" +
"order_id INT AUTO_INCREMENT," +
"name VARCHAR(50)," +
"price DECIMAL(10, 2)," +
"quantity INT," +
"PRIMARY KEY (order_id)" +
")";
st = conn.createStatement();
st.execute(query1);
st.close();
String query2 = "INSERT INTO orders (name, price, quantity) VALUES
(?, ?, ?)";
st = con.createStatement(query2);
st.setString(1, "Item 1");
st.setDouble(2, 10.00);
st.setInt(3, 5);
st.executeUpdate();
st.setString(1, "Item 2");
st.setDouble(2, 20.00);
st.setInt(3, 10);
st.executeUpdate();
st.close();

String query3 = "UPDATE orders SET name = ?, price = ?, quantity = ?


WHERE order_id = ?";
st = con.createStatement(query3);
st.setString(1, "Updated Item 1");
st.setDouble(2, 15.00);
st.setInt(3, 10);
st.setInt(4, 1);
st.executeUpdate();
st.close();
st.close();
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
===================================================================================
=============================
answer19b:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CalculatorServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = res.getWriter()) {
res.setHeader("Refresh", "5");
res.setHeader("Connection", "close");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AutoRefersh</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Gold Price Variations</h1>");
out.println("<table border="1">
<tr><th>Price</th></tr>
<tr><td>4112</td></tr>
<tr><td>12121</td></tr>
<tr><td>6119</td></tr>
</table>");
out.println("</body>");
out.println("</html>");
}
}

You might also like