How do I understand coordinates in a 2D game?

In the previous tutorial, How do I draw 2D shapes using Graphics2D?, we learned how to draw lines, rectangles, circles, and polygons using Java Swing. We also created a simple robot character using geometric shapes.

However, there is something important behind every drawing operation: coordinates.

Coordinates determine where objects appear on the screen. They are also essential for player movement, collision detection, camera scrolling, and many other game mechanics.

In this tutorial, we will learn how the Java 2D coordinate system works and create an interactive application that displays object coordinates.

By the end of this tutorial, you will understand how to:

  • Work with X and Y coordinates.
  • Understand the direction of the coordinate axes.
  • Position objects using absolute and relative coordinates.
  • Calculate the center of an object.
  • Keep an object inside the game area.
  • Calculate distances between objects.
  • Convert mouse positions into game object positions.

We will continue using Java 25, Java Swing, and Apache Maven.

1. Understanding the coordinate system

In Java Swing, the default coordinate system starts at the upper-left corner of a component.

This location is called the origin and has the coordinates:

(0, 0)

The horizontal axis is called the X-axis, and the vertical axis is called the Y-axis.

The important difference from a traditional mathematical graph is that Y increases downward.

For example, in an 800 × 600 game panel:

Coordinate Location
(0, 0) Upper-left corner
(400, 300) Center
(100, 100) 100 pixels right and 100 pixels down
(799, 599) Bottom-right pixel

The last example assumes integer pixel coordinates in an 800 × 600 drawing area.

Understanding these directions is essential because moving an object upward requires decreasing its Y coordinate.

Moving it downward requires increasing its Y coordinate.

2. Drawing an object at a specific position

Let’s start with a simple rectangle.

g2d.fillRect(100, 150, 50, 50);

The fillRect() method accepts four parameters:

fillRect(x, y, width, height);

The first two parameters represent the position of the rectangle’s upper-left corner.

The remaining parameters define its size.

In our example:

int x = 100;
int y = 150;
int width = 50;
int height = 50;

The rectangle begins at coordinate (100, 150) and extends 50 pixels to the right and 50 pixels downward.

We can make our program easier to understand by storing these values in variables:

int playerX = 100;
int playerY = 150;
int playerWidth = 50;
int playerHeight = 50;

g2d.fillRect(
        playerX,
        playerY,
        playerWidth,
        playerHeight);

This approach is useful because the object’s position can be changed without modifying the drawing statement.

Later, we will update these variables to make our player move.

3. Understanding absolute and relative coordinates

There are two useful ways to position objects: absolute coordinates and relative coordinates.

Absolute coordinates

Absolute coordinates represent positions relative to the coordinate system’s origin.

For example:

g2d.fillRect(100, 100, 50, 50);
g2d.fillRect(300, 200, 50, 50);

Both rectangles have fixed positions.

Relative coordinates

Relative coordinates describe positions based on another object’s location.

Consider the robot we created in previuos tutorial.

Instead of assigning independent coordinates to its eyes, arms, and legs, we calculated their positions relative to the robot’s position.

For example:

int robotX = 200;
int robotY = 150;

g2d.fillRect(robotX, robotY, 100, 100);

g2d.fillOval(
        robotX + 20,
        robotY + 25,
        15,
        15);

g2d.fillOval(
        robotX + 65,
        robotY + 25,
        15,
        15);

The rectangle represents the robot’s head, and the circles represent its eyes.

If we change robotX or robotY, the eyes move with the head.

This makes relative coordinates extremely useful for drawing complex objects.

4. Calculating the center of an object

In many games, we need to know the center of an object rather than its upper-left corner.

Consider a player with the following properties:

int playerX = 100;
int playerY = 150;
int playerWidth = 50;
int playerHeight = 50;

We can calculate the player’s center using:

double centerX = playerX + playerWidth / 2.0;
double centerY = playerY + playerHeight / 2.0;

The result is:

centerX = 125
centerY = 175

Why is this useful?

The center of an object can help us determine distances, rotate objects, position projectiles, and detect certain types of collisions.

For example, if we want to draw a small circle at the player’s center:

g2d.setColor(Color.RED);

g2d.fillOval(
        (int) centerX - 5,
        (int) centerY - 5,
        10,
        10);

We subtract 5 from each coordinate because fillOval() also uses the upper-left corner of the oval’s bounding rectangle.

The result is a red circle centered inside the player.

5. Positioning an object in the center of the game window

Suppose our game panel is 800 pixels wide and 600 pixels high.

Our player is a 50 × 50 square.

To center the player, calculate:

int playerX = (800 - 50) / 2;
int playerY = (600 - 50) / 2;

The resulting position is:

playerX = 375
playerY = 275

The player’s center is located at (400, 300).

Instead of hardcoding the panel dimensions, we can use:

int playerX = (getWidth() - playerWidth) / 2;
int playerY = (getHeight() - playerHeight) / 2;

This approach is useful when the game window can be resized.

Note: getWidth() and getHeight() return the actual dimensions of the component. These values may be zero before the component has been laid out.

For this reason, we normally calculate positions based on these methods after the panel has been displayed, or during painting when its dimensions are available.

6. Keeping an object inside the game area

Imagine that our player can move around the screen.

Without boundaries, the player might move outside the visible game area.

We can prevent this by limiting its position.

For example:

