0% found this document useful (0 votes)
25 views51 pages

Practical File of Advanced Java

This document is a practical file for an Advanced Java Laboratory course at Gujranwala Guru Nanak Institute of Management & Technology, covering various topics such as Servlets, JSP, Java Beans, Struts, and Hibernate. It includes detailed implementations, code examples, and assignments related to web development and SEO. The file is submitted by a student to an assistant professor and spans the period of January to May 2024.

Uploaded by

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

Practical File of Advanced Java

This document is a practical file for an Advanced Java Laboratory course at Gujranwala Guru Nanak Institute of Management & Technology, covering various topics such as Servlets, JSP, Java Beans, Struts, and Hibernate. It includes detailed implementations, code examples, and assignments related to web development and SEO. The file is submitted by a student to an assistant professor and spans the period of January to May 2024.

Uploaded by

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

PRACTICAL FILE

Of

Advanced Java Laboratory

(PGCA1922)

AT
GUJRANWALA GURU NANAK INSTITUTE OF MANAGEMENT & TECHNOLOGY

JANURAY-MAY 2024

SUBMMITED BY: SUBMMITED TO:

PRANAV SHARMA Prof. CHARANJEET SINGH

Roll no: 2309950 (Assistant Professor)

Class: MCA 2 (Department of Computer Applications)

GUJRANWALA GURU NANAK INSTITUTE OF MANAGEMENT

AND

TECHNOLOGY CIVIL LINES LUDHIANA

GGNIMT|1
INDEX
Sr.
No. Title Page No
Create a Servlet to handle HTTP Requests and
1. 3-4
Responses.

Implementation of the concept of Cookies and 5-8


2.
Session Tracking.
Illustrate the concept of Java Server Pages 9
3.
(JSP).
Create a Java Bean by using Bean Developer 10
4.
Kit (BDK).
Implementation of various types of beans like 11-13
5.
Session Bean and Entity Bean.
Introduction to Struts platform with basic 14-18
6.
connectivity.
Deploying first sample program using MVC 19-21
7.
architecture in struts.
8. Implementing database connectivity in struts. 22-23

9. Creating one sample application in struts. 24-25

10. Introduction to Hibernate framework. 26-27

11. Creating simple Hibernate application. 28-32

Practical Assignments (SEO)


Take a web site and prepare the SEO report of
the website including status of following
factors:
12. Title tag, meta-description tag, header tags, 33
keyword consistency, number of back links,
robots.txt and xml sitemaps then after going
through the steps of SEO prepare the report.
Discuss any five tools to prepare the list of ten 34-40
13.
organic key words for SEO purpose.
Optimize the images in the website using
14. suitable methods and compare the reports 41-49
before and after the SEO steps.

Write the robot and sitemap file of a website 50-51


15.
under consideration.

GGNIMT|2
1. Create a Servlet to handle HTTP Requests and Responses

HTML File

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<form action="inp">

Enter first number:<input type="text" name="num1"><br> Enter Second number:<input type="text"


name="num2"><br>

<input type="submit">

</form>

</body>

</html>

Servl.java

import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import


jakarta.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import


java.io.IOException;

import java.io.PrintWriter;

/*** Servlet implementation class serv1

GGNIMT|3
*/

public class serv1 extends HttpServlet

