Practical File of Advanced Java
Practical File of Advanced Java
Of
(PGCA1922)
AT
GUJRANWALA GURU NANAK INSTITUTE OF MANAGEMENT & TECHNOLOGY
JANURAY-MAY 2024
AND
GGNIMT|1
INDEX
Sr.
No. Title Page No
Create a Servlet to handle HTTP Requests and
1. 3-4
Responses.
GGNIMT|2
1. Create a Servlet to handle HTTP Requests and Responses
HTML File
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<form action="inp">
<input type="submit">
</form>
</body>
</html>
Servl.java
import java.io.PrintWriter;
GGNIMT|3
*/
Output
GGNIMT|4
2. Implementation of the concept of Cookies and Session Tracking.
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
</head>
<body>
<center>
</form>
</center>
</body>
</html>
OUTPUT-
GGNIMT|5
//AddCookieServlet.java
import java.io.IOException;
import java.io.PrintWriter;
response.addCookie(cookie);
out.println(“<!DOCTYPE html>”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet AddCookieServlet</title>”);
out.println(“</head>”);
out.println(“<body><center>”);
out.println(data);
out.println(“<br>
out.println(“</center></body>”);
out.println(“</html>”); } }
processRequest(request, response);
//AddCookieServlet.java
import java.io.IOException;
import java.io.PrintWriter;
response.addCookie(cookie);
out.println(“<!DOCTYPE html>”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet AddCookieServlet</title>”);
out.println(“</head>”);
out.println(“<body><center>”);
GGNIMT|7
out.println(data);
out.println(“<br>
out.println(“</center></body>”);
out.println(“</html>”); } }
processRequest(request, response);
processRequest(request, response);
OUTPUT-
GGNIMT|8
3. Illustrate the concept of Java Server Pages (JSP)
<html><head><title>Very Simple JSP Example</title></head>
<body bgcolor="white">
<h1>Very Basic JSP</h1>
Current time: <%= new java.util.Date() %>
<br><br>
Reload this page to watch the greeting change.
<br><br><b>
<!-- including lines of Java code in an HTML page -->
<%
int um = (int)( Math.random() * 5 );
switch ( um )
{
case 0: out.println("Welcome"); break;
case 1: out.println("Bienvenidos"); break;
case 2: out.println("Bienvenue"); break;
case 3: out.println("Bienvenuti"); break;
case 4: out.println("Willkommen"); break;
default: out.println("Huh? " + um);
}
out.println("<br>");
%>
</b>
</body>
</html>
OUTPUT-
GGNIMT|9
4. Create a Java Bean by using Bean Developer Kit (BDK).
import javax.ejb.Remote;
@Remote
File: AdderImpl.java
@Stateless(mappedName="st1")
public class AdderImpl implements AdderImplRemote { public int add(int a,int b){
return a+b;
import javax.naming.InitialContext;
AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");
System.out.println(remote.add(32,32));
Output: 64
GGNIMT|10
5. Implementation of various types of beans like Session Bean and Entity Bean
}
package examples;
/*
* SessionBean.java
*
*/
package examples;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
CreateException {
GGNIMT|11
}
return msg;
GGNIMT|12
Entity Bean
GGNIMT|13
6. Introduction to Struts platform with basic connectivity
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-
v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Struts2Jsp</groupId>
<artifactId>Struts2Jsp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.24.1</version>
</dependency>
</dependencies>
<build>
GGNIMT|14
<finalName>${project.artifactId}</finalName>
</build>
</project>
LinkAction.java
Struts.xml
<struts>
<result>views/login.jsp</result>
</action>
<result name="success">views/welcomeUser.jsp</result>
</action>
</package>
</struts>
Login.jsp
<html>
<head>
</head>
<body>
<s:form action="Welcome">
<s:submit />
</s:form>
</body>
</html>
welcomeUser.jsp
<html>
<head>
</head>
<body>
<h4>
</h4>
</body>
</html>
OUTPUT-
GGNIMT|17
7. Deploying first sample program using MVC architecture in struts.
package com.tutorialspoint.struts2; public class HelloWorldAction {
private String name;
GGNIMT|18
public String execute() throws Exception { return "success";
}
<html>
<head>
<title>Hello World</title>
</head>
<body>
Hello World, <s:property value = "name"/>
</body>
</html>
<html>
GGNIMT|19
head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World From Struts2</h1>
<form action = "hello">
<label for = "name">Please enter your name</label><br/>
<input type = "text" name = "name"/>
<input type = "submit" value = "Say Hello"/>
</form>
</body>
</html>
<struts>
<constant name = "struts.devMode" value = "true" />
GGNIMT|20
"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.Filte
rDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Output:
GGNIMT|21
<s:form action="register">
<s:textfield name="name" label="UserName"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:textfield name="email" label="Email"></s:textfield>
<s:radio list="{'male','female'}" name="gender"></s:radio>
<s:select cssStyle="width:155px;"list="{'india','pakistan','other',}" name="country"
label="Country"></s:select>
<s:submit value="register"></s:submit>
</s:form>
GGNIMT|22
PreparedStatement ps=con.prepareStatement("insert into strutsuser values(?,?,?,?,?)");
ps.setString(1,r.getName());
ps.setString(2,r.getPassword()); ps.setString(3,r.getEmail()); ps.setString(4,r.getGender());
ps.setString(5,r.getCountry());
status=ps.executeUpdate();
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD
Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
</package>
</struts>
register-success.jsp
9. Creating one sample application in struts.
index.jsp
GGNIMT|23
2. <s:form action="product">
3. <s:textfield name="id" label="Product Id"></s:textfield>
4. <s:textfield name="name" label="Product Name"></s:textfield>
5. <s:textfield name="price" label="Product Price"></s:textfield>
6. <s:submit value="save"></s:submit>
7. </s:form>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Product.java
package com.javatpoint;
GGNIMT|24
public void setPrice(float price) {
this.price = price;
}
OUTPUT-
Hibernate
GGNIMT|25
This hibernate tutorial provides in-depth concepts of Hibernate Framework with simplified
examples. It was started in 2001 by Gavin King as an alternative to EJB2 style entity bean.
Hibernate Framework
Hibernate is a Java framework that simplifies the development of Java application to interact
with the database. It is an open source, lightweight, ORM (Object Relational Mapping) tool.
Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.
What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain functionality and standard
to ORM tools. The javax.persistence package contains the JPA classes and interfaces.
GGNIMT|26
1) Open Source and Lightweight
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in hibernate
framework. There are two types of cache in hibernate framework first level cache and second
level cache. First level cache is enabled by default.
HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries. Before
Hibernate, if database is changed for the project, we need to change the SQL query as well that
leads to the maintenance problem.
Hibernate framework provides the facility to create the tables of the database automatically. So
there is no need to create tables in the database manually.
Hibernate supports Query cache and provide statistics about query and database status.
package com.javatpoint.mypackage;
GGNIMT|27
public class Employee {
return id;
this.id = id;
return firstName;
this.firstName = firstName;
return lastName;
this.lastName = lastName; }
employee.hbm.xml
GGNIMT|28
<?xml version='1.0' encoding='UTF-8'?>
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
hibernate.cfg.xml
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
GGNIMT|29
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
GGNIMT|30
//Create typesafe ServiceRegistry object
Transaction t = session.beginTransaction();
e1.setId(101);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
GGNIMT|31
GGNIMT|32
12. Take a web site and prepare the SEO report of the website including status of
following factors: Title tag, meta-description tag, header tags, keyword consistency,
number of back links, robots.txt and xml sitemaps then after going through the
steps of SEO prepare the report.
For non-sensitive information, block unwanted crawling by using robots.txt
A robots.txt file tells search engines whether they can access and therefore
crawl parts of your site. This file, which must be named robots.txt, is placed in
the root directory of your site. It is possible that pages blocked by robots.txt can
still be crawled, so for sensitive pages, use a more secure method.
# brandonsbaseballcards.com/robots.txt
# Tell Google not to crawl any URLs in the shopping cart or images in the icons
folder, # because they won't be useful in Google Search results.
User-agent: googlebot Disallow: /checkout/ Disallow: /icons/
You may not want certain pages of your site crawled because they might not be
useful to users if found in a search engine's search results. If you do want to
prevent search engines from crawling your pages, Google Search Console has a
friendly robots.txt generator to help you create this file. Note that if your site
uses subdomains and you wish to have certain pages not crawled on a particular
subdomain, you'll have to create a separate robots.txt file for that subdomain.
For more information on robots.txt, we suggest this guide on using robots.txt
files.
Read about several other ways to prevent content from appearing in search
results. Avoid:
Letting your internal search result pages be crawled by Google. Users dislike
clicking a search engine result only to land on another search result page on your
site.
Allowing URLs created as a result of proxy services to be crawled. For sensitive
information, use more secure methods
A robots.txt file is not an appropriate or effective way of blocking sensitive or
confidential material. It only instructs well-behaved crawlers that the pages are not
for them, but it does not prevent your server from delivering those pages to a browser
that requests them. One reason is that search engines could still reference the URLs
you block (showing just the URL, no title link or snippet) if there happen to be links to
those URLs somewhere on the Internet (like referrer logs). Also, non-compliant or
rogue search engines that don't acknowledge the Robots Exclusion Standard could
disobey the instructions of your robots.txt. Finally, a curious user could examine the
directories or subdirectories in your robots.txt file and guess the URL of the content .
13.Discuss any five tools to prepare the list of ten organic key words for SEO
GGNIMT|33
purpose
SEO purpose.
1. SEMrush
SEMrush is a complete SEO tool suite to carry out keyword research and
improve your SEO rankings.
Using theKeyword Overviewtool, you can type in a keyword and get a full
picture of everything you need to know. This includes how many people search
for the keyword (monthly search volume), whether it’s growing in popularity
or becoming less popular (the Trend), and much more.
After scrolling down, you can also see a handy list of other similar keywords you
might want to use, along with a list of organic search results, so you can find out
GGNIMT|34
for the keyword. You can also check out Google Ads that use that keyword in
PPC advertising (pay-per-click ads).
You can also type in any competitor’s website in the Domain Overview to
see their organic search terms, keyword data, and other organic traffic metrics.
If you click on the Organic Research tab, you’ll be able to see relevant
keywords, your competitor’s search engine ranking positions (serps), the traffic
value (cpc), and more.
All the top marketers in the world rate SEMRush as the #1 keyword research
tool. Their full suite of tools can help you with content marketing, digital
marketing, social media, and more.
2. AnswerThePublic
GGNIMT|35
AnswerThePublic works a bit differently from most other keyword research tools.
They present keywords in a nice visual format although you can also see them in
a list or download a .csv file of results.
If you’re just getting started with SEO and keyword research, then this is a great
tool to try, because you don’t even need to create an account to use it. Just type
in your keyword and take a look at what comes up.
GGNIMT|36
The keyword results from AnswerThePublic are based on Google and Bing’s
auto-suggest / autocomplete features. You can click on any of these keywords to
search for it in Google, and it’ll open up in a new tab.
This will show what content is ranking for those terms and whether there’s a
featured snippet on it.
GGNIMT|37
3. Ubersuggest
Ubersuggest is a free tool from Neil Patel that offers search volume data,
keyword suggestions, an idea of how difficult your keyword will be to rank for
(keyword difficulty), and more.
As well as seeing lots of suggestions for related keywords, you can view a table of
the top 100 Google results for that keyword, with estimated visits, number of
backlinks, a domain score, and a total number of social shares.
Under Content Ideas, it also shows content related to your keyword, listing
estimated monthly visits, backlinks, and number of shares on Facebook and
Pinterest.
GGNIMT|38
If you sign into Ubersuggest with your Google account, then you’ll be able to get
more keyword suggestions, daily rank tracking, and personalized SEO
suggestions. UberSuggest also comes with a Chrome extension that can help
you improve your workflow.
4. Ahrefs
Ahrefs is another popular keyword research tool that offers similar features to
SEMrush. Using Ahrefs keyword explorer, you can come up with keyword ideas
simply by typing a keyword into the search box. You’ll then see a whole list of
keyword suggestions.
GGNIMT|39
You can also use Ahrefs to see the keywords that your competitors are
ranking for (but that you’re not), so you can create new content pieces
targeting keywords related to those subjects.
Another nice competitive intelligence functionality that Ahrefs offer is the ability to
see new keywords, and keyword movements in search queries.
Both SEMrush and Ahrefs offer a bunch of other useful tools too, like reports
that find broken links on your site, ppc keywords for adwords, and more.
GGNIMT|40
14. Optimize the images in the website using suitable methods and compare the
reports before and after the SEO steps.
1. Choose The Right Format
Decoding all the various image formats can feel like your first time ordering at
Taco Bell. But, before you can start adding images to your site, you want to
make sure you’ve chosen the best file type.
While there are many image formats to choose from, the PNG and JPEG are the
most common for the web.
PNG: Produces better quality images, but comes with a larger file size.
JPEG: You may lose image quality, but you can adjust the quality level to find a
good balance.
WebP: Choose lossless or lossy compression using this, the only image format
supported by both Chrome and Firefox.
For me, PNG is the unsung hero of image formatting. But, for my daily use, PNG
is the way to go then convert those into WebP.
Just be careful if you’re using .jpg images inside an inline SVG format as Google’s
systems can’t index these.
GGNIMT|41
1. Compress Your Images
Yep, hell hath no fury like a bloated web page after uploading an image that’s not
compressed.
Search engines will look at your web page like you might look at a big vat of
Crisco: You can’t seriously be considering putting that on your website, right?
According to HTTP Archive, images makeup on average 21% of a total webpage’s weight.
Whatever plugin you use, make sure to find one that compresses the images
externally on their servers. It reduces the load on your own site.
Or, take it a step further and use an image CDN that detects the device and
optimizes the image prior to delivery. Cloudinary and Imgix are two options to try
out.
If you’re unsure how your images are affecting your page speed, I recommend
using Google’s PageSpeed Insights tool.
You want your photos to pop on your site. If you fill your website with stock
imagery, you’ll look unoriginal – like thousands of other sites that don’t stand out.
Too many websites are cluttered with the same generic stock photos.
Think about a corporate website, a consulting firm, a business that prides itself
GGNIMT|42
on customer service. All these websites use virtually the same looking stock image
of a businessman smiling.
While you may have your stock images perfectly optimized, it won’t have the
same impact or potential SEO benefits as an original, high-quality image.
The more original pictures you have, the better experience for the user and the
better your odds are of ranking on relevant searches.
resource,
GGNIMT|43
3. Beware Of Copyright
Regardless of the image files you choose to use, make sure there’s no copyright conflict.
The Postal Service is paying $3.5 million in an image copyright lawsuit. And,
Skechers got sued for $2.5 million.
Under the Digital Millennium Copyright Act (DMCA), you could be issued a notice
if you have violated any copyright issues. If the owner of a piece of content sees
their content on your website, they can issue a DMCA Takedown which you
must comply with.
Google Images allows you to filter results based on those available for reuse, and
Mindy Weinstein shares 41 different websites to find free images.
When it comes to SEO, creating descriptive, keyword-rich file names is absolutely crucial.
Not customizing your image file name is like getting a burrito with nothing in it. It
just plain sucks.
Image file names alert Google and other search engine crawlers as to the subject
matter of the image.
GGNIMT|44
Typically, file names will look like “IMG_722019” or something similar. That’s
like ordering from a menu in a different language. It doesn’t help Google.
Change the file name from the default to help the search engines
understand your image and improve your SEO value.
This involves a bit of work, depending on how extensive your media library is,
but changing the default image name is always a good idea.
I could name it simply “chocolate” but if you sell chocolate on your website,
potentially every image can be named “chocolate-1,” “chocolate-2,” and so on.
I named this image “dark-chocolate-coffee” to let users and search engines understand
the image.
Alt tags are a text alternative to images when a browser can’t properly render
them. Similar to the title, the alt attribute is used to describe the contents of an
image file.
GGNIMT|45
When the image won’t load, you’ll get an image box with the alt tag
present in the top left corner. Make sure they fit with the image and make the
picture relevant.
Paying attention to alt tags is also beneficial to the overall on-page SEO strategy.
You want to make sure that all other optimization areas are in place, but if the
image fails to load for any reason, users will see what the image is supposed to
be.
Plus, adding appropriate alt tags to the images on your website can help your
website achieve better rankings in the search engines by associating keywords
with images. Even Google has remarked on the value of alt text in images.
It provides Google with useful information about the subject matter of the image.
We use this information to help determine the best image to return for a user’s
query.
Alt text is required under the American Disabilities Act for individuals who are
unable to view images themselves. A descriptive alt text can alert users exactly
what is in the photo. For example, say you have a picture of chocolate on your
website.
However, a better alternative text that describes the image would read
GGNIMT|46
<img src=”chocolate-1.jpg” alt=”dark chocolate coffee flavored bar”/>
Alt text is viewable in the cached text version of the page, aiding in its benefit
to both users and the search engines. For further SEO value, the alt text can
act as the anchor text of an internal link when the image links to a different
page on the site.
Google updated its Image Guidelines. One of the major updates they revealed
was that they use the file path and file name to rank images.
Google also revealed that it uses your page title and description as part of its
image search algorithm.
GGNIMT|47
All of your basic on-page SEO factors like meta data, header tags, copy on the
page, structured data, etc. affects the way Google ranks your images.
It’s like putting all your toppings on your burrito. It tastes way better with guac.
So, make sure to add the guac for improving image rankings.
If you’re using AMP or PWAs, you are required to define your image
dimensions in the source code.
However, if you’re not using either, it’s still a best practice to define the
width and height. It provides a better user experience.
GGNIMT|48
Plus, it allows the browsers to size the image before the CSS is loaded. This stops
the page from jumping when it loads.
Making sure that you include width and height attributes for every image and
video element is key.
This tells the browser how much space to allocate for the resource and prevents
that annoying content-shifting that lowers your CLS score. Learn more here.
Oh, mobile SEO. At its worst, it can give you a high bounce rate and low
conversions. But, at its best, it can give you more ranking power and better user
engagement.
In short, you want to create responsive images. This means the image will scale
with the size of the site whether the user is using desktop or mobile. It adjusts to
the size of the device.
Mozilla offers a comprehensive guide on using the srcset and sizes attributes to
provide the browser additional source images, enabling the display of identical
image content resized for the device.
It is important to format this with a different part of the attribute value on each
line, as demonstrated in this example from their resource:
<img srcset=”elva-fairy-
GGNIMT|49
15. Write the robot and sitemap file of a website under consideration.
Crawling
Subsequent to a landing site, before it is “spidered”, the quest crawler will search
for a robots.txt document. If it discovers one, the crawler will peruse that record
first before proceeding through the page.
Since the robots.txt record contains data about how the web index should be
administered, the data discovered there will train further crawler activity on this
specific website.
On the off chance that the robots.txt record doesn’t contain any orders that forbid a
client operator’s action (or if the site doesn’t have a robots.txt document), it will
continue to slither other data on the site.
Indexing
GGNIMT|50
Nevertheless, understanding the verticals of how these technologies play a role over your
website can not only help you in terms of preserving and solidifying a particular brand, but it
also creates a vital channel for your site to be shown to potential buyers who may not
even search for services, solution or product What is a Sitemap?
Specifically speaking, sitemaps are designed to enable Google and other major search
engines to exceptionally crawl your site. The purpose of this is to provide the
search engine crawlers with such a company site’s content.
Robots.txt have specific jobs. They are singularly responsible for creating (coded)
scripts with instructions to control web robots on how to crawl pages for websites.
GGNIMT|51