playerX = Math.max(
        0,
        Math.min(playerX, gameWidth - playerWidth));

playerY = Math.max(
        0,
        Math.min(playerY, gameHeight - playerHeight));

Let’s understand the first expression.

Math.min(playerX, gameWidth - playerWidth)

This ensures that the player’s X position does not exceed the right boundary.

Then:

Math.max(0, ...)

Prevents the position from becoming negative.

We use the same approach for the Y coordinate.

This operation is commonly called clamping.

Clamping values is a useful technique in game programming because it restricts numbers to a specific range.

7. Calculating distances between objects

Another important use of coordinates is calculating the distance between two points.

Suppose we have two objects located at:

double x1 = 100;
double y1 = 100;

double x2 = 400;
double y2 = 300;

We can calculate the distance using the Pythagorean theorem.

The formula is:

d = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2}

Java provides the Math.hypot() method to perform this calculation:

double dx = x2 - x1;
double dy = y2 - y1;

double distance = Math.hypot(dx, dy);

For the points in our example, the distance is approximately:

360.56 pixels

Distance calculations are useful in many game mechanics.

For example, we can use them to determine whether a player is close enough to collect an item, interact with an object, or trigger an enemy’s detection range.

For circular objects, distances between centers are also useful for collision detection.

8. Creating an interactive coordinate explorer

Now that we understand the basic concepts, let’s create an interactive application.

Our application will display a player represented by a blue square.

When the user clicks anywhere inside the game panel, the player moves to the clicked position.

The application will also display:

  • The player’s X and Y coordinates.
  • The player’s center coordinates.
  • The latest mouse click coordinates.
  • The distance between the player and the mouse cursor.

This will help us visualize how coordinates work in Java 2D.

Project structure

We will continue using the same project structure:

java-2d-game/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── org/
                └── kodejava/
                    └── game/
                        ├── Game.java
                        ├── GameWindow.java
                        └── GamePanel.java

Creating GamePanel.java

Replace the contents of GamePanel.java with the following code:

package org.kodejava.game;

import javax.swing.JPanel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

public class GamePanel extends JPanel {

    public static final int GAME_WIDTH = 800;
    public static final int GAME_HEIGHT = 600;

    private static final int PLAYER_SIZE = 50;

    private int playerX = 375;
    private int playerY = 275;

    private Point mousePosition = new Point(400, 300);
    private Point lastClick = new Point(400, 300);

    public GamePanel() {
        setPreferredSize(new Dimension(
                GAME_WIDTH, GAME_HEIGHT));

        setBackground(new Color(15, 23, 42));
        setDoubleBuffered(true);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                movePlayerTo(e.getX(), e.getY());
            }
        });

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                mousePosition = e.getPoint();
                repaint();
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                mousePosition = e.getPoint();
                repaint();
            }
        });
    }

    private void movePlayerTo(int mouseX, int mouseY) {
        lastClick = new Point(mouseX, mouseY);
        mousePosition = new Point(mouseX, mouseY);

        playerX = mouseX - PLAYER_SIZE / 2;
        playerY = mouseY - PLAYER_SIZE / 2;

        int maxX = Math.max(0, getWidth() - PLAYER_SIZE);
        int maxY = Math.max(0, getHeight() - PLAYER_SIZE);

        playerX = Math.max(0, Math.min(playerX, maxX));
        playerY = Math.max(0, Math.min(playerY, maxY));

        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g.create();

        try {
            g2d.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            drawGrid(g2d);
            drawPlayer(g2d);
            drawMouseMarker(g2d);
            drawInformation(g2d);
        } finally {
            g2d.dispose();
        }
    }

    private void drawGrid(Graphics2D g2d) {
        g2d.setColor(new Color(51, 65, 85));
        g2d.setStroke(new BasicStroke(1.0f));

        int gridSize = 50;

        for (int x = 0; x < getWidth(); x += gridSize) {
            g2d.drawLine(x, 0, x, getHeight());
        }

        for (int y = 0; y < getHeight(); y += gridSize) {
            g2d.drawLine(0, y, getWidth(), y);
        }
    }

    private void drawPlayer(Graphics2D g2d) {
        g2d.setColor(new Color(59, 130, 246));

        g2d.fillRoundRect(
                playerX,
                playerY,
                PLAYER_SIZE,
                PLAYER_SIZE,
                10,
                10);

        double centerX = playerX + PLAYER_SIZE / 2.0;
        double centerY = playerY + PLAYER_SIZE / 2.0;

        g2d.setColor(Color.WHITE);

        g2d.fillOval(
                (int) centerX - 4,
                (int) centerY - 4,
                8,
                8);
    }

    private void drawMouseMarker(Graphics2D g2d) {
        g2d.setColor(new Color(250, 204, 21));

        int x = mousePosition.x;
        int y = mousePosition.y;

        g2d.drawOval(x - 6, y - 6, 12, 12);
        g2d.drawLine(x - 12, y, x + 12, y);
        g2d.drawLine(x, y - 12, x, y + 12);
    }

    private void drawInformation(Graphics2D g2d) {
        g2d.setFont(new Font(
                Font.MONOSPACED, Font.PLAIN, 14));

        double centerX = playerX + PLAYER_SIZE / 2.0;
        double centerY = playerY + PLAYER_SIZE / 2.0;

        double distance = Math.hypot(
                mousePosition.x - centerX,
                mousePosition.y - centerY);

        // Panel background for readable information
        g2d.setColor(new Color(15, 23, 42, 235));
        g2d.fillRoundRect(15, 15, 410, 145, 12, 12);

        g2d.setColor(Color.WHITE);

        g2d.drawString(
                "Java 2D Coordinate Explorer",
                30, 40);

        g2d.drawString(
                "Player: (" + playerX + ", " + playerY + ")",
                30, 65);

        g2d.drawString(
                "Center: (" + centerX + ", " + centerY + ")",
                30, 85);

        g2d.drawString(
                "Last click: (" + lastClick.x +
                        ", " + lastClick.y + ")",
                30, 105);

        g2d.drawString(
                "Distance to mouse: %.2f px"
                        .formatted(distance),
                30, 125);

        g2d.drawString(
                "Click anywhere to move the player",
                30, 145);
    }
}

