0% found this document useful (0 votes)
9 views15 pages

MCS 220

The document covers various topics related to web technologies, including design patterns, servlets, JSP, JDBC, Struts 2, Spring Boot, and role-based login. It explains concepts like the Repository Design Pattern, differences between JAR and WAR files, servlet lifecycle, advantages of JSP over servlets, CRUD operations in SQL, and testing in Spring Boot. Additionally, it discusses the JSP Standard Tag Library and the Spring Framework, emphasizing their roles in web application development.

Uploaded by

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

MCS 220

The document covers various topics related to web technologies, including design patterns, servlets, JSP, JDBC, Struts 2, Spring Boot, and role-based login. It explains concepts like the Repository Design Pattern, differences between JAR and WAR files, servlet lifecycle, advantages of JSP over servlets, CRUD operations in SQL, and testing in Spring Boot. Additionally, it discusses the JSP Standard Tag Library and the Spring Framework, emphasizing their roles in web application development.

Uploaded by

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

Course Code : MCS-220

Course Title : Web Technologies

Q1: (a) What is need of design pattern? Explain the use of Repository Design Pattern
with the help of an example.

(b) What is the difference between JAR and WAR files? Describe the process of
creation, deployment and extraction of WAR files.

Ans :- (a) Design patterns are crucial in software development as they provide proven
solutions to recurring design problems. They promote reusability, maintainability, and
scalability by offering a standardized way of structuring code.

The Repository Design Pattern is utilized to separate the data access logic from the
business logic within an application. It centralizes all data access operations, making
it simpler to manage and update.

For example, in a web application that processes user data, we can employ the
Repository Design Pattern by creating a UserRepository class. This class would
encapsulate functions such as adding new users, fetching user details based on
specific criteria, or updating existing user information. By doing so, we avoid
scattering database operations throughout our codebase and enable seamless
switching between different storage technologies without impacting other parts of our
application.

Ans :- (b) JAR (Java Archive) files are used to package and distribute Java applications
and libraries, while WAR (Web Application Archive) files are specifically for packaging
entire web applications.

The process of creating a WAR file involves organizing the web application project
structure, including web pages, servlets/classes, configuration files, etc., and using
build tools like Maven or Gradle to package it into a WAR file.

To deploy a WAR file to an application server or servlet container:

1. Copy the generated WAR file into the deployment directory of the server/container.

2. Start/restart the server/container so that it picks up the newly deployed


application.

To extract a WAR file, you can use an archive utility program such as WinZip or 7-Zip
to extract its contents.
Q2 : (a) What is Servlet interface? Differentiate between GenericServlet and
HTTPServlet?

(b) Briefly explain servlet life cycle. Also, explain the request and response in the
context of HTTP?

Ans (a) :- The Servlet interface is a part of the Java Servlet API and defines methods for
initializing a servlet, handling client requests, and generating responses.

GenericServlet is an abstract class that implements the Servlet interface and


provides generic, protocol-independent servlet functionality.

HTTPServlet is a subclass of GenericServlet specifically designed to handle HTTP


requests, providing methods for processing different types of HTTP requests like GET
and POST.

Ans (b) :- The servlet life cycle involves three main stages: initialization, servicing
client requests, and destruction. It starts with the servlet's init() method for
initialization, followed by the service() method for processing client requests, and
ends with the destroy() method for cleanup.

In an HTTP context, a request is made by a client to access a resource on a server. It


includes details such as the URL being requested, request parameters, headers, and
sometimes a message body. After processing this request, the server sends back an
HTTP response containing status codes (e.g., 200 for success), headers defining
content type or length, and usually some content in its body.

Q3: (a) Explain the advantages of Java Server Pages over the servlet. Also, write a JSP
program for Fibonacci Series.

(b) Explain the various components of JSP with suitable code.

Ans (a) :- Advantages of Java Server Pages (JSP) over servlets include simpler
integration of server-side code with HTML, easier reusability of components, better
separation of concerns, rapid development, and easy integration with Java libraries.

Here's a short JSP program for generating the Fibonacci series:

```jsp
<%@ page language="java" contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Fibonacci Series</title>

</head>

<body>

<h2>Fibonacci Series:</h2>

<%

int n = 10; // Number of terms in the series

int firstTerm = ;

int secondTerm = 1;

out.print(firstTerm + " " + secondTerm);

for (int i = 2; i < n; i++) {

int nextTerm = firstTerm + secondTerm;

out.print(" " + nextTerm);

firstTerm = secondTerm;

secondTerm = nextTerm;

%>
</body>

</html>

```

In this JSP program, we use scriptlet tags (<%) to write Java code that generates the
Fibonacci series up to a given number of terms. The output is then printed within the
HTML body using out.print().

Ans (b) :- The various components of JSP include directives, declarations, scriptlets,
expressions, and actions/tags.

Directives:

```jsp

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


charset=UTF-8" %>

<%@ include file="header.jsp" %>

<%@ taglib uri="/tags/mytags" prefix="mytaglib" %>

```

Declaration:

