0% found this document useful (0 votes)
19 views45 pages

2.advanced Java Practical

The document outlines a series of assignments related to Java web development, including creating servlets, implementing cookies and session tracking, and using Java Server Pages (JSP). It also covers the Struts framework for MVC architecture and Hibernate for database connectivity. Each assignment includes code examples and explanations of key concepts in Java EE development.

Uploaded by

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

2.advanced Java Practical

The document outlines a series of assignments related to Java web development, including creating servlets, implementing cookies and session tracking, and using Java Server Pages (JSP). It also covers the Struts framework for MVC architecture and Hibernate for database connectivity. Each assignment includes code examples and explanations of key concepts in Java EE development.

Uploaded by

rajkumarece2013
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

PAGE
SL No. ASSIGNMENT
No.
01 CREATE A SERVLET TO HANDLE HTTP REQUEST AND 3-6
RESPONSES

02 CREATE A SERVLET TO HANDLE HTTP REQUEST AND 7-10


RESPONSES

03 ILLUSTRATE THE CONCEPT OF JAVA SERVER PAGE 11-12

04 IMPLEMENTATION OF VARIOUS TYPES OF BEANS 13-14


LIKE SESSION BEAN AND ENTITY BEAN

05 CREATE A JAVA BEAN BY USING BEAN DEVELPOPER 15-18


KIT

06 INTRODUCTION TO STRUTS PLATFORM WITH BASIC 19-22


CONNECTIVITY

07 DEPLOYING FIRST SAMPLE PROGRAM USING MVC 23-26


ARCHITECTURE IN STRUTS

08 IMPLEMENTING DATA BASE CONNECTIVITY IN 27-30


STRUTS

09 CREATING ONE SAMPLE APPLICATION IN STRUTS 31-34

10 INTRODUCTION TO HIBERNATE FRAMEWORK 35-38

11 CREATING SIMPLE HIBERNATE APPLICATION 39-42

13 DISCUSS ANY FIVE TOOLS TO PREPARE THE LIST OF 43-45


TEN ORGANIC KEYWORDS FOR SEO PURPOSE

1
2
ASSIGNMENT-01

CREATE A SERVLET TO HANDLE HTTP REQUEST AND


RESPONSES

3
Sample Servlet Code:
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

// Servlet mapped to URL pattern "/hello"


@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// Handles GET request


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Hello from GET method</h2>");
[Link]("</body></html>");
}

// Handles POST request


@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

String name = [Link]("name");

4
[Link]("<html><body>");

[Link]("<h2>Hello, " + name + " (from POST method)</h2>");

[Link]("</body></html>");

[Link] (Optional, if not using @WebServlet):

<web-app xmlns="[Link] version="3.1">

<servlet>

<servlet-name>HelloServlet</servlet-name>

<servlet-class>HelloServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloServlet</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>

</web-app>

5
6
ASSIGNMENT-02

IMPLEMENTAION OF THE CONCEPT OF


COOKIES AND SESSION TRACKING

7
To implement cookies and session tracking in a Java Servlet, we typically use:

 Cookies – to store data on the client's browser.


 Http Session – to store server-side session data for a user across multiple requests.

Here’s a working example that demonstrates both concepts in a simple web application.

Folder Structure (Simplified)

MyWebApp/

├── WEB-INF/

│ └── [Link] (optional)

├── [Link]

├── [Link]

├── [Link]

└── [Link]

1. [Link]

import [Link];
import [Link].*;
import [Link];
import [Link];

@WebServlet("/set-cookie")
public class SetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Cookie cookie = new Cookie("username", "JohnDoe");
[Link](60 * 60); // 1 hour
[Link](cookie);

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Cookie 'username' set to 'JohnDoe'</h2>");
}
}

8
2. [Link]

import [Link];
import [Link].*;
import [Link];
import [Link];

@WebServlet("/get-cookie")
public class GetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
Cookie[] cookies = [Link]();
String username = "Unknown";