How does the mouse listener work?

The following code registers a mouse listener:

addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        movePlayerTo(e.getX(), e.getY());
    }
});

Whenever the user presses a mouse button inside the panel, Swing invokes the mousePressed() method.

The event object provides the mouse coordinates relative to the component.

We use these coordinates to update the player’s position.

Why subtract half the player size?

Inside movePlayerTo(), we calculate the player position using:

playerX = mouseX - PLAYER_SIZE / 2;
playerY = mouseY - PLAYER_SIZE / 2;

Remember that fillRect() and fillRoundRect() expect the upper-left corner of the rectangle.

If we assigned the mouse coordinates directly to playerX and playerY, the player’s upper-left corner would appear at the mouse position.

By subtracting half the player’s width and height, we place the center of the player at the clicked position.

This works exactly for a player with an even size such as our 50 × 50 square, provided it does not need to be clamped at the panel boundaries.

Why call repaint()?

After updating the player’s position, we call:

repaint();

This requests that Swing repaint the component.

The repaint operation is scheduled by Swing rather than necessarily happening immediately.

When Swing processes the repaint request, our paintComponent() method is called, and the player is drawn at its updated position.

The repaint() method is one of the most important methods when creating interactive Swing applications.

Later, when we introduce a game loop, we will request repaints as the game state changes over time.

Understanding mouse movement

We also register a mouse motion listener.

addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseMoved(MouseEvent e) {
        mousePosition = e.getPoint();
        repaint();
    }
});

The mouseMoved() method is invoked when the mouse moves inside the panel without a button pressed.

We store the current mouse position and request a repaint.

This allows the application to display the distance between the player and the mouse cursor.

The example also handles mouseDragged() so that the marker updates while a mouse button is held down.

9. Creating GameWindow.java

The GameWindow class remains similar to the one from Week 02.

package org.kodejava.game;

import javax.swing.JFrame;

public class GameWindow extends JFrame {

    public GameWindow() {
        setTitle("Java 2D Coordinate Explorer");

        setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);

        setContentPane(new GamePanel());

        pack();
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }
}

We use the GamePanel as the content pane and let pack() size the frame according to the panel’s preferred dimensions.

10. Creating Game.java

Our application entry point remains unchanged:

package org.kodejava.game;

import javax.swing.SwingUtilities;

public class Game {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(GameWindow::new);
    }
}

Using SwingUtilities.invokeLater() ensures that our Swing window is created on the Event Dispatch Thread.

11. Running the program

Open a terminal in the project directory and compile the application:

mvn clean compile

Then run it:

java -cp target/classes org.kodejava.game.Game

Coordinate Explorer

The program opens a window displaying a coordinate grid and a blue square representing the player.

Move your mouse around the game panel. You will see a yellow crosshair following the cursor.

Click anywhere in the panel to move the player to that location.

The information panel displays the player’s position, center coordinates, last click position, and distance to the mouse.

Try clicking near the edges of the game window.

Notice that the player remains inside the visible area because we clamp its position.

12. Understanding coordinate boundaries

Let’s look more closely at how boundaries work.

For an 800 × 600 game area and a 50 × 50 player:

Minimum X = 0
Maximum X = 800 - 50 = 750

Minimum Y = 0
Maximum Y = 600 - 50 = 550

This means the player’s upper-left corner must remain within the following range:

0 <= playerX <= 750
0 <= playerY <= 550

If we allowed playerX to become 780, only part of the player would be visible.

By limiting the position to 750, we ensure that the entire 50-pixel-wide player fits inside the 800-pixel-wide panel.

These calculations become especially important when implementing player movement.

13. Understanding coordinate spaces

So far, we have worked with coordinates relative to a single JPanel.

In larger games, however, we often use several coordinate spaces.

The most common ones are:

Screen coordinates

These describe positions on the physical display or within a window.

Component coordinates

These describe positions relative to a Swing component, such as our GamePanel.

World coordinates

These describe positions inside the game world, which can be larger than the visible game area.

For example, imagine a platform game with a world that is 5,000 pixels wide but a window that is only 800 pixels wide.

A player might have a world X coordinate of 2,000, even though the visible window is only 800 pixels wide.

We can use a camera position to convert world coordinates into screen coordinates.

A simplified conversion looks like this:

int screenX = worldX - cameraX;
int screenY = worldY - cameraY;

We will explore this concept in greater detail when we build scrolling game worlds and tile-based maps.