```jsp

<%! int num = 10; %>

```

Scriptlet:

```jsp
<%

for (int i = ; i < num; i++) {

out.println("Iteration: " + i);

%>

```

Expressions:

```jsp

<p>The value of num is <%= num %></p>

```

Actions/Tags:

```jsp

<jsp:include page="header.jsp"/>

```

These components allow for the creation of dynamic web pages with embedded Java
code and special functionality.

Q4: What do you mean by JDBC? Explain how we retrieve data from database using
suitable JSP program.

Ans :- JDBC (Java Database Connectivity) is an API that allows Java programs to
interact with databases. It provides a set of classes and interfaces for establishing
connections, sending SQL queries, and processing results.

To retrieve data from a database using a JSP program, you first need to establish a
connection to the database using JDBC. This typically involves loading the JDBC driver
for your specific database, creating a connection object, and then creating a
statement object to execute SQL queries.
In your JSP code, you can use scriptlets or JSTL (JavaServer Pages Standard Tag
Library) to write Java code that interacts with the database. You would execute an SQL
query using the statement object and process the results using ResultSet. For
example:

```java

<%@ page language="java" %>

<%@ page import="java.sql.*" %>

<%

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase&quot
;, "username", "password");

stmt = conn.createStatement();

rs = stmt.executeQuery("SELECT * FROM mytable");

while(rs.next()) {

out.println(rs.getString(1)); // Process retrieved data here

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

} finally {

if(rs != null) rs.close();

if(stmt != null) stmt.close();

if(conn != null) conn.close();

%>

```

In this example, we establish a connection to a MySQL database, execute an SQL


query to retrieve all rows from 'mytable', then process the retrieved data
within the while loop.

It's important to note that it's generally not recommended to directly


include Java code in JSP pages; instead consider separating concerns by using
servlets or other MVC frameworks

Q5: What are the Strut2 core components? Explain the working and flow of Struts 2
with the help of suitable diagram.

Ans :- The core components of Struts 2 are Action, Interceptors, ValueStack, Result
Types, and Configuration Files.

Working and Flow:

1. HTTP Request is sent from the client browser.

2. The request is intercepted by the Struts 2 Filter or Servlet.

3. The configuration files are parsed to map the request to an appropriate Action
class.

4. The Action class's method is executed, which involves data processing and
business logic.

5. The result type is generated based on the action execution.

6. A response is rendered back to the client browser as an HTTP Response.


Diagram:

```

Client Browser ----> HTTP Request ----> Struts 2 Filter/Servlet

| |

| Configuration Parsing

| |

V V

Action Response Rendering

```

This flow illustrates how a request from the client browser goes through various core
components of Struts 2 before generating a response back to the client.

Q6: (a) Explain process of creating records using Spring Boot and Hibernate.

(b) Explain how testing of custom login form can be performed with the help of an
example.

Ans (a) :- 1. Set up Spring Boot project with JPA and Hibernate dependencies.
2. Create an Entity class annotated with @Entity and @Table.
3. Define a Repository interface extending JpaRepository for CRUD operations.
4. Implement a Service class to interact with the repository.
5. Create RESTful API endpoints using a Controller class.
6. Configure application properties for data source details.
7. Run the Spring Boot application, use Hibernate's session factory to save records into the database via the
API endpoint provided by the controller class.

Ans (b) :- To test a custom login form, you can use Spring Boot's testing
framework along with Mockito for mocking dependencies. Here's an example of
how you can perform testing of a custom login form:

1. Create a test class for the custom login form, let's say
`CustomLoginFormTest`.

2. Use annotations such as `@RunWith(SpringRunner.class)` and


`@SpringBootTest` to initialize the Spring context and load the necessary beans.

3. Use `MockMvc` to simulate HTTP requests to your login endpoint and verify the
response.
4. Mock the authentication service or repository using Mockito to provide predefined
responses for user authentication.

5. Write test methods to check if valid credentials result in successful login and
invalid credentials result in appropriate error messages or redirection.

Example Code:

```java

@RunWith(SpringRunner.class)

@SpringBootTest

public class CustomLoginFormTest {

@Autowired

private WebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@Before

public void setup() {

this.mockMvc =
MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

@Test

public void testValidLogin() throws Exception {

mockMvc.perform(formLogin("/login").user("username",
"validUser").password("password",
"validPassword"))
.andExpect(authenticated());

@Test

public void testInvalidLogin() throws Exception {

mockMvc.perform(formLogin("/login").user("username",
"invalidUser").password("password",
"invalidPassword"))

.andExpect(unauthenticated())

.andExpect(status().is3xxRedirection())

.andExpect(redirectedUrl("/login?error"));

```

In this example, we are using `MockMvc` to perform

Q7: Explain how CRUD operations are mapped to SQL statements, with suitable
example

Ans :- CRUD operations (Create, Read, Update, Delete) in a database are mapped to
SQL statements as follows:

1. Create - The "CREATE" operation is mapped to the "INSERT"


SQL statement. This statement is used to add new records into a table. For example:

