MCS 220
MCS 220
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.
1. Copy the generated WAR file into the deployment directory of the server/container.
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.
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.
Q3: (a) Explain the advantages of Java Server Pages over the servlet. Also, write a JSP
program for Fibonacci Series.
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.
```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 firstTerm = ;
int secondTerm = 1;
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
```
Declaration:
```jsp
```
Scriptlet:
```jsp
<%
%>
```
Expressions:
```jsp
```
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
<%
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase"
;, "username", "password");
stmt = conn.createStatement();
while(rs.next()) {
} catch(Exception e) {
e.printStackTrace();
} finally {
%>
```
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.
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.
```
| |
| Configuration Parsing
| |
V V
```
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`.
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
@Autowired
@Before
this.mockMvc =
MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
@Test
mockMvc.perform(formLogin("/login").user("username",
"validUser").password("password",
"validPassword"))
.andExpect(authenticated());
@Test
mockMvc.perform(formLogin("/login").user("username",
"invalidUser").password("password",
"invalidPassword"))
.andExpect(unauthenticated())
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/login?error"));
```
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:
```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
```
```sql
```
For example:
```sql
```
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)
@Autowired
@Test
mockMvc.perform(get(&quot;/&quot;).with(user(&quot;username&am
p;quot;)))
.andExpect(status().isOk())
.andExpect(model().attribute(&quot;message&quot;, &quot;Hello
World&quot;));
```
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.
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.
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).
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.