Advance Java

SERVLETS

Java Servlets are server-side Java programs that handle client requests and generate dynamic web content, typically in response to HTTP requests. 
They act as a middle layer between a web browser (or other client) and a backend database or application.

What Exactly Is a Servlet?
A Servlet is a Java class that runs inside a Servlet container (like Apache Tomcat) and extends the capabilities of servers that host applications accessed via a request-response model. 
It’s a core component of Java EE (now Jakarta EE) for building web applications.

Key Features
- Runs on the server-side: Handles HTTP requests and responses.
- Dynamic content generation: Can generate HTML, JSON, XML, etc.
- Efficient and scalable: Better performance than older CGI-based solutions.
- Platform-independent: Written in Java, runs on any OS with a compatible JVM.
- Session management: Supports cookies, URL rewriting, and HTTPS sessions.

Servlet Lifecycle
1. Initialization (`init()`): Called once when the servlet is first loaded.
2. Request Handling (`service()`): Called for each client request.
3. Destruction (`destroy()`): Called once when the servlet is taken out of service.

Example: Basic Servlet
```java
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h1>Hello, Servlet!</h1>");
    }
}
```

- @WebServlet("/hello"): Maps the servlet to the `/hello` URL.
- doGet(): Handles HTTP GET requests.

Deployment
Servlets are typically packaged in a WAR (Web Application Archive) file and deployed to a servlet container like Apache Tomcat, Jetty, or GlassFish.

