Server-side Processing with Java

tl;dr

You will explore server-side processing with Java, focusing on Servlets, their lifecycle, and core methods, along with Java Server Pages (JSP) for dynamic web applications. They will gain hands-on experience with the Tomcat web server, learn database connectivity using JDBC, and practice SQL queries to interact with databases efficiently. This module equips students with the skills to build robust, data-driven web applications.

Table of Contents

What is JDBC?

JDBC (Java Database Connectivity) is an API (Application Programming Interface) that allows Java applications to interact with relational databases. It provides methods to query and update data in a database using SQL.

Why Use JDBC?

  • Allows Java programs to communicate with databases.
  • Provides a standard interface for different database systems.
  • Supports different types of database drivers for flexibility.
  • Enables seamless execution of SQL queries from Java applications.

JDBC consists of the following core components:

JDBC API

A collection of Java classes and interfaces that enable database interaction.

JDBC Driver Manager

Manages different types of JDBC drivers and establishes a connection between Java applications and databases.

JDBC Drivers

JDBC drivers translate Java API calls into database-specific calls. The four types of JDBC drivers are:

  • Type 1: JDBC-ODBC Bridge Driver
    • Uses ODBC drivers to connect to databases.
    • Requires ODBC installation.
    • Slow and platform-dependent.
  • Type 2: Native API Driver
    • Converts JDBC calls to native database API.
    • Requires database-specific native libraries.
    • Not portable across different databases.
  • Type 3: Network Protocol Driver
    • Uses a middleware server to translate JDBC calls into database-specific calls.
    • More flexible but requires additional setup.
  • Type 4: Thin Driver (Pure Java Driver)
    • Directly communicates with the database using network protocols.
    • Platform-independent and efficient (most commonly used).

JDBC Workflow

To interact with a database using JDBC, follow these steps:

Step 1: Load the JDBC Driver

Before making a database connection, the driver must be loaded.

java

CopyEdit

Class.forName(“com.mysql.cj.jdbc.Driver”);

This loads the MySQL JDBC driver.

Step 2: Establish a Connection

A connection to the database is created using DriverManager.

java

CopyEdit

Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/db_name”, “username”, “password”);

Step 3: Create a Statement Object

SQL queries are executed using a Statement or PreparedStatement.

java

CopyEdit

Statement stmt = con.createStatement();

Step 4: Execute SQL Queries

You can execute SQL queries using the executeQuery() or executeUpdate() methods.

java

CopyEdit

ResultSet rs = stmt.executeQuery(“SELECT * FROM students”);

Step 5: Process the Results

Results are retrieved using a ResultSet object.

java

CopyEdit

while (rs.next()) {

    System.out.println(rs.getInt(“id”) + ” ” + rs.getString(“name”));

}

Step 6: Close the Connection

Closing the connection ensures that database resources are freed.

java

CopyEdit

con.close();

JDBC provides different ways to execute SQL queries:

Statement

  • Used for executing simple SQL queries.
  • Example:

java

CopyEdit

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(“SELECT * FROM employees”);

PreparedStatement

  • Used for executing parameterized queries (prevents SQL injection).
  • Example:

java

CopyEdit

PreparedStatement pstmt = con.prepareStatement(“SELECT * FROM employees WHERE id = ?”);

pstmt.setInt(1, 101);

ResultSet rs = pstmt.executeQuery();

CallableStatement

  • Used for calling stored procedures in the database.
  • Example:

java

CopyEdit

CallableStatement cstmt = con.prepareCall(“{call getEmployee(?)}”);

cstmt.setInt(1, 101);

ResultSet rs = cstmt.executeQuery();

Best Practices in JDBC

  • Always close database connections to avoid memory leaks.
  • Use PreparedStatement to prevent SQL injection.
  • Implement connection pooling for better performance.
  • Handle exceptions properly using try-catch-finally.
  • Use batch processing for executing multiple queries efficiently.

SQL (Structured Query Language) is used to interact with relational databases. Below are common SQL queries with explanations.

