# Mapping Controller Variables

Variables in the URL can be mapped into the controller arguments.

## Path Variables

These are part of the URL. For example in the following one the name at the end would be a variable:

```
https://localhost:8080/users/John
```

Which can be mapped like this:

```java
@GetMapping(path="/{name}")
public final Employee getEmployee()
```

Regular expressions can be used:

```java
@GetMapping(path="/{name:[A-Za-z0-9]*}")
public final Employee getEmployee()
```

This can be applied to the controller mapping too:

```java
@RestController
@RequestMapping(value = "/users/{name}/")
public class EmployeeController
```

### Path Variables to Arguments

```java
@GetMapping(path="/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public final Employee getEmployee(@PathVariable final String name)
```

### Path Variables to Objects

```java
@GetMapping(path="/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public final Employee getEmployee(final EmployeeName name)
```

This requires EmployeeName being a bean with a field sharing the path variable name:

```java
public final class EmployeeName {

   private String name;

   public EmployeeName () {
      super();
   }

   public final String getName() {
      return name;
   }

   public final void setName(final String n) {
      name = n;
   }

}
```

## Request Parameters

These come as a map added to the URL:

```
https://localhost:8080/users?name=John
```

And can be mapped like this:

```java
@GetMapping
public final Employee getEmployee(@RequestParam(value = "name") final String name)
```

They can be optional:

```java
@GetMapping
public final Employee getEmployee(
   @RequestParam(value = "name", required = false, defaultValue = "") final String name)
```

## Body Content

The content of a request can be mapped into an object:

```java
@PostMapping
public final Employee createEmployee(@RequestBody final EmployeeName name)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bernardo.gitbook.io/development-docs-java/spring-mvc/controllers/mapping-controller-variables.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
