Java web development today means Spring Boot for nearly everyone. Underneath it is the servlet model that has been there since the beginning — a request arrives, your code runs, a response goes back — but Spring Boot removes almost all the configuration that used to sit around it. This guide covers both layers, then building a working REST endpoint and HTML page.
The model underneath#
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String name = request.getParameter("name");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("<h1>Hello " + escape(name) + "</h1>");
}
}
You will rarely write this now, but it is worth seeing once. Everything a framework does eventually reduces to reading a request and writing a response. Knowing that makes framework behaviour much less mysterious.
Starting with Spring Boot#
Generate a project at start.spring.io, choosing Web, Spring Data JPA and a database driver.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
./mvnw spring-boot:run
That single annotation turns on component scanning, auto-configuration and an embedded web server. There is no separate Tomcat to install and no XML.
A REST endpoint#
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductRepository repository;
public ProductController(ProductRepository repository) {
this.repository = repository;
}
@GetMapping
public List<Product> list(@RequestParam(defaultValue = "0") int page) {
return repository.findAll(PageRequest.of(page, 20)).getContent();
}
@GetMapping("/{id}")
public ResponseEntity<Product> get(@PathVariable Long id) {
return repository.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Product create(@Valid @RequestBody ProductRequest request) {
return repository.save(new Product(request.name(), request.price()));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
repository.deleteById(id);
}
}
Constructor injection rather than field injection is worth adopting as a habit: it makes dependencies explicit and the class testable without Spring.
Validation#
public record ProductRequest(
@NotBlank(message = "Name is required")
@Size(max = 120)
String name,
@NotNull
@DecimalMin(value = "0.00", inclusive = false)
BigDecimal price
) { }
The @Valid annotation on the parameter is what triggers these. Without it the annotations are decoration and nothing is checked.
Turn validation failures into a useful response rather than a stack trace:
@RestControllerAdvice
public class ErrorHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> onValidation(MethodArgumentNotValidException e) {
Map<String, String> errors = new HashMap<>();
e.getBindingResult().getFieldErrors()
.forEach(f -> errors.put(f.getField(), f.getDefaultMessage()));
return errors;
}
}
Database access#
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 120)
private String name;
@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal price;
protected Product() { } // required by JPA
public Product(String name, BigDecimal price) {
this.name = name;
this.price = price;
}
// getters
}
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByPriceLessThan(BigDecimal max);
}
Spring implements the interface from the method names. findByPriceLessThan becomes the right query with no code written.
Server-rendered pages#
@Controller
public class PageController {
@GetMapping("/products")
public String products(Model model) {
model.addAttribute("products", repository.findAll());
return "products"; // resolves to templates/products.html
}
}
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Products</h1>
<ul>
<li th:each="p : ${products}">
<span th:text="${p.name}">Name</span>
</li>
</ul>
</body>
</html>
Thymeleaf escapes output by default, which is what protects you from cross-site scripting. The unescaped variant exists for HTML you generated yourself, and should be used sparingly.
Configuration#
spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.open-in-view=false
server.port=8080
Two of those deserve comment. Setting the schema mode to validate rather than update means Hibernate checks the schema matches rather than silently altering your production database — use a migration tool such as Flyway for changes. And turning off open-in-view disables a default that keeps a database session open for the whole request, which hides N+1 problems until they reach production.
Testing#
@SpringBootTest
@AutoConfigureMockMvc
class ProductControllerTest {
@Autowired
private MockMvc mvc;
@Test
void listReturnsOk() throws Exception {
mvc.perform(get("/api/products"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
}
Before deploying#
- Set the active profile to production and keep secrets in environment variables
- Turn off detailed error pages for visitors
- Add Spring Security, even for an internal application
- Expose a health endpoint via Actuator, and restrict the rest
- Use Flyway or Liquibase for schema changes
- Run behind a reverse proxy handling TLS
Questions people ask#
Spring Boot or something lighter?
Spring Boot for most work — the ecosystem and documentation are unmatched. Quarkus and Micronaut start faster and use less memory, which matters for serverless and containers at scale.
Do I need to learn servlets first?
Not in detail, but knowing the request-response model helps enormously when framework behaviour surprises you. An hour on it is well spent.
REST API or server-rendered pages?
Server-rendered for content sites and simple forms — fewer moving parts and better search visibility. A REST API when you have a separate front end or mobile client.
Why is my Spring Boot application slow to start?
Usually component scanning across too broad a package, or eager initialisation of heavy beans. Check the startup log for the slowest steps, and consider lazy initialisation in development.
Where to go next#
- Java and the Spring framework — dependency injection in depth.
- Java database connectivity — the layer beneath JPA.
- Java security — what to get right before going live.