Data Retrieval (SELECT Query)

Retrieves data from a table.

sql

CopyEdit

SELECT * FROM employees;

SELECT name, salary FROM employees WHERE department = ‘HR’;

Inserting Data (INSERT Query)

Adds new records to a table.

sql

CopyEdit

INSERT INTO employees (id, name, department, salary) VALUES (101, ‘John Doe’, ‘HR’, 60000);

Updating Data (UPDATE Query)

Modifies existing records.

sql

CopyEdit

UPDATE employees SET salary = 70000 WHERE id = 101;

Deleting Data (DELETE Query)

Removes records from a table.

sql

CopyEdit

DELETE FROM employees WHERE id = 101;

Filtering Data with WHERE Clause

Filters results based on conditions.

sql

CopyEdit

SELECT * FROM employees WHERE salary > 50000;

Sorting Data with ORDER BY

Sorts results in ascending or descending order.

sql

CopyEdit

SELECT * FROM employees ORDER BY salary DESC;

Grouping Data with GROUP BY

Groups records and applies aggregate functions.

sql

CopyEdit

SELECT department, COUNT(*) FROM employees GROUP BY department;

Using Aggregate Functions

Performs calculations on a set of values.

sql

CopyEdit

SELECT AVG(salary) FROM employees;

SELECT MAX(salary), MIN(salary) FROM employees;

Using Joins to Combine Tables

Joins data from multiple tables.

sql

CopyEdit

SELECT employees.name, departments.department_name

FROM employees

INNER JOIN departments ON employees.department_id = departments.id;

Using Subqueries

Executes a query within another query.

sql

CopyEdit

SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);

Using CASE Statement

Used for conditional expressions in SQL queries.

sql

CopyEdit

SELECT name, salary,

       CASE 

           WHEN salary > 80000 THEN ‘High Salary’

           WHEN salary BETWEEN 50000 AND 80000 THEN ‘Medium Salary’

           ELSE ‘Low Salary’

       END AS salary_category

FROM employees;

Using Indexes for Performance

Indexes improve query performance by speeding up data retrieval.

sql

CopyEdit

CREATE INDEX idx_salary ON employees(salary);

Using Views

Views act as virtual tables for easier data retrieval.

sql

CopyEdit

CREATE VIEW employee_salaries AS 

SELECT name, department, salary FROM employees;

SQL Syntax Errors

Error: Incorrect SQL syntax
Solution: Always verify SQL statements before execution.

Connection Errors

Error: java.sql.SQLException: No suitable driver found
Solution: Ensure the correct JDBC driver is included in the classpath.

SQL Injection

Error: Application vulnerability due to unsanitized inputs
Solution: Use PreparedStatement instead of Statement to prevent SQL injection.

JDBC is a powerful API for integrating Java applications with relational databases. Understanding SQL queries and best practices ensures secure, efficient, and optimized database interactions. By mastering JDBC and SQL, developers can build robust data-driven applications effortlessly.

2. Complete Guide to Server-Side Processing with Java

Server-side processing refers to handling requests, executing business logic, and generating dynamic responses on the server before sending them to the client. Java is widely used for server-side development due to its platform independence, scalability, and security.

Why Use Java for Server-Side Processing?

  • Cross-platform compatibility: Runs on any OS with JVM.
  • Performance & Scalability: Suitable for large-scale applications.
  • Security: Provides robust authentication and encryption mechanisms.
  • Multi-threading Support: Handles multiple requests simultaneously.

Servlets

Java Servlets are Java programs that run on a web server and handle HTTP requests.

How Servlets Work?

  1. Client sends an HTTP request.
  2. Web server forwards the request to the Servlet container.
  3. Servlet processes the request and generates a response.
  4. Servlet container sends the response back to the client.

Servlet Lifecycle

  • Initialization (init()) – Called when the servlet is first loaded.
  • Request Handling (service()) – Handles client requests using doGet(), doPost(), etc.
  • Destruction (destroy()) – Called before the servlet is removed from memory.

Example: Simple Servlet