protected void service(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException

int n1=Integer.parseInt(request.getParameter("num1")); int


n2=Integer.parseInt(request.getParameter("num2")); int n3=n1+n2;

PrintWriter pw=response.getWriter(); pw.println("Addition of 2 numbers is " +n3);

Output

GGNIMT|4
2. Implementation of the concept of Cookies and Session Tracking.

Index.html

<!DOCTYPE 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>

<center>

<form method=”post” action=”AddCookieServlet”> <B>Enter a value for MyCookie: </B> <input


type=”text” name=”data” size=”25″>

<input type=”submit” value=”Submit”>

</form>

</center>

</body>

</html>

OUTPUT-

GGNIMT|5
//AddCookieServlet.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import


javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class


AddCookieServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException { response.setContentType(“text/html;charset=UTF-8”); try


(PrintWriter out = response.getWriter()) { String data=request.getParameter(“data”);

Cookie cookie=new Cookie(“MyCookie”,data);

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(“<B>My Cookie has been set to</B>”);

out.println(data);

out.println(“<br>

<a Href=’http://localhost:8088/UsingCookies/GetCookiesServlet’>To view your cookie, Click here </a>”);

out.println(“</center></body>”);

out.println(“</html>”); } }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,


IOException {
GGNIMT|6
processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException,


IOException {

processRequest(request, response);

//AddCookieServlet.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import


javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class


AddCookieServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException { response.setContentType(“text/html;charset=UTF-8”); try


(PrintWriter out = response.getWriter()) { String data=request.getParameter(“data”);

Cookie cookie=new Cookie(“MyCookie”,data);

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(“<B>My Cookie has been set to</B>”);

GGNIMT|7
out.println(data);

out.println(“<br>

<a Href=’http://localhost:8088/UsingCookies/GetCookiesServlet’>To view your cookie, Click here </a>”);

out.println(“</center></body>”);

out.println(“</html>”); } }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,


IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throwsServletException, IOException {

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).

File: AdderImplRemote.java package com.point;

import javax.ejb.Remote;

@Remote

public interface AdderImplRemote

int add(int a,int b);

File: AdderImpl.java

package com.javatpoint; import javax.ejb.Stateless;

@Stateless(mappedName="st1")

public class AdderImpl implements AdderImplRemote { public int add(int a,int b){

return a+b;

package com.javatpoint; import javax.naming.Context;

import javax.naming.InitialContext;

public class Test

public static void main(String[] args)throws Exception

Context context=new 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

public interface TestSessionBeanHome


extends javax.ejb.EJBHome
{
public examples.TestSessionBean create()
throws javax.ejb.CreateException,
java.rmi.RemoteException;

}
package examples;

public interface TestSessionBean


extends javax.ejb.EJBObject
{ public java.lang.String SayHello( )
throws java.rmi.RemoteException;

/*
* SessionBean.java
*
*/
package examples;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class MyTestSessionBean implements

SessionBean{ public void ejbCreate() throws

CreateException {

GGNIMT|11
}

public void setSessionContext(

SessionContext aContext ) throws EJBException {

public void ejbActivate() throws EJBException {

public void ejbPassivate() throws EJBException {

public void ejbRemove() throws EJBException {

public String SayHello(){

String msg="Hello! I am Session Bean"; System.out.println(msg);

return msg;

GGNIMT|12
Entity Bean

package MsgClientEJB; import javax.naming.*; import MsgServer.*; import java.util.*; public


class ClientApp {

public static void main(String[] args) {

// TODO Auto-generated method stub try{

System.out.println("Client App Started"); Properties props = new Properties();

props.put("java.naming.factory.url.pkgs","org.jboss.ejb.client.naming"); InitialContext context =


new InitialContext(props);

String appName = "";

String moduleName = "MsgFromServerEJB";

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>

<!-- Servlet API Dependency -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<version>3.1.0</version>

</dependency>

<!-- Struts2 Core Framework 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

package com.jcg.struts2.jsp; public class LinkAction {

private String user_name;

public String getUser_name() { return user_name;

public void setUser_name(String user_name) { this.user_name = user_name;

// All Struts Logic Goes In This Method

public String execute() { return "success";

Struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"


"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="default" extends="struts-default">


GGNIMT|15
<action name="Login">

<result>views/login.jsp</result>

</action>

<action name="Welcome" class="com.jcg.struts2.jsp.LinkAction">

<result name="success">views/welcomeUser.jsp</result>

</action>

</package>

</struts>

Login.jsp

<%@ page contentType="text/html; charset=UTF-8"%>

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Struts2 JSP Example</title>

</head>

<body>

<h1>Struts2 Hello World Example</h1>

<s:form action="Welcome">

<s:textfield name="user_name" label="Username" />


GGNIMT|16
<s:password name="password" label="Password" />

<s:submit />

</s:form>

</body>

</html>

welcomeUser.jsp

<%@ page contentType="text/html; charset=UTF-8"%>

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Struts2 JSP Example</title>

</head>

<body>

<h1>Struts2 Hello World Example</h1>

<h4>

Hello <s:property value="user_name"/>

</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";
}

public String getName() { return name;


}

public void setName(String name) { this.name = name;


}
}

<%@ page contentType = "text/html; charset = UTF-8" %>


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

<html>
<head>
<title>Hello World</title>
</head>

<body>
Hello World, <s:property value = "name"/>
</body>
</html>

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1" pageEncoding =


"ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<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>

<?xml version = "1.0" Encoding = "UTF-8"?>


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name = "struts.devMode" value = "true" />

<package name = "helloworld" extends = "struts-default">


<action name = "hello"
class = "com.tutorialspoint.struts2.HelloWorldAction" method = "execute">
<result name = "success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns =
"http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation =

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:

8. Implementing database connectivity in struts.


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

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>

RegisterAction.java package com.javatpoint;

public class RegisterAction {


private String name,password,email,gender,country;

//setters and getters public String execute(){


int i=RegisterDao.save(this); if(i>0){
return "success";
}
return "error";
}
}

RegisterDao.java package com.javatpoint; import java.sql.*;


public class RegisterDao {

public static int save(RegisterAction r){ int status=0;


try{
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

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();

}catch(Exception e){e.printStackTrace();} return status;


}
}

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 name="default" extends="struts-default">

<action name="register" class="com.javatpoint.RegisterAction">


<result name="success">register-success.jsp</result>
<result name="error">register-error.jsp</result>
</action>

</package>
</struts>

register-success.jsp
9. Creating one sample application in struts.

index.jsp

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

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;

public class Product {


private int id;
private String name;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}

GGNIMT|24
public void setPrice(float price) {
this.price = price;
}

public String execute(){


return "success";
}
}

OUTPUT-

10.introduction to Hibernate framework.

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.

Advantages of Hibernate Framework

Following are the advantages of hibernate framework:

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.

3) Database Independent Query

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.

4) Automatic Table Creation

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.

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status

Hibernate supports Query cache and provide statistics about query and database status.

11. Creating simple Hibernate application.

package com.javatpoint.mypackage;

GGNIMT|27
public class Employee {

private int id;

private String firstName,lastName;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {

return lastName;

public void setLastName(String lastName) {

this.lastName = lastName; }

employee.hbm.xml

GGNIMT|28
<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 5.3//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">

<hibernate-mapping>

<class name="com.javatpoint.mypackage.Employee" table="emp1000">

<id name="id">

<generator class="assigned"></generator>

</id>

<property name="firstName"></property>

<property name="lastName"></property>

</class>

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 5.3//EN"

"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;

public class StoreData {

public static void main(String[] args) {

GGNIMT|30
//Create typesafe ServiceRegistry object

StandardServiceRegistry ssr = new


StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory = meta.getSessionFactoryBuilder().build();

Session session = factory.openSession();

Transaction t = session.beginTransaction();

Employee e1=new Employee();

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.

The free version of AnswerThePublic is a great resource for bloggers. However if


you perform keyword search on a regular basis, then you’ll need their pro plan.

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.

That’s why I highly recommend compressing your images before uploading to


your site. You can do this in Photoshop or you can use a tool like TinyPNG.

TingPNG also has a WordPress plugin you can use too.

However, I prefer WP Smush as my WordPress plugin. It reduces the image


file size without removing the quality.

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.

Increasingly.com improved website speed by 33%/2 seconds by compressing images.

If you’re unsure how your images are affecting your page speed, I recommend
using Google’s PageSpeed Insights tool.

2. Create Unique Images

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.

I’m sure you’ve seen one that looks like this:

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.

Keep in mind that large images are more likely to be featured in

Google Discover. As Google recommends in its Advanced SEO

resource,

“Large images need to be at least1200 pxwide and enabled by the max-image-


preview:large setting, or by using AMP.”

Do not use your logo as the image.

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.

If Getty, Shutterstock, DepositFiles, or some other stock photo provider owns an


image you use, and you don’t have a license to use it, then you’re risking an
expensive lawsuit.

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.

4. Customize Image File Names

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.

Let’s pretend you have an image of chocolate for example.

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.

5. Write SEO-Friendly Alt Text

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.

The alt text could read:

<img src=”chocolate-1.jpg” alt=”chocolate”/>

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.

6. Think About The Image File Structure

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.

Repeat:The file path and file name is an actual ranking factor.

For example, if you’re an ecommerce brand with multiple products, instead of


placing all your product images into a generic /media/ folder, I would
recommend structuring your subfolders to more category related topics like
/shorts/ or /denim/.

7. Optimize Your Page Title & Description

Google also revealed that it uses your page title and description as part of its
image search algorithm.

The Google support page states:

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.

8. Define Your Dimensions

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.

Image dimension attributes are also important for preventing Cumulative


Layout Shift (CLS) issues that can interfere with your Core Web Vitals
optimization.

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.

9. Make Your Images Mobile-Friendly

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.

Problem is, how do you optimize your images for the

mobile-first index? Luckily, Google offers guidance on best

practices for images.

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

Empowered and driven by a software process, “crawling” is the process of


fetching web pages through a designated software, and then it is read. The
reading part is de
ployed to ensure that the content materials associated with all your online
landing pages are not copied.

Furthermore, it follows the associated thousands and thousands of links across


the network until it slithers across a huge number of connections and sites. This
Crawling process is known as spidering.

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

Empowered and driven by a software process, indexing is the process to index


the content of a website and then placed in an algorithmic-depository system (via
cloud system of Search engine), so that it can be easily filtered and searched by
online searchers through platforms like Google, Yahoo and Bing.

Sitemaps & Robots

It may seem that as we further progress in time, the complexity of


technologies can sometimes be inevitable, and sometimes comprehensible with
ease.

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.

Sitemaps are configured in two categories;

A) XML – which is used for major search engines

B) HTML – which is used for its audiences / users / searchers

What is a Robots.txt file?

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

You might also like