Learn More
- [GeeksforGeeks: Introduction to Java Servlets](https://www.geeksforgeeks.org/java/introduction-java-servlets/)
- [TutorialsPoint: Servlets Overview](https://www.tutorialspoint.com/servlets/servlets_overview.htm)
- [Baeldung: Intro to Servlets](https://www.baeldung.com/intro-to-servlets)

> Would you like to scaffold a mini-project using Servlets—like a login form, contact form handler, or a REST-style backend?


JavaServer Pages (JSP)


JavaServer Pages (JSP) is a server-side technology that enables dynamic web content creation by embedding Java code directly into HTML pages. 
It simplifies web development by separating presentation logic from business logic and is often used alongside Servlets in Java web applications.

What Is JSP?
JSP is part of the Jakarta EE (formerly Java EE) platform and acts as a view layer in MVC-based web applications. It allows developers to write HTML pages with embedded Java code using special tags like `<% %>`, making it easier to generate dynamic content such as user-specific pages, database-driven views, and form responses.

Key Features
- Dynamic Content: Generates HTML based on server-side logic.
- Tag-Based Syntax: Uses JSP tags to insert Java code into HTML.
- Implicit Objects: Provides built-in objects like `request`, `response`, `session`, `application`, and `out`.
- JavaBeans Integration: Easily connects to JavaBeans for reusable business logic.
- Custom Tags and JSTL: Supports reusable tag libraries like JSTL for cleaner code.

JSP Lifecycle
1. Translation: JSP is converted into a Servlet by the container.
2. Compilation: The Servlet is compiled into bytecode.
3. Initialization: The Servlet is initialized.
4. Execution: The Servlet handles requests and generates responses.
5. Destruction: The Servlet is destroyed when no longer needed.

Example JSP Page
```jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head><title>Welcome</title></head>
<body>
<%
    String name = request.getParameter("name");
    out.println("<h1>Hello, " + name + "!</h1>");
%>
</body>
</html>
```

This page greets the user by name, using a query parameter from the URL.

Advantages Over Servlets
- Cleaner Syntax: Easier to write and maintain than pure Java Servlets.
- Separation of Concerns: Keeps UI logic separate from backend logic.
- Rapid Development: Ideal for quick prototyping and dynamic page generation.

Learn More
- [GeeksforGeeks: Introduction to JSP](https://www.geeksforgeeks.org/advance-java/introduction-to-jsp/)
- [Baeldung: Guide to JSP](https://www.baeldung.com/jsp)
- [TutorialsPoint: JSP Overview](https://www.tutorialspoint.com/jsp/jsp_overview.htm)

> Would you like to scaffold a mini-project using JSP—like a login form, user dashboard, or a dynamic product listing page?


JSP tags


JSP tags are special constructs used to embed Java code and control logic within HTML pages in JavaServer Pages (JSP). 
They enable dynamic content generation, interaction with JavaBeans, and control over page flow and data presentation.

Types of JSP Tags
JSP tags are categorized into several types, each serving a specific purpose:

1. Scripting Elements
Used to embed Java code directly into the JSP page.
Tag | Purpose
`<% ... %>` | Scriptlet: embeds Java code
`<%= ... %>` | Expression: outputs result of Java expression
`<%! ... %>` | Declaration: declares methods or variables

Example:
```jsp
<% int count = 5; %>
<%= count * 2 %>
```

2. Directive Tags
Provide global information about the JSP page.

Tag | Purpose
`<%@ page ... %>` | Defines page-level settings (e.g., contentType, import)
`<%@ include file="..." %>` | Includes static content from another file
`<%@ taglib ... %>` | Declares tag libraries like JSTL

Example:
```jsp
<%@ page import="java.util.Date" %>
```

3. Action Tags
Interact with JavaBeans and control page flow.

Tag | Purpose
`<jsp:useBean>` | Instantiates or accesses a JavaBean
`<jsp:setProperty>` | Sets bean properties
`<jsp:getProperty>` | Retrieves bean properties
`<jsp:include>` | Includes dynamic content
`<jsp:forward>` | Forwards request to another resource

Example:
```jsp
<jsp:useBean id="user" class="com.example.User" />
<jsp:setProperty name="user" property="name" value="Sudhamsh" />
<jsp:getProperty name="user" property="name" />
```

4. Custom Tags
Reusable components defined in tag libraries (e.g., JSTL).

Example (JSTL):
```jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:if test="${user.loggedIn}">
  Welcome back!
</c:if>
```

Learn More
- [JSP Tags Overview – TechGuruSpeaks](https://www.techguruspeaks.com/jsp-tags/)
- [TutorialsPoint JSP Overview](https://www.tutorialspoint.com/jsp/jsp_overview.htm)
- [GeeksforGeeks Introduction to JSP](https://www.geeksforgeeks.org/advance-java/introduction-to-jsp/)

> Would you like to scaffold a JSP-based login page or dashboard using these tags? 



JSTL (JavaServer Pages Standard Tag Library)

JSTL (JavaServer Pages Standard Tag Library) provides a set of powerful, reusable tags that simplify common tasks in JSP like iteration, conditionals, formatting, and database access. 
These tags help eliminate Java scriptlets from JSP pages, making them cleaner and more maintainable.

Categories of JSTL Tags
JSTL tags are grouped into five major categories:
1. Core Tags (`c` prefix)
Used for control flow, variable manipulation, and URL handling.

Tag | Purpose
`<c:if>` | Conditional logic
`<c:choose>`, `<c:when>`, `<c:otherwise>` | Switch-case style logic
`<c:forEach>` | Iteration over collections
`<c:set>` | Set variable values
`<c:out>` | Output values (auto-escapes HTML)
`<c:import>` | Import content from a URL or file
`<c:redirect>` | Redirect to another page

Example:
```jsp
<c:forEach var="item" items="${items}">
  <li>${item}</li>
</c:forEach>
```

2. Formatting Tags (`fmt` prefix)
Used for internationalization and number/date formatting.

Tag | Purpose
`<fmt:formatNumber>` | Format numbers
`<fmt:formatDate>` | Format dates
`<fmt:message>` | Retrieve localized messages
`<fmt:setLocale>` | Set locale for formatting

Example:
```jsp
<fmt:formatDate value="${now}" pattern="dd-MM-yyyy" />
```

3. SQL Tags (`sql` prefix)
Used for database operations directly from JSP (not recommended for production).

Tag | Purpose
`<sql:query>` | Execute SQL SELECT |
`<sql:update>` | Execute SQL UPDATE/INSERT/DELETE |
`<sql:setDataSource>` | Define database connection |

Example:
```jsp
<sql:query var="users" dataSource="${myDS}">
  SELECT * FROM users
</sql:query>
```

4. XML Tags (`x` prefix)
Used for parsing and transforming XML documents.

Tag | Purpose
`<x:parse>` | Parse XML |
`<x:forEach>` | Iterate over XML nodes |
`<x:out>` | Output XML data |

5. Functions Tags (`fn` prefix)
Provides string manipulation functions.

Tag | Purpose
`fn:length()` | Get length of a string or collection
`fn:contains()` | Check substring presence
`fn:startsWith()` / `fn:endsWith()` | Check string prefixes/suffixes
`fn:toUpperCase()` / `fn:toLowerCase()` | Change case

Example:
```jsp
<c:if test="${fn:contains(name, 'Sudhamsh')}">
  Welcome, Sudhamsh!
</c:if>
```

Setup Instructions
To use JSTL in your project:
1. Add JSTL dependency in Maven:
   ```xml
   <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>jstl</artifactId>
     <version>1.2</version>
   </dependency>
   ```

2. Declare taglib in your JSP:
   ```jsp
   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
   ```

Sources
- [Baeldung – JSTL Guide](https://www.baeldung.com/jstl)
- [GeeksforGeeks – JSTL Core Tags](https://www.geeksforgeeks.org/java/jstl-core-tags/)
- [TutorialsPoint – JSTL Tutorial](https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm)

> Would you like to scaffold a JSP page using JSTL—for example, a dynamic product list or a multilingual welcome page?



JDBC (Java Database Connectivity)

JDBC (Java Database Connectivity) is a standard Java API that enables Java applications to interact with relational databases. 
It provides a set of interfaces and classes for connecting to databases, executing SQL queries, and processing results.

Key Features of JDBC
- Database Independence: Works with any relational database (MySQL, Oracle, PostgreSQL, etc.) via JDBC drivers.
- SQL Execution: Allows execution of SQL statements like `SELECT`, `INSERT`, `UPDATE`, and `DELETE`.
- Result Handling: Retrieves query results using `ResultSet` and processes them in Java.
- Transaction Management: Supports commit and rollback operations for reliable data handling.

Core Components
Component | Description
`DriverManager` | Manages JDBC drivers and establishes connections to databases.              |
`Connection` | Represents a session with the database.                                     |
`Statement` | Executes static SQL queries.                                                |
`PreparedStatement` | Executes parameterized SQL queries (safer and faster).                  |
`ResultSet` | Holds data retrieved from the database.                                     |
`SQLException` | Handles database-related errors.                                            |

JDBC Workflow Example
```java
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE age > ?");
stmt.setInt(1, 25);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
    System.out.println(rs.getString("name"));
}
rs.close();
stmt.close();
conn.close();
```

JDBC Driver Types
Type | Description
Type 1 | JDBC-ODBC bridge (obsolete)
Type 2 | Native-API driver (uses client-side libraries)
Type 3 | Network protocol driver (uses middleware)
Type 4 | Thin driver (pure Java, direct to database)



JavaMail API

JavaMail API is a platform-independent framework for building email and messaging applications in Java. 
It provides classes and interfaces to send, receive, and manage electronic messages using standard protocols like SMTP, POP3, and IMAP.

What JavaMail API Offers
- Protocol Independence: Supports multiple protocols including *SMTP* (sending), *POP3* and *IMAP* (receiving).
- Platform Independence: Works across operating systems and Java environments.
- MIME and RFC822 Support: Includes classes to handle Internet messaging standards like MIME (attachments, HTML content) and RFC822 (email headers).

Core Components
- javax.mail: Base package with classes like `Session`, `Message`, `Address`, and `Transport`.
- javax.mail.internet: Provides Internet-specific classes like `MimeMessage`, `InternetAddress`, and `MimeBodyPart`.
- javax.mail.event: Event listeners for message changes, folder updates, etc.
- javax.mail.search: Enables searching messages based on criteria like sender, subject, or date.

Typical Use Cases
- Sending Emails: Compose and send messages using SMTP.
- Receiving Emails: Connect to mail servers via POP3 or IMAP to read messages.
- Attachments and HTML: Handle rich content and file attachments using MIME.
- Email Automation: Integrate with backend systems for alerts, notifications, or scheduled reports.

Example Workflow
```java
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
Session session = Session.getDefaultInstance(props);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
message.setSubject("Test Mail");
message.setText("Hello from JavaMail!");
Transport.send(message);
```

Want to Dive Deeper?
You can explore the full documentation and tutorials on [TutorialsPoint](https://www.tutorialspoint.com/javamail_api/javamail_api_overview.htm) 
or the [official JavaMail API docs](https://javaee.github.io/javamail/docs/api/overview-summary.html).
> Would you like to scaffold a mini-project using JavaMail—say, an email alert system or a contact form backend?

Comments

Popular posts from this blog

Java 25 Features

Java Version Features

Java 8 Programs