For now, our game uses component coordinates directly.

14. Try it yourself

Before continuing to the next tutorial, try the following exercises.

Exercise 1: Change the player size

Modify:

private static final int PLAYER_SIZE = 50;

Try using 80 or 100 instead.

Observe how the boundary calculations keep the larger player inside the game area.

Exercise 2: Display the player’s bottom-right coordinate

Calculate the bottom-right corner:

int right = playerX + PLAYER_SIZE;
int bottom = playerY + PLAYER_SIZE;

Display these values in the information panel.

Exercise 3: Draw a line from the player to the mouse

Inside paintComponent(), add a method that draws a line between the player’s center and the current mouse position.

For example:

g2d.setColor(Color.GREEN);

g2d.drawLine(
        playerX + PLAYER_SIZE / 2,
        playerY + PLAYER_SIZE / 2,
        mousePosition.x,
        mousePosition.y);

Remember that drawing order matters.

Draw the line before drawing the player if you want the player to appear on top of it.

Exercise 4: Create a collectible object

Add a yellow circle at position (600, 400).

Calculate the distance between the player’s center and the circle’s center.

Display a message when the distance is less than 60 pixels.

For this exercise, we are using a distance threshold rather than checking whether the actual shapes overlap.

We will learn about collision detection in a later tutorial.

15. Summary

In this tutorial, we learned how coordinates work in Java 2D game programming.

We covered:

  • The Java Swing coordinate system.
  • The difference between X and Y coordinates.
  • Absolute and relative positioning.
  • Calculating the center of an object.
  • Centering an object in the game window.
  • Keeping objects inside the visible game area.
  • Calculating distances using Math.hypot().
  • Handling mouse coordinates.
  • Updating object positions and requesting repaints.
  • Understanding component, screen, and world coordinates.

We also created an interactive coordinate explorer that allows us to move a player around the game area using the mouse.

These concepts form the foundation for player movement, collision detection, and camera systems.

In the next tutorial, How do I handle keyboard input in a Java game?, we will learn how to use keyboard events to control our game objects.

We will introduce Swing key bindings and create a simple input system that prepares our project for player movement.

Maven Dependencies

Java Swing, Java 2D, and the event-handling classes used in this tutorial are included in the JDK.

No external game libraries are required.

The complete pom.xml is shown below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
             http://maven.apache.org/POM/4.0.0
             https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kodejava</groupId>
    <artifactId>java-2d-game</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
            </plugin>
        </plugins>
    </build>
</project>

Required Maven dependencies: None.

Build plugin:

org.apache.maven.plugins:maven-compiler-plugin:3.14.1

References

How do I handle a button click in Java Swing?

Use addActionListener() to run code when a JButton is activated. In this example, clicking a button changes the text of a label in the same window.

Source code