if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals([Link]())) {
username = [Link]();
break;
}
}
}

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Username from cookie: " + username + "</h2>");
}
}

9
10
ASSIGNMENT-03

ILLUSTRATE THE CONCEPT OF JAVA SERVER


PAGE

11
What is JSP (Java Server Pages)?

Java Server Pages (JSP) is a server-side technology used to create dynamic web content by
combining HTML and Java code.

 It allows Java code to be embedded in HTML pages.


 JSP pages are compiled into servlets by the server.
 Typically used to display dynamic content like user names, database results, etc.

A basic JSP file looks like this:

<%@ page language="java" contentType="text/html" %>


<html>
<head><title>Sample JSP</title></head>
<body>
<%
// Scriptlet: Java code inside JSP
String name = "Alice";
%>
<h2>Welcome, <%= name %>!</h2> <!-- Expression: outputs value -->
</body>
</html>

Key Components of JSP:

Element Syntax Description


Directive <%@ ... %> Sets global page settings (like import)
Scriptlet <% ... %> Java code block inside JSP
Expression <%= ... %> Outputs a value to the page
Declaration <%! ... %> Declare variables or methods
Comments <%-- comment --%> JSP comment (not sent to client)

Advantages of JSP:

 Easier than writing pure Servlets for UI.


 Good separation of content and logic.
 Can use built-in objects: request, response, session, application, etc.
 Integrates well with Servlets and JavaBeans.

12
ASSIGNMENT-04

IMPLEMENTATION OF VARIOUS TYPES OF


BEANS LIKE SESSION BEAN AND ENTITY
BEAN

13
Session Beans

 Handle business logic.


 Types: Stateless, Stateful, Singleton.

1. Stateless Session Bean

 Does not maintain client state between method calls.


 Ideal for reusable, independent operations (e.g., a calculator service).

import [Link]

@Stateless

public class CalculatorBean {


public int add(int a, int b) {
return a + b;
}
}

2. Singleton Session Bean

 A single shared instance across the application.


 Ideal for caching, shared configuration, or initialization logic.

import [Link];

@Singleton

public class AppConfigBean {


private String appName = "My EJB App";

public String getAppName() {


return appName;
}
}

Entity Beans (Legacy – now replaced by JPA entities)

 Represent persistent data stored in a database.


 Replaced by Java Persistence API (JPA).

14
ASSIGNMENT-05

CREATE A JAVA BEAN BY USING BEAN


DEVELPOPER KIT

15
1. JavaBeans (Standard Java Component Model)

 A reusable software component written in Java.


 Follows a specific convention: properties, getters/setters, no-arg constructor.

2. Beam Developer Kit (Potentially refers to Apache Beam SDK)

 Apache Beam is a framework for batch and stream data processing.


 If you meant Apache Beam SDK, it's unrelated to JavaBeans.

What Is a JavaBean?

A JavaBean is a simple Java class that:

 Implements Serializable
 Has a no-argument constructor
 Provides getters and setters for accessing private properties

How to Create a JavaBean in a Java IDE

Using NetBeans / Eclipse / IntelliJ:

1. Create a new Java project.


2. Add a new class (e.g., [Link]).
3. Make sure it has:
o A no-arg constructor
o Private properties
o Public getters/setters
o Optionally implement Serializable

Example Use of JavaBean in a JSP Page

<jsp:useBean id="user" class="UserBean" scope="session" />

<jsp:setProperty name="user" property="name" value="Alice" />

<jsp:setProperty name="user" property="age" value="25" />

<p>Hello, <jsp:getProperty name="user" property="name" />!</p>

<p>Your age is: <jsp:getProperty name="user" property="age" /></p>

How to Create a JavaBean in a Java IDE

Using NetBeans / Eclipse / IntelliJ:

1. Create a new Java project.


2. Add a new class (e.g., [Link]).

16
3. Make sure it has:
o A no-arg constructor
o Private properties
o Public getters/setters
o Optionally implement Serializable

17
18
ASSIGNMENT-06

INTRODUCTION TO STRUTS PLATFORM


