If you are looking for MCS-220 IGNOU Solved Assignment solution for the subject Web Technologies, you have come to the right place. MCS-220 solution on this page applies to 2022-23 session students studying in MCA_NEW, MCA courses of IGNOU.
MCS-220 Solved Assignment Solution by Gyaniversity
Assignment Code: MCS-220/Assignment/22-23
Course Code: MCS-220
Assignment Name: Web Technologies
Year: 2022-2023
Verification Status: Verified by Professor
Q1. What is need of design pattern? Explain use of Singleton Design Pattern with the help of an example. (10 Marks)
Ans) A design pattern provides a general reusable solution for the common problems that occur in software design. The pattern typically shows relationships and interactions between classes or objects. The idea is to speed up the development process by providing well-tested, proven development/design paradigms.
Singleton Design Pattern
Among the 23 well-known "Gang of Four" design patterns, the singleton pattern is one of the simplest used in software development. It falls within the area of creational design patterns, which is concerned with the production of an object. The singleton design pattern is used to produce a single instance of a class that can be utilised by all other classes in the application. Multi-threaded applications and database connections are the two main uses of this paradigm.
A sample implementation of Singleton design pattern in Java is as follows:
public final class Singleton
{
//A singleton class should have public visibility
//static instance of class globally accessible
private static final Singleton instance = new Singleton();
private Singleton()
{
/*private constructor, so that class cannot be instantiated from outside this class
*/
}
public static Singleton getInstance()
{
/declaration of the method as public static, so that instance can be used by other classes/
return instance;
}
}
This Singleton Design Pattern example contains two classes. One is ‘SingletonClass’, which behaves as Singleton class. This class have private constructor and provides a static method to get its static instance to other classes. The second class is SingletonExample’, which use an instance of the ‘SingletonClass’ class. The implementation of this example is underneath.
First, you can create a Singleton Class as the name of ‘SingletonClass’ using the following source code:
//SingeltonClass.java
public class SingletonClass
{
//create an object of SingletonClass
private static SingletonClass instance = new SingletonClass();
private SingletonClass(){}
public static SingletonClass getInstance()
{
return instance;
}
public void display()
{
System.out.printIn(“Hello Students in SOCIS, IGNOU);
}
}
Create another class called ‘SingletonExample’ to get the only instance from the singleton class. The code of this class is listed below:
/SingletonExample.java
public class SingletonExample
{
Public static void main (String[] args)
{
//Get the instance created by Singleton class
SingletonClass instance = SingletonClass.getInstance();
Instance.dispaly(); //display data
}
}
Now compile the both classes and run the ‘SingleExample’. The output of this example is as follows:
C: \javaclasses>javac SingletonClass.java
C: \javaclasses>javac SingletonExample.java
C: \javaclasses>javac SingletonClass
Hello Students in SOCIS, IGNOU
C: \javaclasses
Q2. (a) What is Servlet? Explain use of GET and POST methods in Servlet programming. (5 Marks)
Ans) On a web server that supports Java, a little Java programme known as a servlet runs. It extends from a Java class or interface and needs to have specific methods implemented in order for a web container or servlet container (such as Tomcat, etc.) to be able to execute your servlet. To handle requests, it just generates a class that extends either GenericServlet or HttpServlet by overriding the relevant methods. It is the responsibility of web containers to manage the web server's requests, process them, make responses, and then deliver those responses back to the web server. A web server's address space is where servlets are executed. A request-response programming style is used to access applications hosted by web servers, and servlets expand their functionality.
GET Method in Servlet Programming
To retrieve requested data from a particular server resource, utilise the GET technique. One of the most well-known and often employed HTTP request methods is GET. Data requests are the only uses for GET requests (not modify). It implies that the GET technique is used to retrieve data without altering the server in any way. These procedures are referred to as "safe" procedures.
POST Method in Servlet Programming
This technique is used in web communication to transmit information to a server so that it can create or update a resource. The request body of an HTTP request stores the data that was submitted to the server using the POST request method. Since parameters are not included with the URL, the information or data sent using the POST method won't be shown in the URL.
Q2. (b) Explain JSP and database connection using JDBC, with the help of an example code. (5 Marks)
Ans) Database access is one of the important features of Web application. Java has its own technology for database connectivity called JDBC (Java Database Connectivity). JDBC provides a standard library for accessing a wide range of relational databases like MS-Access, Oracle and Microsoft SQL Server. Using JDBC API, you can access a wide variety of different SQL databases. The core functionality of JDBC is found in java.sql package.
Consider a table named as Student is created in Microsoft SQL Server database with Roll No, Name and Course name. This table is used in both the following sections. This section defines example for storing/retrieving data into/from a Microsoft SQL Server using type-4 JDBC driver. You can run these programs on any web server such as Tomcat. For running these programs, you need a JDBC driver in .jar form and place them in lib directory under the web application.
Insert data in Database using JSP
You can see an example of how to retrieve data from the database in the example that follows. You have enough data in the database after running the aforementioned DataStoreServlet software. You will now run the code listed below to get the data out of the database. For the purpose of this programme, the data from the select query is retrieved using a separate ResultSet object. Using the getXXX() method, which accepts arguments like getInt() and getString, the data is obtained from the ResultSet object (). Remember to use the getInt() function rather than the getString() method if the column name is of the integer type. For obtaining data from a database, the RetDataServlet application is listed after that.
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RetDataServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection con = null; //create connection object
Statement stmt = null; // create statement object
ResultSet rs = null; // create ResultSet object
// connection string using Type-4 Microsoft SQL Server driver
// you can also change the next line with your own environment
String url="jdbc:microsoft:sqlserver://127.0.0.1:1433;user=sa;password=poonam;DatabaseName=SOCIS";
try
{
//load JDBC type-4 SQL Server driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager.getConnection(url);
if (con != null)
{
stmt = con.createStatement(); // select SQL statement
String rsql ="select * from Student";
rs = stmt.executeQuery(rsql); //execute query
out.println("<table border=1><tr><td>Roll Number</td><td>Student
Name</td><td>Programme</td></tr>");
while( rs.next() )
{
out.println("<tr><td>" + rs.getInt("RollNo") + "</td>");
out.println("<td>" + rs.getString("Student_Name") + "</td>");
out.println("<td>" + rs.getString("Programme") + "</td></tr>");
}
out.println("</table>");
}
if(con == null) {con.close();}
}
catch(SQLException se){ out.println("SQL:"+se.getMessage());}
catch(Exception e){ out.println("Exception:"+e.getMessage());}
}
}
Q3. What session management? Explain different ways of session management. (10 Marks)
Ans) Servlets can keep track of a number of requests from the same user thanks to session management. The four methods of managing sessions in Java Servlets are the HttpSession API, Cookies, URL rewriting, and Hidden Field.
HttpSession Object
The idea of sessions and the Session object are used by any dynamic website or web application to keep data specific to a certain user. For instance, you must provide your login name and password the first time you access any web application. During your visit to the web application, this data may be preserved in a session variable and kept available for access by the servlet container. When your session begins, the requesting browser is given a special id that uniquely identifies each client.
Cookies
Cookies only make up a small portion of data, along with attributes like name, a single value, and optional features like comment, path and domain qualifiers, a maximum age, and a version number. This cookie data is transmitted to a web browser by a servlet.
The browser stores it and then sends it back to the server. The browser likely supports 20 cookies per Web server, a total of 300 cookies, and may have a 4 KB cookie size restriction. Cookies are typically employed for session management since the value of a cookie may be utilised to uniquely identify a client. It won't function and you won't be able to use cookies to keep a session if the client disables the cookies.
In servlets, there are two different sorts of cookies: non-permanent cookies and persistent cookies. Each time a user closes their browser, a non-persistent cookie is deleted after being used for a single session. Contrarily, a persistent cookie remains in place for numerous sessions and is only deleted upon user logout.
URL Writing
Utilizing URL writing is the third method you may employ to keep user sessions active. This method embeds the token (parameter) into each URL. The token is sent back to the server when a client submits a request using one of these URLs. The server embeds an additional query parameter or additional path information into each dynamically created page. The best solution for session management in that circumstance is URL rewriting technique if a browser does not support cookies.
Hidden Fields
A token can also be given as the value of an HTML hidden field as another method for controlling user sessions. Web forms are widely used on the website. In order to keep track of the session, hidden fields will also be supplied in the request when the client submits the form. The benefit of using this strategy is that you may utilise it regardless of whether your browser allows cookies or not. It also has a drawback in that it is insecure due to the fact that anyone may access the value of the hidden form field from the HTML file and use it to hijack the session. This method's requirement for additional form submission on each page is another drawback.
Q4. Explain Java annotations (both built-in and custom). (10 Marks)
Ans) Syntactic metadata known as Java Annotations allows for the addition of more information in the source code. Packages, classes, interfaces, methods, and fields can all have annotations applied to them, but they are not considered to be a part of the programme itself and do not affect how it runs. The annotation representation looks like @ followed by the annotation name; for instance, @Entity has @ followed by the annotation name, meaning that the compiler and entity will behave as intended.
Applications for Java Annotation:
Compiler instructions: Annotations are used by the compiler to find faults or turn off warnings. The three built-in annotations @Deprecated, @Override, and @SuppressWarnings are used to provide the compiler particular instructions.
Compile-time instructors: Software tools process the metadata data before sending the compiler the compile-time directives. The software tools create the necessary XML files, code, etc.
Runtime instructions: The Runtime annotations, which give instructions to the application at runtime, are accessed using Java reflections.
Built-in Java Annotations
The built-in Java annotations used in Java code are @Override, @SuppressWarnings, and @Deprecated, whereas built-in Java annotations used in other annotations are @Target, @Retention, @Inherited, and @Documented.
A compile-time error would result from a subclass not overriding the parent class method, which is ensured by the @Override annotation. For instance, the @Override annotation, which offers the method overridden, can be used to correct any spelling issue.
Let's use an illustration to better comprehend the idea:
class ClassParent
{
public void display()
{
System.out.println("Method of Parent class");
}
}
class ClassChild extends ClassParent
{
@Override
public void display()
{
System.out.println("Method of Child class");
}
}
class Main
{
public static void main(String[] args)
{
ClassChild c1 = new ClassChild ();
c1.display();
}
}
OUTPUT: Method of Child class
Java Custom Annotations
User-defined or Java custom annotations, which are specified using @interface with the annotation name, are highly helpful in creating legible code. The method declaration forbade having any parameters and limited the use of user-defined annotations to primitives, String, Class, enums, annotations, and arrays of the aforementioned types as return types.
To generate an annotation, we need a retention rule and a goal. A retention policy specifies how long the annotation must be kept once the program's lifecycle has ended. Depending on the retention policy of the annotation, the retention of the annotation may occur at compile-time or runtime. Source, Class, and Runtime are the three types of standard retention policies.
Source: compiler discard annotations so invisible for compiler and runtime.
Class: The class file records the annotations but not retained by Java Virtual machine, so only visible by compiler.
Runtime: Annotations are recorded in the class file but are nevertheless accessible to the compiler and runtime thanks to the Java Virtual Machine.
The @Target annotation tag lists all of the methods, classes, fields, and other legal Java constructs. One or more targets may be connected to an annotation.
The annotation @Documented denotes the addition of a new annotation to a Java document.
The @Inherited annotation permits inheritance, allowing us to apply one annotation to another. Since annotation inheritance is not enabled by default, child classes of a parent class cannot use it.
Because the @Repeatable annotation is applied once by default to a Java element, it makes it easier to annotate many times.
Q5. Explain CRUD application development process using Hibernate. (10 Marks)
Ans) Follows the following steps for developing the CRUD application in hibernate annotation.
Step 1: Create Domain Entity Class
Student.java
package com.sdnext.hibernate.tutorial.dto;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Table(name="STUDENT")
public class Student implements Serializable
{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 8633415090390966715L;
@Id
@Column(name="ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="STUDENT_NAME")
private String studentName;
@Column(name="ROLL_NUMBER")
private int rollNumber;
@Column(name="COURSE")
private String course;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Step 2: Create Hibernate Configuration file
hibernate.cfg.xml
file contains
(a.) database connection setting (database driver (com.mysql.jdbc.Driver), url (jdbc:mysql://localhost:3306/hibernateDB2), username (root) and password (root)),
(b.) SQL dialect (dialect – org.hibernate.dialect.MySQLDialect),
(c.) enable hibernate’s automatic session context management (current_session_context_class – thread),
(d.) disable the second level cache (cache.provider_class – org.hibernate.cache.NoCacheProvider),
(e.) print all executed SQL to stdout (show_sql – true) and
(f.) drop and re-create the database schema on startup (hbm2ddl.auto – none).
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernateDB2</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.sdnext.hibernate.tutorial.dto.Student">
</mapping></session-factory>
</hibernate-configuration>
Step 3: Create Hibernate Utility Class
HibernateUtil.java
package com.sdnext.hibernate.tutorial.utility;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static
{
try
{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
catch(Throwable th){
System.err.println("Enitial SessionFactory creation failed"+th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
Step 4: Create Student on the database.
CreateStudent.java
package com.sdnext.hibernate.tutorial;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.sdnext.hibernate.tutorial.dto.Student;
import com.sdnext.hibernate.tutorial.utility.HibernateUtil;
public class CreateStudent {
/**
* @param args
*/
public static void main(String[] args)
{
//Create student entity object
Student = new Student();
student.setStudentName("Dinesh Rajput");
student.setRollNumber(01);
student.setCourse("MCA");
//Create session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//getting session object from session factory
Session session = sessionFactory.openSession();
//getting transaction object from session object
session.beginTransaction();
session.save(student);
System.out.println("Inserted Successfully");
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into STUDENT (COURSE, ROLL_NUMBER, STUDENT_NAME) values (?, ?, ?)
Inserted Successfully
Step 5: Reading the Student data from the database table STUDENT
ReadStudent.java
package com.sdnext.hibernate.tutorial;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.sdnext.hibernate.tutorial.dto.Student;
import com.sdnext.hibernate.tutorial.utility.HibernateUtil;
public class ReadStudent {
/**
* @param args
*/
public static void main(String[] args)
{
//Create session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//getting session object from session factory
Session session = sessionFactory.openSession();
//getting transaction object from session object
session.beginTransaction();
Query query = session.createQuery("from Student");
List students = query.list();
for(Student student : students)
{
System.out.println("Roll Number: "+student.getRollNumber()+", Student Name: "+student.getStudentName()+", Course: "+student.getCourse());
}
session.getTransaction().commit();
sessionFactory.close();
}
}
Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_, student0_.COURSE as COURSE0_, student0_.ROLL_NUMBER as ROLL3_0_, student0_.STUDENT_NAME as STUDENT4_0_ from STUDENT student0_
Roll Number: 1, Student Name: Dinesh Rajput, Course: MCA
Roll Number: 2, Student Name: Anamika Rajput, Course: PGDCP
Roll Number: 3, Student Name: Adesh Rajput, Course: MA
Roll Number: 4, Student Name: Vinesh Rajput, Course: BA
Step 6: Update the Student Record in the Database.
UpdateStudent.java
package com.sdnext.hibernate.tutorial;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.sdnext.hibernate.tutorial.dto.Student;
import com.sdnext.hibernate.tutorial.utility.HibernateUtil;
public class UpdateStudent {
/**
* @param args
*/
public static void main(String[] args)
{
//Create session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//getting session object from session factory
Session session = sessionFactory.openSession();
//getting transaction object from session object
session.beginTransaction();
Student student = (Student)session.get(Student.class, 2);
student.setStudentName("Sweety Rajput");
System.out.println("Updated Successfully");
session.getTransaction().commit();
sessionFactory.close();
}
}
Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_0_, student0_.COURSE as COURSE0_0_, student0_.ROLL_NUMBER as ROLL3_0_0_, student0_.STUDENT_NAME as STUDENT4_0_0_ from STUDENT student0_ where student0_.ID=?
Hibernate: update STUDENT set COURSE=?, ROLL_NUMBER=?, STUDENT_NAME=? where ID=?
Updated Successfully
Step 7: Delete the student data from the database.
DeleteStudent.java
package com.sdnext.hibernate.tutorial;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.sdnext.hibernate.tutorial.dto.Student;
import com.sdnext.hibernate.tutorial.utility.HibernateUtil;
public class DeleteStudent {
/**
* @param args
*/
public static void main(String[] args)
{
//Create session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//getting session object from session factory
Session session = sessionFactory.openSession();
//getting transaction object from session object
session.beginTransaction();
Student student = (Student)session.load(Student.class, 4);
session.delete(student);
System.out.println("Deleted Successfully");
session.getTransaction().commit();
sessionFactory.close();
}
}
Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_0_, student0_.COURSE as COURSE0_0_, student0_.ROLL_NUMBER as ROLL3_0_0_, student0_.STUDENT_NAME as STUDENT4_0_0_ from STUDENT student0_ where student0_.ID=?
Deleted Successfully
Hibernate: delete from STUDENT where ID=?
Q6. Explain Hibernate (ORM) Architecture. (10 Marks)
Ans) Hibernate: Hibernate is a framework which is used to develop persistence logic which is independent of Database software. In JDBC to develop persistence logic we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic which are independent of database software.
Hibernate Architecture is explained as follows:
Configuration
1) Configuration is a class which is present in org.hibernate.cfg package. It activates Hibernate framework. It reads both configuration file and mapping files.
It activate Hibernate Framework
Configuration cfg=new Configuration();
It read both cfg file and mapping files
cfg.configure();
2) It checks whether the config file is syntactically correct or not.
3) If the config file is not valid then it will throw an exception. If it is valid then it creates a meta-data in memory and returns the meta-data to object to represent the config file.
SessionFactor
SessionFactory is an Interface which is present in org.hibernate package and it is used to create Session Object.
It is immutable and thread-safe in nature.
buildSessionFactory() method gathers the meta-data which is in the cfg Object.
From cfg object it takes the JDBC information and create a JDBC Connection.
SessionFactory factory=cfg.buildSessionFactory();
Session
Session is an interface which is present in org.hibernate package. Session object is created based upon SessionFactory object i.e., factory.
It opens the Connection/Session with Database software through Hibernate Framework.
It is a light-weight object and it is not thread-safe.
Session object is used to perform CRUD operations.
Session session=factory.buildSession();
Transaction
Transaction object is used whenever we perform any operation and based upon that operation there is some change in database.
Transaction object is used to give the instruction to the database to make the changes that happen because of operation as a permanent by using commit() method.
Transaction tx=session.beginTransaction();
tx.commit();
Query
Query is an interface that present inside org.hibernate package.
A Query instance is obtained by calling Session.createQuery().
This interface exposes some extra functionality beyond that provided by Session.iterate() and Session.find():
a) A particular page of the result set may be selected by calling setMaxResults(), setFirstResult().
b) Named query parameters may be used.
Query query=session.createQuery();
Criteria
Criteria is a simplified API for retrieving entities by composing Criterion objects.
The Session is a factory for Criteria. Criterion instances are usually obtained via the factory methods on Restrictions.
Criteria criteria=session.createCriteria();
Flow of Working during Operation in Hibernate Framework
Suppose we want to insert an Object to the database. Here Object is nothing but persistence logic which we write on java program and create an object of that program. If we want to insert that object in the database or we want to retrieve the object from the database. Now the question is that how hibernate save the Object to the database or retrieve the object from the database.
Stage I: In first stage, we will write the persistence logic to perform some specific operations to the database with the help of Hibernate Configuration file and Hibernate mapping file. And after that we create an object of the particular class on which we wrote the persistence logic.
Stage II: In second stage, our class which contains the persistence logic will interact with the hibernate framework where hibernate framework gives some abstraction do perform some task. Now here the picture of java class is over. Now Hibernate is responsible to perform the persistence logic with the help of layers which is below of Hibernate framework or we can say that the layers which are the internal implementation of Hibernate.
Stage III: In third stage, our hibernate framework interact which JDBC, JNDI, JTA etc to go to the database to perform that persistence logic.
Stage IV & V: In fourth & fifth stage, hibernate is interact with Database with the help of JDBC driver. Now here hibernate perform that persistence logic which is nothing but CRUD operation. If our persistence logic is to retrieve a record then in the reverse order it will display on the console of our java program in terms of Object.
Q7. Explain Java Socket Extension (JSSE) features and benefits. (10 Marks)
Ans) Data that is in transit is open to modification or hacking by an unauthorised party. Information such as passwords, credit card numbers, and other private or crucial data that flow across the network must be rendered unreadable to unauthorised parties. While data is being transported, data integrity must be protected. Many protocols have been created to safeguard the confidentiality and integrity of data while it is in transit. Among these are the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols.
A framework for enabling secure internet connection is called the Java Secure Socket Extension (JSSE). The Secure Socket Layer (SSL) and Transport Layer Security (TLS) protocols are implemented in Java using this framework. Additionally, it offers APIs for message integrity, server authentication, data encryption, and optional client authentication.
JSSE Features and Benefits
As per the Oracle JSSE reference guide, important benefits and features of JSSE are as follows:
A fundamental part of the JDK.
It is adaptable and expandable thanks to provider-based design.
Provides classes like SSLSocket, SSLServerSocket, and SSLEngine for building secure communications.
Cypher suite negotiation is used to start or confirm secure communication.
The regular SSL/TLS/DTLS handshaking includes support for client and server authentication.
The SSL/TLS protocol encapsulates HTTP, enabling HTTPS access to online pages.
APIs for server session management.
Extension for the server name to enable secure connections to virtual servers.
Supports the Server Name Indication (SNI) Extension, which allows clients to specify the server name they are seeking to connect to during handshaking using the SSL/TLS/DTLS protocols.
By supporting endpoint identification during handshaking, prevents man-in-the-middle attacks.
Java applications can use the SSL toolkit that JSSE offers. JSSE has a convenient command-line debugging switch that you may use to observe the SSL protocol in action in addition to the necessary classes and interfaces. We can run a straightforward example with the code below in debug mode to see the handshaking specifics.
packagecom.ignou;
publicclassSecureConnection
{
publicstaticvoidmain(String[] arstring)
{
try
{
new java.net.URL("https://www.google.com").getContent();
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}
We must enable SSL debugging in order to execute the aforementioned application in debug mode. The programme uses HTTPS to establish a secure SSL connection with https://www.google.com. In the command below, the debug option forces the programme to report out its behaviour while the first option loads the HTTPS protocol handler.
java -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol-Djavax.net.debug=sslcom.ignou.SecureConnection
The simplest way to include SSL into your programmes is demonstrated by the SecureConnection programme utilising the java.net.URL class. Although this method is practical, it is not adaptable enough to let you develop a secure application that makes use of generic sockets. Server and client communications are secure thanks to SSL. To create a secure channel for communication between two devices via a network connection, SSL encrypts the data. SSL is frequently used to enable secure communication between web browsers and web servers.
Q8. (a) What is Custom Login? Explain with example. (5 Marks)
Ans) In spring security, customising the login process from creation to configuration is really simple. Like other web pages written in Java, the custom login form in Spring Application is just a straightforward html or JSP file. A custom login form enables an organisation to modify the login form according to their preferred design. It gives the developer complete flexibility over handling URLs and CSS.
Form Action URL(Custom login Controller):
packagecom.ignou.javabasedspringsecurity.controller;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value="/customlogin")
publicclassLoginController
{
@GetMapping
public String login()
{
return"customlogin";
}
}
Custom Login Form with CSS:
<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1; width: 50%; margin: auto;}
input[type=text], input[type=password]
{
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button
{
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover
{
opacity: 0.8;
}
.cancelbtn
{
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.container
{
padding: 16px;
width: 50%;
margin: auto;
}
.errormsg
{
width: 100%;
color: red;
padding: 12px 0px;
text-align: center;
}
span.psw
{
float: right;
padding-top: 16px;
}
</style>
<head>
<body>
<h2 style="text-align: center;">Spring Security Custom Login Form</h2>
<form action="/signin" method="post">
<div class="container">
<c:if test="${param.error ne null}">
<div class="errormsg"><b>Invalid
credentials</b></div>
</c:if>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<div>
<div class="container">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
</body>
</html>
The above-created login form contains the following pertinent artefacts:
Authentication is started when a form is posted to a certain URL or signed.
username is the name of the username input field.
password is the name of the password input box.
Q8. (b) Explain issues and challenges in Web Security. (5 Marks)
Ans) The issues and challenges in Web Security are as follows:
Client side code injection attacks include cross site scripting (XSS). By embedding malicious code in safe and reputable websites, the attacker launches malicious script into the victim's web browser. Attackers typically use message boards, forums, and websites that permit comments to carry out XSS. The web page becomes vulnerable to XSS when user input is used without validation in the output produced by the web page.
Cross-site request forgery, or CSRF or XSRF, is a kind of attack in which attackers deceive a victim into sending a request that makes use of their authentication or authorization. The impact of a CSRF attack is determined by the victim's level of permission.
SQL Injection flaws allow attackers to get around application security safeguards. SQL Injection can have an effect on any website or web application that uses a relational database, such as MySQL, Oracle, SQL Server, etc. Attackers can change or add user permissions, access unauthorised information, manipulate sensitive data in various ways, or even delete it using SQLi.
By overwhelming the targeted host or network with traffic until it becomes unresponsive or fails, a denial-of-service condition is created, blocking access for authorised users. A denial of service is also caused by a DoS attack, which takes use of a flaw in a software or website to force incorrect usage of its resources or network connections.
100% Verified solved assignments from ₹ 40 written in our own words so that you get the best marks!
Don't have time to write your assignment neatly? Get it written by experts and get free home delivery
Get Guidebooks and Help books to pass your exams easily. Get home delivery or download instantly!
Download IGNOU's official study material combined into a single PDF file absolutely free!
Download latest Assignment Question Papers for free in PDF format at the click of a button!
Download Previous year Question Papers for reference and Exam Preparation for free!