Save the following code as ButtonClickExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class ButtonClickExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JLabel message = new JLabel(
                "Click the button.", SwingConstants.CENTER);
        JButton button = new JButton("Click me");

        button.addActionListener(event ->
                message.setText("Button clicked!"));

        JPanel panel = new JPanel(new BorderLayout(0, 12));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 30, 20, 30));
        panel.add(message, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(button);
        panel.add(buttonPanel, BorderLayout.PAGE_END);

        JFrame frame = new JFrame("Button Click");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration showing the label before and after clicking the Swing button

Explanation

The JLabel starts with the text Click the button.. The JButton displays Click me. This line connects the button to the label:

button.addActionListener(event ->
        message.setText("Button clicked!"));

addActionListener() registers a listener that Swing calls when the button is activated. The lambda is the listener in this example. Its event parameter receives information about the action, but the example only needs to update the label, so it does not use that parameter.

When the listener runs, message.setText() changes the existing label. It works whether you click the button with a mouse or activate it with the keyboard.

SwingUtilities.invokeLater() creates the window on the event dispatch thread. Swing also runs the listener on that thread, so it can update the label directly. Keep listeners short so the window stays responsive.

Run the example

javac ButtonClickExample.java
java ButtonClickExample

The window opens with the message Click the button.. Click Click me and the label changes to Button clicked!.

How do I open a Swing window on the event dispatch thread in Java?

Use SwingUtilities.invokeLater() to create and show a Swing window on the event dispatch thread (EDT). Swing uses this thread to process events such as mouse clicks and to update the interface.

This example opens a window and prints whether the code that creates it is running on the EDT.

Source code

Save the following code as SwingEdtExample.java:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class SwingEdtExample {
    void main() {
        IO.println("main() on the EDT: "
                + SwingUtilities.isEventDispatchThread());

        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        IO.println("showWindow() on the EDT: "
                + SwingUtilities.isEventDispatchThread());

        JFrame frame = new JFrame("Hello, Swing!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JLabel("Welcome to Swing", SwingConstants.CENTER));
        frame.setSize(400, 240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Hello Swing!

The window looks like the one in the previous example. The console messages show which thread runs each method.

Explanation

When you launch the program, main() runs outside the EDT. It schedules the showWindow() method with this line:

SwingUtilities.invokeLater(this::showWindow);

The method reference this::showWindow supplies the task. invokeLater() puts that task on Swing’s event queue and returns without waiting. The EDT runs the task when it reaches the front of the queue.

The showWindow() method creates the frame and label, adds the label to the frame, and makes the window visible. All of those steps run on the EDT. Calling showWindow() directly from main() would run those steps on the main thread instead.

SwingUtilities.isEventDispatchThread() checks the thread that is running the current code. It returns false in main() and true in showWindow().

Run the example

javac SwingEdtExample.java
java SwingEdtExample

The console prints:

main() on the EDT: false
showWindow() on the EDT: true

Keep work on the EDT short. A slow operation, such as downloading a file, can keep Swing from responding to clicks or repainting the window. Run slow work in the background and send interface updates back to the EDT.

How do I understand the DispatcherServlet in Spring MVC?

In the previous tutorial, we created our first Spring MVC application using Java configuration, Maven, and Apache Tomcat. We registered a DispatcherServlet, created a controller, and displayed a JSP page in the browser.

But what actually happens when a browser sends an HTTP request to a Spring MVC application? How does Spring MVC know which controller method to execute? How does it generate an HTML page or write data directly to the HTTP response?

In this tutorial, we will explore the DispatcherServlet and the components involved in processing HTTP requests. We will also create a simple application that allows us to observe the request-processing flow.

1. What is the DispatcherServlet?

The DispatcherServlet is the central servlet in Spring MVC. It receives incoming HTTP requests mapped to it and coordinates the components responsible for processing those requests.

It implements a design pattern known as the Front Controller Pattern.

Instead of creating a separate servlet for every application feature, Spring MVC uses a central servlet to delegate requests to the appropriate controllers.

For example, consider the following application endpoints:

GET /products
GET /customers
GET /orders

Each endpoint may be handled by a different controller. However, all these requests can enter the application through the same DispatcherServlet.

The DispatcherServlet does not contain the application’s business logic. Its responsibility is to coordinate request processing.

2. The Front Controller Pattern

The Front Controller Pattern provides a centralized entry point for handling requests in a web application.

Without a front controller, we might need to create and register multiple servlets manually:

/products  --> ProductServlet
/customers --> CustomerServlet
/orders    --> OrderServlet

With Spring MVC, the requests are handled through the DispatcherServlet:

DispatcherServlet

This approach allows Spring MVC to provide common functionality, such as request mapping, parameter conversion, exception handling, and response generation, without requiring developers to implement these features separately in every controller.

3. Main Components of the DispatcherServlet

The DispatcherServlet works with several components to process HTTP requests.

Component Responsibility
DispatcherServlet Coordinates request processing.
HandlerMapping Finds the handler associated with an HTTP request.
HandlerAdapter Executes the selected handler.
HandlerInterceptor Intercepts requests before and after handler execution.
Controller Processes application requests.
Model Holds data to be displayed by a view.
ViewResolver Resolves a logical view name into a view.
View Renders the response using model data.
HttpMessageConverter Reads and writes HTTP message bodies.
HandlerExceptionResolver Handles exceptions during request processing.

Let’s examine the most important components.

HandlerMapping

The HandlerMapping determines which handler should process an incoming request.

For annotation-based controllers, Spring MVC uses the RequestMappingHandlerMapping class.

Consider the following controller method:

@GetMapping("/hello")
public String hello() {
    return "hello";
}

When Spring MVC receives a GET request for /hello, the handler mapping identifies the hello() method as the appropriate handler.

HandlerAdapter

After finding the handler, the DispatcherServlet delegates its execution to a HandlerAdapter.

For annotation-based controllers, Spring MVC uses RequestMappingHandlerAdapter.

This component performs several tasks, including:

  • Resolving controller method arguments.
  • Converting request parameters into Java types.
  • Invoking the controller method.
  • Processing the method’s return value.

For example:

@GetMapping("/hello")
public String hello(Model model) {
    model.addAttribute("message", "Hello!");
    return "hello";
}

Spring MVC automatically provides the Model argument when invoking the method.

ViewResolver

A ViewResolver converts a logical view name into a view that can render the response.

For example, if a controller returns:

return "hello";

An InternalResourceViewResolver configured with a prefix of /WEB-INF/views/ and a suffix of .jsp resolves the view to:

/WEB-INF/views/hello.jsp

HttpMessageConverter

Not every Spring MVC request requires a view.

A controller method annotated with @ResponseBody can write its return value directly to the HTTP response.

@GetMapping("/message")
@ResponseBody
public String message() {
    return "Hello, Spring MVC!";
}

Spring MVC uses an appropriate HttpMessageConverter to write the returned value to the response body.

In this example, the StringHttpMessageConverter can write the returned string as plain text.

For Java objects, Spring MVC can use a JSON message converter when the necessary JSON library is available.

HandlerExceptionResolver

The HandlerExceptionResolver provides a mechanism for handling exceptions that occur during request processing.

For example, it can help Spring MVC convert an exception into an appropriate HTTP error response or an error view.

We will explore exception handling in more detail in a later tutorial.

4. Understanding the Request Processing Flow

A typical Spring MVC request that returns an HTML page follows these steps:

  1. The client sends an HTTP request.
  2. The servlet container forwards the request to the DispatcherServlet.
  3. The DispatcherServlet uses a HandlerMapping to find the appropriate controller method.
  4. The DispatcherServlet delegates handler execution to a HandlerAdapter.
  5. The controller processes the request and returns a logical view name.
  6. The DispatcherServlet uses a ViewResolver to resolve the view.
  7. The view renders the response using the model data.
  8. The response is returned to the client.

When a controller uses @ResponseBody, the handler adapter can write the response through an HTTP message converter. In this case, the view resolution and rendering steps are not required.

5. Creating the Example Application

To understand how these components work together, we will create a Spring MVC application with two endpoints:

  • /hello — returns an HTML page using a JSP view.
  • /message — returns a plain-text response.

We will also register a simple interceptor to observe the request-processing lifecycle.

This example uses the following technologies:

Technology Version
Java 25
Spring Framework 7.1.0
Jakarta Servlet API 6.1.0
Apache Tomcat 11.x
Apache Maven 3.9 or later

We will continue using traditional Spring MVC without Spring Boot.

6. Project Structure

Create a Maven project named spring-mvc-dispatcher.

The project has the following directory structure:

spring-mvc-dispatcher/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── org/kodejava/springmvc/
        │       ├── config/
        │       │   ├── WebConfig.java
        │       │   └── WebAppInitializer.java
        │       ├── controller/
        │       │   └── HelloController.java
        │       └── interceptor/
        │           └── RequestLoggingInterceptor.java
        └── webapp/
            └── WEB-INF/
                └── views/
                    └── hello.jsp

7. Configuring Maven

Create the following pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
             http://maven.apache.org/POM/4.0.0
             https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kodejava</groupId>
    <artifactId>spring-mvc-dispatcher</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>7.1.0</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring-mvc-dispatcher</finalName>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.5.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The spring-webmvc dependency provides the Spring MVC infrastructure.

The Jakarta Servlet API uses the provided scope because Apache Tomcat provides the servlet implementation at runtime.

8. Registering the DispatcherServlet

Create the WebAppInitializer.java class.

package org.kodejava.springmvc.config;

import org.springframework.web.servlet.support
        .AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

When Tomcat starts the application, Spring’s servlet initialization mechanism discovers this class and registers the DispatcherServlet.

The getServletConfigClasses() method specifies the configuration class used by the servlet’s application context.

The getServletMappings() method maps the servlet to /.

This mapping allows the DispatcherServlet to handle our application endpoints while JSP requests can still be handled by the container’s JSP servlet.

9. Creating a Request Logging Interceptor

To observe request processing, we will implement the HandlerInterceptor interface.

Create the RequestLoggingInterceptor.java class.

package org.kodejava.springmvc.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.jspecify.annotations.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class RequestLoggingInterceptor
        implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {

        System.out.println("[1] preHandle");

        System.out.printf(
                "    Request: %s %s%n",
                request.getMethod(),
                request.getRequestURI()
        );

        if (handler instanceof HandlerMethod method) {
            System.out.printf(
                    "    Handler: %s.%s()%n",
                    method.getBeanType().getSimpleName(),
                    method.getMethod().getName()
            );
        }

        return true;
    }

    @Override
    public void postHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            @Nullable ModelAndView modelAndView) {

        System.out.println("[3] postHandle");

        if (modelAndView != null) {
            System.out.println(
                    "    View: " + modelAndView.getViewName()
            );
        } else {
            System.out.println("    No ModelAndView");
        }
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            @Nullable Exception ex) {

        System.out.println("[4] afterCompletion");
        System.out.println(
                "    HTTP status: " + response.getStatus()
        );
    }
}

The HandlerInterceptor interface provides three callback methods.

preHandle()

The preHandle() method is called after Spring MVC selects a handler but before the handler is executed.

Returning true allows request processing to continue.

Returning false stops the normal handler execution chain.

postHandle()

The postHandle() method is called after successful handler execution.

For a controller that returns a view, this method is normally called before the view is rendered.

The ModelAndView argument contains the model and view information when available.

For a controller that writes directly to the response body, the argument is normally null.

afterCompletion()

The afterCompletion() method is called when request processing completes, provided the interceptor’s preHandle() method completed successfully and returned true.

This method is useful for cleanup and request logging.

In this example, we use System.out.println() to keep the code simple. Production applications should use a proper logging framework.

10. Configuring Spring MVC

Create the WebConfig.java class.

package org.kodejava.springmvc.config;

import org.kodejava.springmvc.interceptor.RequestLoggingInterceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("org.kodejava.springmvc.controller")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        var resolver = new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestLoggingInterceptor())
                .addPathPatterns("/hello", "/message");
    }
}