WITH BASIC CONNECTIVITY

19
What is Struts?

Apache Struts is a web application framework for developing Java EE web applications. It
uses the Model-View-Controller (MVC) design pattern.

There are two major versions:

 Struts 1.x – older, now end-of-life.


 Struts 2.x – modern and widely used.

Key Components of Struts

Component Description

Model JavaBeans / POJOs – business logic and data

View JSPs / HTML – presentation layer

Controller Servlet-based – handles routing and request mapping

Required Libraries (Struts 2)

Add these JARs to your WEB-INF/lib (if using manually):

 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]

Basic Struts 2 App: User Login (Example)

<%@ taglib prefix="s" uri="/struts-tags" %>


<html>
<body>
<h2>Login Page</h2>
<s:form action="login">
<s:textfield name="username" label="Username" />
<s:password name="password" label="Password" />
<s:submit value="Login" />

20
</s:form>
</body>
</html>
2. [Link]
import [Link];

public class LoginAction extends ActionSupport {


private String username;
private String password;

public String execute() {


if ("admin".equals(username) && "123".equals(password)) {
return SUCCESS;
} else {
return ERROR;
}
}

// Getters and Setters


public String getUsername() { return username; }
public void setUsername(String username) { [Link] = username; }

public String getPassword() { return password; }


public void setPassword(String password) { [Link] = password;

21
22
ASSIGNMENT-07

DEPLOYING FIRST SAMPLE PROGRAM USING


MVC ARCHITECTURE IN STRUTS

23
Let's walk through deploying your first Struts 2 program using the MVC architecture, with a simple
login example. This includes full setup, source code, and deployment on Apache Tomcat.

What You Will Build

A Struts 2 web app where:

 User enters a username and password on a login form.


 The controller (LoginAction) processes the login.
 If correct, user is redirected to [Link], else to [Link].

Project Structure (Struts 2 MVC)

StrutsLoginApp/

├── src/

│ ├── [Link]

│ ├── [Link]

├── WebContent/

│ ├── [Link]

│ ├── [Link]

│ ├── [Link]

│ └── WEB-INF/

│ ├── [Link]

│ └── lib/ (Struts JARs if not using Maven)

Step 1: [Link] (View)

<%@ taglib prefix="s" uri="/struts-tags" %>


<html>
<head><title>Login</title></head>
<body>
<h2>Login Form</h2>
<s:form action="login">
<s:textfield name="username" label="Username"/>
<s:password name="password" label="Password"/>

24
<s:submit value="Login"/>
</s:form>
</body>
</html>

Step 2: [Link] (Controller)

import [Link];

public class LoginAction extends ActionSupport {


private String username;
private String password;

public String execute() {


if ("admin".equals(username) && "123".equals(password)) {
return SUCCESS;
} else {
return ERROR;
}
}

public String getUsername() { return username; }


public void setUsername(String username) { [Link] = username; }

public String getPassword() { return password; }


public void setPassword(String password) { [Link] = password; }
}

25
26
ASSIGNMENT-08

IMPLEMENTING DATA BASE CONNECTIVITY


IN STRUTS

27
To implement database connectivity in a Struts 2 application, you’ll integrate JDBC or
JPA/Hibernate with your Struts Action class, typically during user login or data manipulation
operations.

Let’s go step-by-step to build a Struts 2 + JDBC login example.

Goal

Enhance your Struts login app to:

 Validate user credentials from a MySQL database (or any JDBC-supported DB).

Requirements

 Apache Tomcat 9+
 Struts 2 libraries
 MySQL database (or similar)
 JDBC driver (e.g., [Link])

Create a Database Table

CREATE DATABASE strutsdb;

USE strutsdb;

CREATE TABLE users (

id INT PRIMARY KEY AUTO_INCREMENT,

username VARCHAR(50),

password VARCHAR(50)

INSERT INTO users (username, password) VALUES ('admin', '123');

28
[Link] (JDBC Helper)

import [Link].*;

public class DBUtil {


public static boolean validate(String username, String password) {
boolean status = false;
try {
[Link]("[Link]");
Connection conn = [Link](
"jdbc:mysql://localhost:3306/strutsdb", "root", "your_password");

PreparedStatement ps = [Link](
"SELECT * FROM users WHERE username=? AND password=?");
[Link](1, username);
[Link](2, password);

ResultSet rs = [Link]();
status = [Link]();

[Link](); [Link](); [Link]();


} catch (Exception e) {
[Link]();
}
return status;
}
}

Deploy and Test

1. Build the project as a .war file or run from IDE.


2. Deploy on Apache Tomcat.
3. Visit: [Link]
4. Try logging in with:
o Username: admin
o Password: 123

29
30
ASSIGNMENT-09

CREATING ONE SAMPLE APPLICATION IN


STRUTS

31
Struts 2 Sample Example: "Hello User"

You’ll build a form where:

 The user enters their name.


 After submitting, the controller returns a greeting using Struts 2 action class.

<%@ taglib prefix="s" uri="/struts-tags" %>


<html>
<head><title>Struts Hello</title></head>
<body>
<h2>Enter Your Name</h2>
<s:form action="hello">
<s:textfield name="username" label="Name"/>
<s:submit value="Say Hello"/>
</s:form>
</body>
</html>
import [Link];

public class HelloAction extends ActionSupport {


private String username;

public String execute() {


return SUCCESS;
}

public String getUsername() { return username; }


public void setUsername(String username) { [Link] = username; }
}
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Hello User</title></head>
<body>
<h2>Hello, <s:property value="username" />! Welcome to Struts 2!</h2>
</body>
</html>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"

32
"[Link]

<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="HelloAction">
<result name="success">[Link]</result>
</action>
</package>
</struts>
<web-app xmlns="[Link]
version="3.1">
<filter>
<filter-name>struts2</filter-name>
<filter-class>
[Link]
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

Summary
Component Role

[Link] View (Input form)

[Link] Controller (Handles input)

[Link] View (Output response)

[Link] Action mapping configuration

[Link] Servlet/filter config

33
34
ASSIGNMENT-10

INTRODUCTION TO HIBERNATE
FRAMEWORK

35
What is Hibernate?

Hibernate is an Object-Relational Mapping (ORM) framework for Java. It simplifies the


interaction between Java objects and relational databases.

Instead of writing complex JDBC code to perform CRUD operations (Create, Read, Update,
Delete), you can use Hibernate to manage your database entities as Java objects.

Key Features of Hibernate


Feature Description

ORM (Object-Relational Mapping) Maps Java classes to DB tables and Java data types to SQL types

Automatic Table Mapping Maps objects and fields to tables and columns

HQL (Hibernate Query Language) Object-oriented query language similar to SQL

Caching First-level and second-level caching for better performance

Transaction Management Handles transactions automatically or manually

Database Independence Can switch between databases with little/no code change

Core Concepts

Concept Description

Configuration Reads settings (e.g., DB URL, username) from [Link]

SessionFactory Creates Session objects; heavy-weight object (one per DB)

Session Represents a unit of work with the database

Transaction Optional but recommended to wrap operations

Entity Class Java class mapped to a database table using annotations or XML

36
Technologies Hibernate Works With

 JDBC (under the hood)


 JPA (Hibernate is a JPA implementation)
 Spring Framework
 MySQL, Oracle, PostgreSQL, H2, and more

Advantages of Hibernate

 Eliminates boilerplate JDBC code


 Cleaner, object-oriented database access
 Portable across different databases
 Built-in connection pooling and caching
 Supports lazy loading, transactions, and complex joins

When Not to Use Hibernate

 For very simple, small apps (JDBC might be enough)


 When fine-tuned SQL performance is absolutely critical
 For non-relational (NoSQL) databases

Summary

Hibernate Is... Hibernate Is Not...

ORM tool for Java A database or a programming language

Database independent Bound to a single DB vendor

Object-centric Table-centric like SQL

37
38
ASSIGNMENT-11

CREATING SIMPLE HIBERNATE


APPLICATION

39
Goal

Create a basic Hibernate application to:

 Connect to a MySQL database


 Insert a user into the users table
 Retrieve and display user information

<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>

CREATE DATABASE hibernatedb;

USE hibernatedb;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
import [Link].*;

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = [Link])
private int id;

private String name;


private String email;

40
// Constructors
public User() {}
public User(String name, String email) {
[Link] = name;
[Link] = email;
}

// Getters and Setters


public int getId() { return id; }
public void setId(int id) { [Link] = id; }

public String getName() { return name; }


public void setName(String name) { [Link] = name; }

public String getEmail() { return email; }


public void setEmail(String email) { [Link] = email; }
}
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"[Link]
<hibernate-configuration>
<session-factory>
<!-- JDBC Properties -->
<property
name="[Link].driver_class">[Link]</property>
<property
name="[Link]">jdbc:mysql://localhost:3306/hibernatedb</property>
<property name="[Link]">root</property>
<property name="[Link]">your_password</property>

<!-- Hibernate Properties -->


<property name="[Link]">[Link]</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>

<!-- Mapping Class -->


<mapping class="User"/>
</session-factory>
</hibernate-configuration>

41
42
ASSIGNMENT-12

DISCUSS ANY FIVE TOOLS TO PREPARE THE


LIST OF TEN ORGANIC KEYWORDS FOR SEO
PURPOSE

43
To prepare a list of ten organic keywords for SEO (Search Engine Optimization), marketers
and content creators use various tools designed to research, analyze, and identify keywords
with the potential to drive organic traffic. Here are five effective tools commonly used for
this purpose:

1. Google Keyword Planner

Purpose: Originally built for Google Ads, it is also useful for organic keyword research.

Features:

