Ajava
Ajava
Redirects the request to another Includes the content of another resource into the
Action
resource current response
User
User is redirected to a new URL User remains on the same page
Perspective
• The InetAddress class in Java is used to represent an Internet Protocol (IP) address.
2. What are the differences between a TCP socket and UDP socket? How are they created in Java?
• Heavier: Involves more overhead due to connection establishment and error checking.
• URL Connection: An abstract class that represents a communication link to a URL. It provides
methods for opening a connection to the URL, setting request properties, reading response
headers and data, and writing data to the server.
• ServerSocket: A class in Java that represents a server-side socket. It listens for client
connection requests on a specified port. When a client connects, the ServerSocket creates a
new Socket object to handle the communication with that client.
Example:
Java
import java.io.*;
import java.net.*;
try {
while (true) {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
5. Write a client-server application using TCP Socket where client can send message & server
respond with the server of them.
Server Code (MyServer.java): (Similar to the example above, but with message handling)
Java
while (true) {
out.println(serverResponse);
clientSocket.close();
Java
Java
out.println("Hello");
socket.close();
Note: These are simplified examples and may require additional error handling and input validation
in real-world scenarios.
=
o Performance: Precompiling the statement once and then reusing it with different
parameter values significantly improves performance compared to executing the
same statement repeatedly with Statement.
o Security: Helps prevent SQL injection vulnerabilities by separating the SQL statement
from the input parameters. This makes it harder for attackers to manipulate the
query.
Example:
Java
String sql = "INSERT INTO users (username, email) VALUES (?, ?)";
pstmt.setString(1, "john.doe");
pstmt.setString(2, "john.doe@example.com");
In this example: - We create a PreparedStatement with placeholders (?) for the username and email.
- We set the values for the placeholders using pstmt.setString(1, value). - pstmt.executeUpdate()
executes the prepared statement and returns the number of rows affected.
Example (CallableStatement):
Java
ResultSet rs = cstmt.executeQuery();
// Process the ResultSet
• execute(): The most general method. It can be used for any SQL statement. Returns boolean:
true if the result is a ResultSet, false otherwise.
• executeUpdate(): Used for SQL statements that modify data (INSERT, UPDATE, DELETE).
Returns the number of rows affected.
4. What is database connection URL? How do you make a database connection? Explain various
ways to make the connection URL.
• Database Connection URL: A string that specifies the details required to connect to a
database, such as:
o Hostname or IP address
o Port number
o Database name
Example:
jdbc:mysql://localhost:3306/mydatabase
1. Using DriverManager:
Java
2. Using a connection pool (e.g., Apache Commons DBCP, HikariCP): Connection pools manage
a pool of database connections, which can improve performance and resource utilization.
5. What is JDBC driver? Explain its role and compare various JDBC drivers.
• JDBC Driver: A software component that enables Java programs to interact with a database.
It translates JDBC calls into the specific protocol understood by the database.
o Type 4 (Thin Driver): Pure Java driver, communicates directly with the database.
• Comparison:
o Type 4 drivers are generally preferred due to their portability and ease of
deployment.
o Number of columns
o Column names
o Column types
o Column sizes
7. What is ResultSet Interface? Write various methods for ResultSet interface. Write a code to
update record using this interface.
Methods:
Updating a record:
Java
rs.updateString("username", "updated_username");
rs.updateInt("age", 30);
rs.updateRow();
8. List types of driver used in JDBC. Explain any 2 JDBC Drivers in Details.
• Requires an ODBC driver for the specific database to be installed on the client machine.
Servlet is a Java class that extends the javax.servlet.HttpServlet class. It acts as a middle
layer between a web server (like Tomcat, Apache) and a web browser. Servlets handle client
requests, process them, and generate dynamic web content.
• init(): This method is called only once when the servlet is first loaded or instantiated
by the web container. It's used to perform one-time initialization tasks like creating
database connections or loading configuration files.
• service(): This is the core method that handles all client requests. It determines the
HTTP method used (GET, POST, etc.) and dispatches the request to the appropriate
doXXX() method (e.g., doGet(), doPost()).
• destroy(): This method is called only once before the servlet is unloaded from the
web container. It's used to release any resources acquired during initialization, such as
database connections or open files.
• Cookies: Small pieces of data stored on the client-side (browser) by the server. They
can be used to identify the user and maintain session information.
• URL Rewriting: Appending session information to the URL of each page. This is
useful when cookies are disabled or not supported.
• Hidden Form Fields: Including hidden form fields with session information in each
form submission.
• HTTPSession Object: A Java object provided by the Servlet API to manage session
data on the server-side.
3. Explain the purpose of Request Dispatcher using the methods forward() & include().
(M-4)
Request Dispatcher is an interface in the Servlet API that allows a servlet to forward or
include the processing of a request to another resource (servlet, JSP, HTML file).
• forward(): Sends the request directly to the specified resource. The original request
object is passed to the new resource, so the original servlet is no longer involved in
the response.
• include(): Includes the content of the specified resource into the response of the
original servlet. Both the original servlet and the included resource contribute to the
final response.
Cookies are small text files stored on the client-side (browser) by the web server. They can
contain information like user preferences, login status, or session IDs.
Java
// Create a cookie
Cookie cookie = new Cookie("username", "john_doe");
response.addCookie(cookie);
5. What is filter? List the applications of filter. Explain the configuration of filter using
deployment descriptor. (M-7)
Applications of Filters:
XML
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.example.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
6. Discuss Servlet life cycle methods. Explain the role of the web container. (M-4)
Servlet is a Java class that extends the javax.servlet.HttpServlet class. It acts as a middle layer
between a web server (like Tomcat, Apache) and a web browser. Servlets handle client requests,
process them, and generate dynamic web content
Web Container: A web container is a runtime environment that provides the necessary
infrastructure for deploying and running Java servlets and JavaServer Pages (JSPs). It handles
tasks like:
Java
// Servlet1
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet2");
dispatcher.forward(request, response);
// Servlet2
PrintWriter out = response.getWriter();
out.println("This is Servlet2");
Java
// Servlet1
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet2");
dispatcher.include(request, response);
// Servlet1
PrintWriter out = response.getWriter();
out.println("This is Servlet1");
out.println("Including Servlet2...");
dispatcher.include(request, response);
out.println("Back to Servlet1");
8. Write a servlet code which reads the student details from a web page and stores it in a
database. (M-7)
Java
// StudentServlet
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
// ... get other details
FilterConfig is an interface that provides access to the filter's configuration information, such
as initialization parameters defined in the deployment descriptor.
Using FilterConfig:
Java
public class MyFilter implements Filter {
private FilterConfig filterConfig;
JSP provides a set of predefined objects that can be used directly within JSP pages without explicit
declaration. These objects represent various aspects of the servlet environment.
• request: Represents the HTTP request sent by the client. It provides methods to access
request parameters, headers, cookies, attributes, etc.
• response: Represents the HTTP response to be sent back to the client. It provides methods
to set headers, cookies, status codes, and write content to the output stream.
• session: Represents the HTTP session associated with the client. It allows you to store and
retrieve session-specific data.
• application: Represents the servlet context, which is shared across all servlets within the
web application. It provides methods to access application-wide resources and attributes.
• out: Represents the output stream used to send data to the client. It provides methods for
writing text, HTML, and other content to the response.
• page: Represents the current JSP page. It can be used to access page-specific information.
• config: Represents the servlet configuration object. It provides access to initialization
parameters defined in the deployment descriptor.
• pageContext: Provides access to the current page context, including the request, response,
session, application, out, config, exception, and other useful information.
• exception: Represents the exception object, if any, that occurred during the processing of
the JSP page.
2. Which action tags are used to access the JavaBeans from a JSP page? (M-3)
3. What is Expression Language EL in JSP explain with suitable example program? (M-4)
EL is a simple and powerful language used to access and manipulate data within JSP pages. It
provides a concise way to access and manipulate data from various sources, including JavaBeans,
request parameters, session attributes, and application attributes.
Example:
Java
Session:
A session represents a conversation or interaction between a client and a server that spans multiple
requests. It allows you to track user information and preferences across multiple pages within a
single visit.
Example:
Java
<%
if (username != null) {
// User is logged in
} else {
%>
5. What is JSTL? Explain the core tags of the SQL tag library. (M-4)
JSTL is a set of custom tags that provide common functionality for web applications, such as iteration,
conditional logic, data manipulation, and database access.
1. Translation: The JSP page is translated into a servlet by the JSP container.
3. Loading: The compiled servlet class is loaded into memory by the web container.
6. Request Processing: The servlet's service() method is called to handle each incoming
request.
7. Destruction: The servlet's destroy() method is called when the servlet is being removed from
the web container.
7. What is a custom tag? Explain the life cycle of tag handler. (M-3)
Custom Tag:
A custom tag is a user-defined tag that extends the functionality of JSP. It encapsulates reusable logic
and presentation elements.
2. Setting Properties: The tag handler's properties are set based on the attributes specified in
the tag.
3. DoStartTag(): This method is called when the start tag of the custom tag is encountered.
4. DoEndTag(): This method is called when the end tag of the custom tag is encountered.
5. Release(): This method is called to release any resources held by the tag handler.
8. Write a JSP application for login module with reset password feature using database
connectivity. (M-7)
This would require a more complex implementation with database interaction, form handling, and
session management. Please refer to JSP examples and tutorials for a complete implementation.
Page directives provide instructions to the JSP container about how to process the JSP page.
Example:
Java
This directive sets the content type of the response to HTML and specifies the character encoding.
11. What are the implicit objects of JSP? Write a JSP page to demonstrate the use them. (M-7)
12. What is JSTL? Write a code snippet to show the use of flow control tags. (M-3)
Java
<c:if test="${condition}">
</c:if>
<c:choose>
<c:when test="${condition1}">
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
</c:forEach>
Chapter-5: Java Server Faces 2.0
JSF (JavaServer Faces) is a framework for building user interfaces for Java web applications. It aims to
simplify the development of web applications by providing a component-based model and a set of
standard UI components.
Features of JSF:
• Event Handling: JSF provides a robust event-handling mechanism that simplifies the
management of user interactions with UI components.
• Data Binding: JSF offers seamless data binding between UI components and JavaBeans,
making it easier to manage data flow in the application.
• Expression Language (EL): EL is used to access and manipulate data within JSF pages,
providing a concise and powerful way to work with data.
• Validation and Conversion: JSF includes built-in support for data validation and conversion,
ensuring that user input is correct and in the expected format.
• State Management: JSF provides mechanisms for managing the state of the application, such
as session management and view state.
• Facelets: Facelets is a templating system that provides a more efficient and flexible way to
create JSF views compared to traditional JSP.
2. Discuss JSF life cycle phases. OR Explain the JSF request processing life cycle. (M-7)
2. Apply Request Values: The values submitted by the user in the request are applied to the
corresponding UI components.
3. Process Validations: Validation rules are applied to the component values to ensure they are
valid.
4. Update Model Values: The valid values from the UI components are updated in the backing
bean.
6. Render Response: The JSF runtime renders the updated view to the client.
3. What is the JSF facelets? Explain any two facelets tags. (M-3)
Facelets:
Facelets is a templating system that provides a more efficient and flexible way to create JSF views
compared to traditional JSP. It offers features like composite components, templating, and expression
language integration.
• ui:composition: This tag is used to define the structure of a Facelets template or composite
component.
• ui:include: This tag is used to include other Facelets templates or components within a page.
4. List the JSF standard converter tags and explain any three in detail. (M-4)
• <f:convertNumber>: This tag is used to convert a string value entered by the user into a
numeric value. It can handle different number formats based on the locale.
• <f:convertDateTime>: This tag is used to convert a string value entered by the user into a
date or time object. It supports various date and time formats.
• <f:convertBoolean>: This tag is used to convert a string value entered by the user into a
boolean value (true or false). It can handle different string representations of boolean values.
5. What is EL? Write a code snippet to show the use of method expressions in JSF page. (M-3)
Expression Language (EL):
EL is a simple and powerful language used to access and manipulate data within JSF pages. It
provides a concise way to access and manipulate data from various sources, including JavaBeans,
request parameters, session attributes, and application attributes.
XML
This code snippet demonstrates the use of a method expression #{myBean.doSomething()} to invoke
the doSomething() method of the myBean bean when the button is clicked.
6. Write a code snippet to show the use of JSF action event. (M-4)
XML
In this example, processForm is the action method in the myBean bean that will be invoked when the
button is clicked.
JSF Converter:
A converter is used to convert data between the string representation entered by the user and the
corresponding Java object. It ensures that the data entered by the user is in the correct format.
A validation tag is used to define validation rules for the data entered by the user. It checks if the
data meets certain criteria, such as required fields, length constraints, and regular expression
patterns.
Chapter-6: Hibernate 4.0
• Simplified Database Interactions: Hibernate abstracts away the complexities of SQL and
JDBC, allowing you to work with objects instead of database tables and rows.
• Improved Productivity: By reducing the amount of code needed to interact with the
database, Hibernate can significantly increase developer productivity.
• Portability: Hibernate applications are more portable across different databases as it handles
the database-specific details.
• Lazy Loading: Hibernate supports lazy loading, which can improve performance by fetching
only the necessary data from the database.
2. What is HQL? How does it different from SQL? List its advantages. (M-4)
HQL (Hibernate Query Language) is an object-oriented query language used within Hibernate to
interact with objects and their relationships.
• Object-Oriented: HQL operates on objects and their properties, while SQL operates on tables
and columns.
• Associations: HQL provides easy ways to query associated objects, which can be complex to
express in SQL.
Advantages of HQL:
• Database Independence: HQL queries can be easily ported across different databases.
• Type Safety: HQL provides type safety, as it operates on Java objects and their properties.
Object-Relational Mapping (ORM) is a technique that maps Java objects to relational database
tables. It allows you to work with objects in your application while Hibernate handles the underlying
database interactions.
• <mapping resource="...">: Specifies the location of the Hibernate mapping files (usually in
XML format) that define the mapping between Java classes and database tables.
• <mapping class="...">: (Optional) Specifies the fully qualified name of a Java class that has
annotations for Hibernate mapping.
• SessionFactory: A factory object that creates Session objects. It's responsible for managing
the connection pool and configuration settings.
• Session: An interface that represents a single unit of work with the database. It provides
methods for saving, loading, updating, and deleting objects.
• Transaction: Represents a single unit of work that must be completed atomically (either all
operations succeed or all fail).
Hibernate uses XML mapping files or annotations to define the mapping between Java classes and
database tables. This includes:
6. What are the different Hibernate interfaces? Explain their role in brief. (M-7)
8. What is OR mapping? How will you configure hibernate mapping file to map a table & its
columns from a given database? (M-4)
OR Mapping:
(Refer to the explanation of ORM in question 3)
1. Create a Java Class: Create a Java class that represents the database table.
2. Create a Mapping File (XML): Create an XML file (e.g., User.hbm.xml) to define the mapping
between the Java class and the table.
3. Define Class Mapping: In the mapping file, specify the table name and the class name.
4. Define Property Mappings: Map the class properties to the corresponding table columns
using the <property> tag. Specify the column name, data type, and any additional properties
like length or precision.
Example:
XML
<hibernate-mapping>
<generator class="increment"/>
</id>
</class>
</hibernate-mapping>
Chapter-7: Java Web Frameworks: Spring MVC
In Spring MVC, controllers are the heart of the application. They handle incoming HTTP requests,
process them, and generate appropriate responses. Here's a breakdown:
• Role:
o Handle the request, process data, and interact with other components like services
and repositories.
• Types:
o @Controller: The primary annotation for marking a class as a Spring MVC controller.
• Methods:
Spring provides several bean scopes to control the lifecycle and sharing of beans within the
application context:
• singleton: Only one instance of the bean is created and shared across the entire application.
This is the default scope.
• request: A new instance of the bean is created for each HTTP request.
• session: A new instance of the bean is created for each HTTP session.
• application: A new instance of the bean is created for each web application.
• websocket: A new instance of the bean is created for each WebSocket session.
3. What is Spring Bean? How can you create bean in Spring Boot? (M-4)
Spring Bean:
A Spring Bean is any Java class that is managed by the Spring IoC container. It's instantiated,
configured, and wired together by the container.
Creating Beans in Spring Boot:
o Annotate your class with @Component (or its variants like @Service, @Repository,
@Controller).
o Spring will automatically detect and register this class as a bean in the application
context.
o The method's return value will be registered as a bean in the application context.
Example:
Java
@Component
// ...
@Configuration
@Bean
• Flexible view resolution: Supports various view technologies like JSP, Thymeleaf, Velocity.
• RESTful web services support: Easily create RESTful APIs using @RestController.
• Integration with other Spring modules: Seamlessly integrates with other Spring modules like
Spring Security, Spring Data, etc.
1. DispatcherServlet: The central front controller that intercepts all incoming HTTP requests.
3. Controller: Handles the request, processes data, and returns a ModelAndView object.
4. ViewResolver: Resolves the view name returned by the controller to an actual view object.
5. View: Renders the model data to the client using a specific view technology.
6. What are the advantages of Spring MVC? Explain the flow of Spring Web MVC. (M-7)
• Testability: Easy to test controllers and other components using unit tests.
• Community and Support: Backed by a large and active community with extensive
documentation and support.
3. Controller: The controller method handles the request, processes the data, and returns a
ModelAndView object.
4. View Resolver: The DispatcherServlet delegates the view resolution to the ViewResolver,
which finds the appropriate view based on the view name.
5. View Rendering: The view renders the model data and sends the response back to the client.
7. What is Spring AOP? What are Join points and Point cuts? (M-3)
AOP is a programming paradigm that allows you to add cross-cutting concerns (like logging, security,
transaction management) to your application without modifying the core business logic.
• Join Points: Points in the application where you can apply AOP advice (e.g., method
execution, exception handling).
• Pointcuts: Expressions that define which join points you want to apply advice to.
8. What is dependency Injection? What is the role IoC container in Spring? (M-4)
Dependency Injection (DI):
DI is a design pattern where objects get their dependencies (other objects they need to work with)
from an external source, rather than creating them themselves.
The IoC container is responsible for creating, configuring, and managing the lifecycle of beans in a
Spring application. It injects dependencies into beans based on their configuration.
9. What do you mean by MVC architecture? Explain its role in modern applications with its
advantages. (M-3)
MVC (Model-View-Controller):
MVC is a software architectural pattern that separates an application into three interconnected
components:
• View: Displays the data to the user and allows user interaction.
• Controller: Handles user input, interacts with the model, and selects the appropriate view.
MVC promotes loose coupling between different parts of the application, making it easier to
maintain, test, and modify. It also improves code reusability and enables parallel development.
Advantages:
• Maintainability: Easier to maintain and modify as changes in one component have minimal
impact on others.
• Reusability: Views and controllers can be reused in different parts of the application or even
in other applications.
• Parallel Development: Different teams can work on the model, view, and controller
components concurrently.
Feel free to ask if you have any more questions or want to explore specific topics in more detail!