The @EnableWebMvc annotation enables Spring MVC infrastructure, including handler mappings, handler adapters, and message converters.

The viewResolver() method configures JSP view resolution.

The addInterceptors() method registers our custom interceptor for the /hello and /message endpoints.

The interceptor allows us to observe the request-processing lifecycle without modifying the DispatcherServlet itself.

11. Creating the Controller

Create the HelloController.java class.

package org.kodejava.springmvc.controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        System.out.println("[2] Controller: hello()");

        model.addAttribute(
                "message",
                "Hello from DispatcherServlet!"
        );

        return "hello";
    }

    @GetMapping(
            value = "/message",
            produces = MediaType.TEXT_PLAIN_VALUE
    )
    @ResponseBody
    public String message() {
        System.out.println("[2] Controller: message()");

        return "This response does not require a view.";
    }
}

The controller contains two methods that demonstrate different response-processing mechanisms.

The hello() method adds data to the model and returns a logical view name.

The message() method uses @ResponseBody to write a string directly to the HTTP response.

Although both methods return a String, Spring MVC processes their return values differently.

Method Return value interpretation
hello() Logical view name
message() HTTP response body

The @ResponseBody annotation is what makes the difference.

12. Creating the JSP View

Create the hello.jsp file under the src/main/webapp/WEB-INF/views directory.

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring MVC DispatcherServlet</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f8fafc;
            color: #1e293b;
            margin: 40px;
        }

        main {
            max-width: 640px;
            margin: 60px auto;
            padding: 32px;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
        }

        h1 {
            color: #2563eb;
        }

        code {
            background: #f1f5f9;
            padding: 3px 6px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <main>
        <h1>${message}</h1>

        <p>
            This page is rendered using a JSP view.
        </p>

        <p>
            The request is processed by the
            <code>DispatcherServlet</code>.
        </p>
    </main>
</body>
</html>

The ${message} expression retrieves the model attribute provided by the controller.

Because the message is a fixed application-defined string, this example does not involve untrusted user input. When displaying user-provided values, make sure to escape the output appropriately.

13. Building and Running the Application

Open a terminal in the project directory and execute:

mvn clean package

After Maven completes the build, the generated WAR file is located at:

target/spring-mvc-dispatcher.war

Copy the WAR file into the webapps directory of Apache Tomcat 11.

On Linux or macOS:

cp target/spring-mvc-dispatcher.war \
   "$CATALINA_HOME/webapps/"

On Windows PowerShell:

Copy-Item target/spring-mvc-dispatcher.war `
    "$env:CATALINA_HOME\webapps\"

These commands assume that the CATALINA_HOME environment variable points to your Tomcat installation directory.

Start Tomcat in foreground mode so that you can observe the interceptor output directly in the terminal.

On Linux or macOS:

"$CATALINA_HOME/bin/catalina.sh" run

On Windows PowerShell:

& "$env:CATALINA_HOME\bin\catalina.bat" run

Make sure Tomcat is running with Java 25 because our application is compiled for Java 25.

14. Testing the HTML Response

Open your browser and visit:

http://localhost:8080/spring-mvc-dispatcher/hello

The browser should display:

Spring MVC Dispatcher

The Tomcat console should contain output similar to the following:

[1] preHandle
    Request: GET /spring-mvc-dispatcher/hello
    Handler: HelloController.hello()
[2] Controller: hello()
[3] postHandle
    View: hello
[4] afterCompletion
    HTTP status: 200

The output shows that Spring MVC has selected the hello() method before calling the interceptor’s preHandle() method.

The controller is then executed, followed by the postHandle() method.

After the JSP view has been rendered, the afterCompletion() method is called.

15. Testing the Plain-Text Response

Open the following URL:

http://localhost:8080/spring-mvc-dispatcher/message

The browser should display:

Plain-Text Response

The Tomcat console should contain output similar to the following:

[1] preHandle
    Request: GET /spring-mvc-dispatcher/message
    Handler: HelloController.message()
[2] Controller: message()
[3] postHandle
    No ModelAndView
[4] afterCompletion
    HTTP status: 200

Notice that the postHandle() method does not receive a ModelAndView object.

This happens because the controller uses @ResponseBody.

The handler adapter processes the return value using an HTTP message converter rather than returning a logical view name to the DispatcherServlet.

We can also test this endpoint using curl:

curl -i http://localhost:8080/spring-mvc-dispatcher/message

The response should be similar to:

HTTP/1.1 200
Content-Type: text/plain;charset=ISO-8859-1

This response does not require a view.

The actual response headers, including the character encoding, may vary depending on the Spring MVC and servlet container configuration.

16. Comparing View Rendering and Response Body Processing

Our application demonstrates two common ways of generating HTTP responses.

View Rendering and Response Body Processing

When a controller returns a logical view name, the processing flow includes view resolution and rendering.

When a controller uses @ResponseBody, the response is generated through an HTTP message converter during handler adapter execution.

Simplified DipatcherServlet Processing Flow

These diagrams are simplified. The DispatcherServlet coordinates the components rather than simply passing the request from one component to the next.

The important difference is that response body processing does not require a ViewResolver.

This mechanism is commonly used when building REST APIs.

17. What Happens When No Handler Is Found?

Try accessing an endpoint that does not exist:

http://localhost:8080/spring-mvc-dispatcher/unknown

The application should return an HTTP 404 response.

This happens because Spring MVC cannot find a handler for the requested path.

Similarly, sending a POST request to an endpoint that only supports GET normally produces an HTTP 405 response.

curl -i -X POST \
    http://localhost:8080/spring-mvc-dispatcher/hello

Expected HTTP status:

405 Method Not Allowed

These examples demonstrate that Spring MVC considers both the request path and the HTTP method when selecting a handler.

18. Summary

In this tutorial, we learned how the DispatcherServlet coordinates HTTP request processing in Spring MVC.

We explored the following concepts:

  • The Front Controller Pattern.
  • The role of the DispatcherServlet.
  • Finding controllers using HandlerMapping.
  • Executing controllers using HandlerAdapter.
  • Observing request processing using HandlerInterceptor.
  • Rendering HTML pages using ViewResolver.
  • Writing response bodies using HttpMessageConverter.
  • Understanding the difference between view names and response bodies.
  • Handling requests that do not match a controller.

Understanding the DispatcherServlet provides a strong foundation for learning more advanced Spring MVC features.

In the next tutorial, How do I configure Spring MVC using Java configuration?, we will explore WebMvcConfigurer, application context configuration, static resources, and other configuration options in more detail.

19. Maven Artifacts

The following Maven artifacts are required for this example.

Spring Web MVC

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>7.1.0</version>
</dependency>

Maven coordinates:

org.springframework:spring-webmvc:7.1.0

Jakarta Servlet API

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven coordinates:

jakarta.servlet:jakarta.servlet-api:6.1.0

Maven Compiler Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.14.1</version>
</plugin>

Maven WAR Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.5.0</version>
</plugin>

Other required Spring modules and JSpecify annotations are available through Spring’s transitive dependencies.

References

How do I implement the Prototype pattern in Java?

Suppose an application creates monthly sales reports with the same initial sections. A configured report can serve as a template. Each month, the application copies it, changes the title, and adds the sections needed for that month.

Prototype is a Gang of Four creational pattern that creates objects by copying an existing instance. The prototype carries the configuration from which new objects are produced. A client can request a copy through an interface while the concrete class implements its copying rules. GoF pattern catalog

This article completes our creational patterns series following Factory Method, Abstract Factory, and Builder. The series began with Singleton.

A complete example

Save the following code as PrototypeExample.java. It uses standard Java APIs available in Java 8 and later.

package org.kodejava.pattern.prototype;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class PrototypeExample {
    interface Report {
        Report copy();
        void setTitle(String title);
        void addSection(String section);
    }

    static final class SalesReport implements Report {
        private String title;
        private final List<String> sections;

        SalesReport(String title, List<String> sections) {
            this.title = Objects.requireNonNull(title);
            this.sections = new ArrayList<>(sections);
        }

        private SalesReport(SalesReport original) {
            this(original.title, original.sections);
        }

        @Override
        public SalesReport copy() {
            return new SalesReport(this);
        }

        @Override
        public void setTitle(String title) {
            this.title = Objects.requireNonNull(title);
        }

        @Override
        public void addSection(String section) {
            sections.add(Objects.requireNonNull(section));
        }

        @Override
        public String toString() {
            return title + " " + sections;
        }
    }

    static Report customize(Report prototype) {
        Report report = prototype.copy();
        report.setTitle("November sales");
        report.addSection("Regional totals");
        return report;
    }

    public static void main(String[] args) {
        Report template = new SalesReport("Sales template",
                Arrays.asList("Summary", "Revenue"));
        Report november = customize(template);

        System.out.println("Template: " + template);
        System.out.println("Copy: " + november);
        System.out.println("Same instance: " + (template == november));

        november.addSection("Forecast");
        System.out.println("Template after edit: " + template);
        System.out.println("Copy after edit: " + november);
    }
}

Compile and run the example from the directory containing the source file.

javac -d out PrototypeExample.java
java -cp out org.kodejava.pattern.prototype.PrototypeExample

The program prints the original template and customized copy, then edits the copy again.

Template: Sales template [Summary, Revenue]
Copy: November sales [Summary, Revenue, Regional totals]
Same instance: false
Template after edit: Sales template [Summary, Revenue]
Copy after edit: November sales [Summary, Revenue, Regional totals, Forecast]

How copying works

GoF role Example Responsibility
Prototype Report Declares the copying operation used by the client.
Concrete prototype SalesReport Copies its title and sections according to its own rules.
Client customize() Obtains a copy through the interface and customizes it.
Configured prototype instance template in main() Supplies the initial report state.

The application creates the template once. The customize() method receives it through the Report interface and calls copy(). The concrete prototype returns a new SalesReport using a private copy constructor. Another report implementation could supply its own copying behavior through the same interface.

The false identity comparison shows that the template and copy are distinct report instances. Their section lists are also separate. The constructor creates a new ArrayList, so adding Regional totals or Forecast to the copy leaves the template’s sections intact.

The list elements are strings, which are immutable, so both lists can safely refer to the same section strings. If sections become mutable objects with their own fields, copying the list will still share those elements. The copy implementation must then decide which elements to duplicate and which references to share.

Choosing a copy policy

A useful copy contract states what the new object inherits and what becomes independent. In this example, the copy starts with the same title and section values, then owns its own mutable section list. A business object might also need a new identifier or a cleared creation timestamp.

Java provides Object.clone(), whose default behavior copies field values and shares referenced objects. This is a shallow copy. Our example exposes an explicit copy() method and constructs its result with the required list ownership. The Prototype pattern’s copying contract can be implemented this way. Object.clone() documentation

More elaborate object graphs require additional decisions. Shared subobjects, cycles, open resources, and external identities all affect what a valid copy means. Keep those decisions in the concrete prototype and document them for callers.

When should I use Prototype?

Prototype fits applications that repeatedly create objects from configured templates, particularly when client code works with multiple concrete types through a shared interface. A registry of named templates can let callers choose the starting configuration at runtime.

Copying also has a maintenance cost. When fields are added, review the copy operation so the new state receives the intended treatment. Copying large mutable graphs can consume substantial memory and time. Measure the actual construction and copying costs before choosing Prototype for performance.

For a small object with straightforward initialization, a constructor or factory can be sufficient. Prototype becomes useful when an existing instance provides the state needed to create another object.

Next, we begin structural patterns with Adapter.