 Provides keyword ideas based on seed terms or website content.


 Shows monthly search volume, competition level, and cost-per-click (CPC).
 Can filter keywords by location, language, and search network.

Why use it: It’s a free, reliable tool directly from Google with real data on search trends.

2. SEMrush

Purpose: A comprehensive SEO tool that includes keyword research, competitor analysis,
and more.

Features:

 Suggests related keywords and long-tail phrases.


 Shows keyword difficulty, search volume, trends, and CPC.
 Offers competitive analysis to identify keywords used by rivals.

Why use it: Its in-depth keyword analytics and competitor insights help refine a high-impact
keyword list.

3. Ahrefs Keywords Explorer

Purpose: A powerful SEO tool for deep keyword and backlink analysis.

Features:

 Provides keyword difficulty scores and traffic potential.


 Lists parent topics, questions, and related keywords.
 Shows how competitors rank and what keywords they use.

44
Why use it: It goes beyond simple metrics to show real ranking opportunities and topical
clusters.

4. Ubersuggest

Purpose: A user-friendly keyword research tool by Neil Patel that’s ideal for beginners.

Features:

 Offers keyword suggestions, search volume, and SEO difficulty.


 Shows top-ranking content for each keyword.
 Provides content ideas based on keyword trends.

Why use it: It’s affordable and easy to use for building keyword lists quickly and effectively.

5. Answer the Public

Purpose: Visual keyword tool that focuses on questions and prepositions around a keyword.

Features:

 Visualizes what users are asking about a keyword.


 Groups keyword queries into "what," "how," "why," etc.
 Ideal for discovering long-tail and voice-search-friendly keywords.

Why use it: It’s excellent for understanding user intent and finding content ideas based on
actual search queries.

Summary Table:
Tool Free/Paid Best For

Google Keyword Planner Free Basic keyword ideas and volumes

SEMrush Paid (Free trial) In-depth competitive keyword research

Ahrefs Paid Advanced keyword metrics and opportunities

Ubersuggest Freemium Quick and easy keyword insights

Answer the Public Freemium Content ideas based on real questions

Would you like help using one of these tools to generate your keyword list?

45

You might also like