Advance Java Programing ASS.1,2,3,4,5
Advance Java Programing ASS.1,2,3,4,5
Advance Java Programing ASS.1,2,3,4,5
Assignments : 1,2,3,4,5
Assignment 1
Unit 1: JAVA Networking
```sh
nslookup hostname
```
For example:
```sh
nslookup google.com
```
3. Press Enter.
```java
InetAddress address =
InetAddress.getByName("192.168.1.1");
```
```java
InetAddress address =
InetAddress.getByName("www.example.com");
```
```java
```
```
3. **Checking Reachability:**
```java
```
```java
```
```java
try {
InetAddress address =
InetAddress.getByName("unknownhostname");
} catch (UnknownHostException e) {
1. **Server Side:**
```java
import java.io.*;
import java.net.*;
while (true) {
socket.receive(packet);
String fileName = new String(packet.getData(),
0, packet.getLength());
if (!file.exists()) {
continue;
int bytesRead;
packet.setData(buffer);
packet.setLength(bytesRead);
socket.send(packet);
fis.close();
System.out.println("File sent.");
} catch (IOException e) {
e.printStackTrace();
}
```
2. **Client Side:**
```java
import java.io.*;
import java.net.*;
InetAddress serverAddress =
InetAddress.getByName(SERVER_IP);
socket.send(packet);
while (true) {
socket.receive(receivedPacket);
fos.write(receivedPacket.getData(), 0,
receivedPacket.getLength());
break;
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
```
Please note that this is a basic example and does not include
error handling or advanced features. Also, UDP is not the best
choice for file transfer due to its unreliable nature. Consider
using TCP for reliable file transfer.
Q.4. What are the differences between a TCP socket and UDP
socket? How are they created in Java?
In Java, you can create TCP and UDP sockets using the
`Socket` and `DatagramSocket` classes, respectively:
**Creating TCP Socket (Client):**
```java
import java.net.*;
```
```java
import java.net.*;
```
```java
import java.net.*;
```
**Server:**
```java
import java.io.*;
import java.net.*;
ServerSocket(PORT)) {
while (true) {
String upperCaseString =
inputLine.toUpperCase();
out.println(upperCaseString);
} catch (IOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
```
**Client:**
```java
import java.io.*;
import java.net.*;
out.println(userInput);
} catch (IOException e) {
e.printStackTrace();
```
Assignment 2
Unit 2: JDBC Programming
Q.1. What is JDBC driver? Explain its role and compare various
JDBC drivers.
```java
import java.sql.*;
ResultSet resultSet =
statement.executeQuery(sql)) {
ResultSetMetaData metaData =
resultSet.getMetaData();
System.out.println("Columns:");
for (int i = 1; i <= columnCount; i++) {
String columnName =
metaData.getColumnName(i);
String columnType =
metaData.getColumnTypeName(i);
int columnDisplaySize =
metaData.getColumnDisplaySize(i);
} catch (SQLException e) {
e.printStackTrace();
```
```java
import java.sql.*;
int rowsAffected =
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
```
Q.4. What is connection URL? How do you make a database
connection? Explain various ways to make the database
connection using JDBC code snippets.
```java
import java.sql.*;
} catch (SQLException e) {
e.printStackTrace();
```
```java
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
dataSource.setUsername("username");
dataSource.setPassword("password");
} catch (SQLException e) {
e.printStackTrace();
```
```java
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
try {
DataSource ds = (DataSource)
ctx.lookup("java:comp/env/jdbc/myDataSource");
}
} catch (Exception e) {
e.printStackTrace();
```
Q.5. What is the use of Callable Statement? How will you use
it?
```java
import java.sql.*;
if (hasResults) {
while (resultSet.next()) {
System.out.println(resultSet.getString("name"));
} catch (SQLException e) {
e.printStackTrace();
```
Q.6. Discuss the use of execute(), execute Update() and
execute Query() methods.
Example:
```java
if (hasResults) {
} else {
}
```
Example:
```java
```
Example:
```java
while (resultSet.next()) {
} }```
Assignment 3
Unit 3: Servlet API and Overview
Q.1. Differentiate HTTP Get and Post methods.
1. **GET**:
2. **POST**:
1. **ServletConfig**:
2. **ServletContext**:
```xml
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.example.MyFilter</filter-class>
</filter>
```
```xml
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
```java
package com.example;
import javax.servlet.*;
import java.io.IOException;
The Servlet interface defines the methods that all servlets must
implement. A servlet's life cycle is controlled by the container in
which the servlet has been deployed, and the container invokes
life cycle methods on the servlet to handle requests from
clients.
```java
```
```
```java
```
4. **Destroy**: The `destroy()` method is called by the
container to indicate to the servlet that it is being taken out of
service. This method allows the servlet to release any resources
it is holding (such as database connections or file handles) and
erform any cleanup necessary before the servlet is destroyed.
```java
```
Ans. Cookies are small pieces of data that are sent from a
website and stored on a user's computer by the user's web
browser while the user is browsing. Cookies are commonly used to
store information such as user preferences, shopping cart
contents, and session identifiers.
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.addCookie(cookie);
// Set response content type
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
if (cookies != null) {
if (cookie.getName().equals("username")) {
name = cookie.getValue();
break;
}
// Set response content type
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
```
Q.6. What do you mean by session tracking? Discuss different
session tracking.
1. **FirstServlet**:
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.setContentType("text/html");
// Get PrintWriter
RequestDispatcher includeDispatcher =
request.getRequestDispatcher("/second");
includeDispatcher.include(request, response);
RequestDispatcher forwardDispatcher =
request.getRequestDispatcher("/second");
forwardDispatcher.forward(request, response);
// Output
out.println("<html><body>");
out.println("<h1>FirstServlet Response</h1>");
out.println("</body></html>");
```
2. **SecondServlet**:
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.setContentType("text/html");
// Get PrintWriter
// Output
out.println("<html><body>");
out.println("<h1>SecondServlet Response</h1>");
out.println("</body></html>");
```
Ans. Java Server Pages (JSP) have a well-defined life cycle that
describes how they are processed, from creation to destruction.
The JSP life cycle consists of several stages:
1. **index.jsp**:
```jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>
```
2. **included.jsp**:
```jsp
```
3. **forwarded.jsp**:
```jsp
```
In this example:
```java
return a + b;
```
```jsp
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<jsp:useBean id="calculator"
class="your_package_name.Calculator" />
</body>
</html>
```
Q.4. What is a custom tag? Explain the life cycle of tag
handler.
The life cycle of a tag handler, which is the Java class that
implements the custom tag's behavior, consists of several
stages:
```jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<%-- Page Directive: Setting response content type to HTML
--%>
<h1>Welcome to My Website!</h1>
<mytags:customTag />
</body>
</html>
```
Q.6. What are the implicit objects of JSP? Write a JSP page
to demonstrate the use them.
Ans. In JSP, there are several implicit objects that are available
to the developer without needing to be explicitly declared. These
objects provide access to various elements of the JSP
environment. Some of the commonly used implicit objects are:
```jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Implicit Objects Example</title>
</head>
<body>
</body>
</html>```
Q.7. Develop a web application as following to demonstrate the
use of <jsp:useBean>.
```java
package com.example;
return name;
this.name = name;
return age;
}
public void setAge(int age) {
this.age = age;
```
```jsp
<html>
<head>
<title>Set Student</title>
</head>
<body>
<p>Age: ${student.age}</p>
</body>
</html>
```
```jsp
<html>
<head>
<title>Get Student</title>
</head>
<body>
<h1>Student Information</h1>
</body>
</html>
```
4. **Deploy the web application:**
```xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
```
- Access
`http://localhost:8080/your-web-app-name/setStudent.jsp` to
set the student information.
- In this phase, JSF extracts the new data from the request
parameters and updates the component tree with these values.
7. **View Scope**:
- View scope allows you to store bean data for the entire
view, maintaining state across multiple requests within the same
view.
8. **Application Scope**:
```xml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<head>
</head>
<body>
<h:form>
<br/>
</h:form>
</body>
</html>
```
```java
// Bean.java
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
```
Q.3. Create a JSF custom convertor and use it in JSP page.
```java
// PersonConverter.java
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@FacesConverter("personConverter")
@Override
@Override
return null;
```
```jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h:form>
</h:form>
</body>
</html>
```
Q.4. What is JSF? List and explain its features.
1. **f:convertDateTime**:
- Example:
```xml
<h:outputText value="#{bean.date}">
</h:outputText>
```
2. **f:convertNumber**:
- Example:
```xml
<h:outputText value="#{bean.number}">
<f:convertNumber type="number"
pattern="#,##0.00" />
</h:outputText>
```
3. **f:convertEnum**:
```xml
<h:outputText value="#{bean.enumValue}">
<f:convertEnum />
</h:outputText>
```
Q.6. What is the JSF facelets? Explain any two facelets tags.
Example:
```xml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
</h:head>
<h:body>
<ui:insert name="content" />
</h:body>
</html>
```
Example:
```xml
<ui:composition
template="/WEB-INF/templates/base_template.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<ui:define name="content">
</ui:define>
</ui:composition>
```
These Facelets tags help you create modular and reusable views
for your JSF applications, making it easier to maintain and
update the user interface.
************************************************************
************************************************************