java

CopyEdit

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

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, World!</h1>”);

    }

}

JavaServer Pages (JSP)

JSP allows embedding Java code inside HTML to generate dynamic content.

Advantages of JSP

  • Reduces the need for Java code in HTML.
  • Easier to write compared to servlets.
  • Supports reusable components like JavaBeans.

Basic JSP Example

jsp

CopyEdit

<%@ page language=”java” contentType=”text/html” %>

<html>

<body>

    <h2>Hello, <%= request.getParameter(“name”) %>!</h2>

</body>

</html>

JavaBeans

JavaBeans are reusable components that store and process data in JSP applications.

Example of a JavaBean

java

CopyEdit

public class User {

    private String name;

    public void setName(String name) { this.name = name; }

    public String getName() { return name; }

}

JSP can use this bean like:

jsp

CopyEdit

<jsp:useBean id=”user” class=”User” />

<jsp:setProperty name=”user” property=”name” value=”John” />

Hello, <jsp:getProperty name=”user” property=”name” />

JavaServer Faces (JSF)

JSF is a framework for building UI-based Java web applications.

Features of JSF

  • Supports reusable UI components.
  • Uses event-driven programming.
  • Supports managed beans for data handling.

JSF Example (index.xhtml)

xml

CopyEdit

<h:form>

    Enter Name: <h:inputText value=”#{userBean.name}” />

    <h:commandButton value=”Submit” action=”#{userBean.display}” />

    <h:outputText value=”#{userBean.message}” />

</h:form>

JDBC (Java Database Connectivity)

JDBC allows Java applications to connect to databases and execute queries.

JDBC Example (Connecting to MySQL)

java

CopyEdit

import java.sql.*;

public class DatabaseExample {

    public static void main(String[] args) throws Exception {

        Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/testdb”, “root”, “password”);

        Statement stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery(“SELECT * FROM users”);

        while (rs.next()) {

            System.out.println(rs.getString(“name”));

        }

        con.close();

    }

}

Several frameworks make server-side development easier:

Spring Boot

  • Simplifies Java web application development.
  • Built-in support for dependency injection and REST APIs.

Hibernate

  • Simplifies database interactions using Object-Relational Mapping (ORM).
  • Eliminates the need for writing complex SQL queries.

Struts

  • Follows the Model-View-Controller (MVC) architecture.
  • Helps in building scalable enterprise applications.

Handling GET and POST Requests in Servlets

  • doGet() – Handles read requests.
  • doPost() – Handles form submissions.

Example: Handling GET and POST Requests

java

CopyEdit

protected void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    response.getWriter().println(“This is a GET request”);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    String name = request.getParameter(“name”);

    response.getWriter().println(“Hello, ” + name);

}

Preventing SQL Injection

Use PreparedStatement instead of string concatenation.

java

CopyEdit

PreparedStatement pstmt = con.prepareStatement(“SELECT * FROM users WHERE name = ?”);

pstmt.setString(1, userInput);

ResultSet rs = pstmt.executeQuery();

Using Authentication and Authorization

Java EE supports authentication via Servlet Filters and Spring Security.

Securing Data with HTTPS

Use SSL/TLS to encrypt data between the client and server.

Connection Pooling

Reduces the overhead of creating new database connections.

Caching Mechanisms

Use caching libraries like Ehcache to store frequently used data.

Load Balancing

Distribute traffic across multiple servers using Apache Load Balancer or Nginx.

  1. E-Commerce Websites – Amazon, eBay (using Java for handling orders, payments).
  2. Banking Systems – Secure online transactions (JSP & Servlets).
  3. Social Media Platforms – Facebook, LinkedIn (using Spring Boot & Hibernate).
  4. Enterprise Applications – CRM, ERP (using Java EE frameworks).

Server-side processing in Java plays a crucial role in building scalable, secure, and high-performance applications. By using Servlets, JSP, JDBC, JavaBeans, and frameworks like Spring Boot and Hibernate, developers can efficiently manage data and deliver dynamic content.

more from