Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Core Techniques of Java Servlets for Web Development

Tech May 7 3

Client/Server vs Browser/Server Architectures

The Client/Server (C/S) model divides responsibilities between a client interface handling user interaction and a server managing data. Advantages include rich client UI and fast responses. Drawbacks are limited applicability, fixed user base, and costly maintenance requiring updates on every client.

The Browser/Server (B/S) model centralizes business logic on the server, using browsers mainly for interaction. Benefits are zero client installation, broad accessibility via permissions, and low maintenance overhead. Limitations include heavier server load, effort to match rich client features in browsers, and cross-browser compatibility challenges.

JavaWeb Fundamentals

Web resources fall into static (unchanging content) and dynamic (content generated at runtime). JavaWeb denotes Java-based technologies for building dynamic web solutions.

In early B/S setups, clients held preloaded pages while servers handled only data. Modern B/S involves servers delivering both page structures and data dynamically upon each refresh.

HTTP Protocol Essentials

HTTP governs browser-server communication, specifying request and response formats. It typically runs over TCP; HTTPS adds TLS/SSL encryption. Default ports: HTTP 80, HTTPS 443.

Request message structure:

  • Request line: method, URI, protocol version
  • Headers: metadata like host, content length, user-agent
  • Blank line
  • Body: optional payload

Example:

POST /app01/home HTTP/1.1
Host: localhost:8088
Content-Length: 19
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64)

user=jordan&pass=abc123

Response message structure:

  • Status line: protocol version, status code, reason phrase
  • Headers: content type, length, date, etc.
  • Blank line
  • Body: returned resource data

Example:

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 320
Date: Thu, 08 Sep 2021 12:59:54 GMT

<html><body><h1>Sample Page</h1></body></html>

Use browser developer tools (F12 → Network tab) to inspect requests and responses.

Tomcat Server Overview

Tomcat is a lightweight open-source Java web server suited for small-to-medium applications and servlet/JSP development.

Directory layout:

  • bin: executables and scripts
  • conf: configuration files
  • lib: required JARs
  • logs: runtime logs
  • temp: temporary files
  • webapps: deployed web apps
  • work: compiled JSP artifacts

Startup/shutdown: Run startup.bat / shutdown.bat from bin. Ensure JAVA_HOME is defined; optionally set CATALINA_HOME for global invocation.

Default ports: Tomcat 8080, MySQL 3306, HTTP 80. Port conflicts can be diagnosed via netstat -ano and resolved with taskkill /F /PID <id> or registry changes under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP.

Key config file server.xml allows port, domain, and encoding adjustments:

<Connector port="9090" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

tomcat-users.xml defines admin users:

<role rolename="manager-gui"/>
<user username="admin" password="secret" roles="manager-gui"/>

Access localhost:8080 for server status, app management, and virtual host controls.

Servlet Basics

Servlets are Java classes running on servers to handle client requests and produce dynamic responses.

Development steps:

  1. Create a Java web project with Tomcat configured.
  2. Implement Servlet interface or extend HttpServlet, overriding service.
  3. Declare servlet in web.xml or via annotations.

Example using annotation:

@WebServlet(name = "GreetingServlet", urlPatterns = {"/greet"})
public class GreetingServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("<h2>Hello from servlet</h2>");
    }
}

Lifecycle:

  • Constructor: once, on first request
  • init(): once, post construction
  • service(): per request
  • destroy(): once, on undeployment

Request types:

  • GET appends data to URL; limited size, less secure.
  • POST sends data in body; supports large payloads, more secure.

ServletRequest & HttpServletRequest: Provide access to parameters, headers, client info.

ServletResponse & HttpServletResponse: Enable setting content type, encoding, and writing output.

Handling Character Encoding

POST: call request.setCharacterEncoding("UTF-8") before reading parameters.

GET: re-encode manually:

String raw = request.getParameter("field");
String decoded = new String(raw.getBytes("ISO-8859-1"), "UTF-8");

Servlet Configuration Interfaces

ServletConfig provides access to initialization parameters specific to a servlet.

ServletContext represents application-wide scope, allowing shared attributes and access to context-level settings and paths.

Servlet with JDBC

Servlets often interact with databases via JDBC for tasks like listing records or processing forms (registration, login). Encapsulate DB logic in Data Access Objects (DAO).

Example flow:

  1. Servlet receives form data.
  2. Constructs a domain object (e.g., User).
  3. Passes it to DAO for persistence.
  4. Returns outcome to client.

Utility class example:

public class DbConnector {
    private static final String URL = "jdbc:mysql://localhost:3306/appdb";
    private static final String USER = "root";
    private static final String PASS = "pwd";
    static {
        try { Class.forName("com.mysql.cj.jdbc.Driver"); }
        catch (Exception e) { throw new RuntimeException(e); }
    }
    public static Connection getConn() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASS);
    }
}

DAO method:

public int insertUser(User u) throws SQLException {
    String sql = "INSERT INTO users (username, pwd) VALUES (?, ?)";
    try (Connection c = DbConnector.getConn();
         PreparedStatement ps = c.prepareStatement(sql)) {
        ps.setString(1, u.getUsername());
        ps.setString(2, u.getPwd());
        return ps.executeUpdate();
    }
}

Redirection vs Forwarding

Redirection:

  • Triggered via response.sendRedirect(url)
  • Sends 302 status + Location header
  • Client issues a new request to the target URL
  • Original request attributes are lost
  • URL in browser changes

Forwarding:

  • Performed via RequestDispatcher.forward(req, resp)
  • Server internally passes request to another resource
  • Same request/response objects shared
  • Browser URL remains unchanged
  • Limited to same web application context

Thread Safety

By default, one servlet instance handles multiple threads. Shared mutable state requires synchronization to prevent race conditions.

State Management

HTTP is stateless; mechanisms like Cookie and Session maintain state across interactions.

Cookie: Small name-value pairs stored on client side. Created server-side via new Cookie(name, value) and added with response.addCookie(). Sent back by browser on subsequent requests matching path/domain.

Control lifespan with setMaxAge(seconds): positive for expiry duration, negative for session-only, zero to delete immediately.

Session: Server-side storage tied to a unique session ID sent via cookie (JSESSIONID). Retrieved with request.getSession(). Attributes manipulated via setAttribute, getAttribute, removeAttribute.

Session timeout defaults to 30 minutes; configurable in web.xml:

<session-config>
    <session-timeout>15</session-timeout>
</session-config>

Sessions consume server memory; unsuitable for massive data volumes.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.