```sql

INSERT INTO employees (id, name, department) VALUES (1, 'John Doe',
'IT');

```
2. Read - The "READ" operation is mapped to the "SELECT"
SQL statement. This statement retrieves data from the database based on specified
conditions. For example:

```sql

SELECT * FROM employees WHERE department = 'IT';

```

3. Update - The "UPDATE" operation is mapped to the


"UPDATE" SQL statement. This statement modifies existing records in a
table based on specified conditions. For example:

```sql

UPDATE employees SET department = 'HR' WHERE id = 1;

```

4. Delete - The "DELETE" operation is mapped to the "DELETE"


SQL statement. This statement removes records from a table based on specified
conditions.

For example:

```sql

DELETE FROM employees WHERE id = 1;

```

These SQL statements correspond directly to their respective CRUD operations and
allow for manipulation of data within a database management system.

Q8: (a) Write the unit test case to execute it as a user with RequestPostProcessor for
the URL pattern “/” which returns model attribute with key as “message” and value as
“Hello World”.

(b) What is Role-based Login? Explain how user’s access can be restricted using Role-
based Login.

Ans :- ```java
import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;

import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)

@WebMvcTest(YourController.class)

public class YourControllerTest {

@Autowired

private MockMvc mockMvc;

@Test

public void testHelloWorldMessage() throws Exception {

mockMvc.perform(get("/").with(user("username&am
p;quot;)))

.andExpect(status().isOk())

.andExpect(model().attribute("message", "Hello
World"));

```

Ans (b) :- Role-based login is a method of controlling user access to different features
or areas within an application based on their assigned role or permission level. This
approach allows administrators to define specific roles, such as "admin,"
"manager," or "employee," and assign access rights and
privileges accordingly.

Using role-based login, access restrictions are enforced by associating each user
with one or more roles that determine the actions they can perform and the resources
they can access. For example, an admin might have full access to all parts of the
application, while a manager may have restricted access, and an employee may only
be able to view certain information.

By implementing role-based login, organizations can ensure that users are granted
appropriate levels of access based on their responsibilities and permissions within
the system. This enhances security by preventing unauthorized users from accessing
sensitive information or performing actions beyond their scope of authority.

Q9: Write short notes on the following:

(a) JSP Standard Tag Library (JSTL)

(b) Spring Framework

(c) Cross Site Request Forgery (CSRF)

Ans (a) :- The JSP Standard Tag Library (JSTL) is a collection of custom tags and
functions that extend the functionality of JavaServer Pages (JSP). It provides a set of
tags that allow developers to perform common tasks, such as iteration, conditional
processing, manipulation of XML documents, and formatting and internationalization
of data, without using embedded Java code.

JSTL simplifies JSP development by providing a more declarative approach to creating


dynamic web pages. It helps separate the presentation logic from the underlying
business logic by allowing developers to use tags instead of writing Java code directly
within the JSP file.

There are several core components in JSTL:

1. Core Tags: These include tags for iteration, conditionals, URL management, and
output formatting.

2. Formatting Tags: These provide support for formatting dates, numbers, currencies,
and messages based on locale settings.

3. SQL Tags: These provide simple database access capabilities for querying
databases from within JSP pages.
4. XML Tags: These enable parsing and transformation of XML documents within JSP
pages.

Overall, the use of JSTL promotes cleaner and more maintainable code in JSP
applications by encapsulating common functionality in reusable tag libraries.

Ans (b):- The Spring Framework is a comprehensive and widely used open-source
application framework for Java. It provides a comprehensive programming and
configuration model for modern Java-based enterprise applications, with features
such as dependency injection, aspect-oriented programming, and support for various
architectural patterns like MVC (Model-View-Controller).

Spring aims to simplify the development of enterprise-level applications by


promoting good design principles and providing reusable components that can be
easily integrated into various layers of an application. It also offers support for
integration with other technologies such as Hibernate, JPA, JMS, and more.

Overall, the Spring Framework is known for its flexibility, modularity, and extensive
ecosystem of extensions that cater to different aspects of enterprise application
development.

Ans (c) :- Cross-Site Request Forgery (CSRF) is a type of web security vulnerability. It
occurs when an attacker tricks a user into performing actions on a website without
their knowledge or consent. This typically happens when the user is authenticated on
the targeted website.

CSRF attacks involve the attacker crafting a malicious request and getting the
victim's browser to execute it, often using hidden form elements or JavaScript.
This can lead to unauthorized actions being performed within the context of the
victim's active session, such as changing account settings, making purchases,
or transferring funds.

To protect against CSRF attacks, developers can implement measures such as using
anti-CSRF tokens in web forms and requests. These tokens help verify that requests
are legitimate and originate from authorized sources. Frameworks like Spring Security
offer built-in protection against CSRF through token-based security mechanisms.
In essence, defending against CSRF involves ensuring that any user-initiated action
requires an unpredictable token or challenge to be included with the request. This
helps prevent attackers from forging requests and carrying out unauthorized actions
on behalf of unsuspecting users.

You might also like