Spring MVC Full CRUD Controller

Descripción

Create a Spring MVC Controller with full CRUD endpoints for Thymeleaf/JSP


File Template: ✅


Prefix

spring:controller


Scopes

java


Snippet de código

package ${1:com.example.demo.controller};

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import ${2:com.example.demo.service.${3:MyService}};
import ${4:com.example.demo.model.${5:MyEntity}};
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/${6:entidades}")
public class ${7:${5/^(.*)/$1Controller/}} {

	@Autowired
	private ${3:MyService} ${8:service};

	// List all entities
	@GetMapping
	public String listAll(Model model) {
		List<$5> items = ${8:service}.findAll();
		model.addAttribute("items", items);
		return "${6:list}";
	}

	// Show one entity by id
	@GetMapping("/{id}")
	public String getById(@PathVariable Long id, Model model) {
		Optional<$5> item = ${8:service}.findById(id);
		if(item.isPresent()) {
			model.addAttribute("item", item.get());
			return "${6:detail}";
		} else {
			return "redirect:/${6}"; // redirect to list if not found
		}
	}

	// Show create form
	@GetMapping("/new")
	public String showCreateForm(Model model) {
		model.addAttribute("item", new $5());
		return "${6:create}";
	}

	// Handle create POST
	@PostMapping
	public String create(@ModelAttribute $5 item) {
		${8:service}.save(item);
		return "redirect:/${6}";
	}

	// Show edit form
	@GetMapping("/{id}/edit")
	public String showEditForm(@PathVariable Long id, Model model) {
		Optional<$5> item = ${8:service}.findById(id);
		if(item.isPresent()) {
			model.addAttribute("item", item.get());
			return "${6:edit}";
		} else {
			return "redirect:/${6}";
		}
	}

	// Handle update POST
	@PostMapping("/{id}")
	public String update(@PathVariable Long id, @ModelAttribute $5 item) {
		${8:service}.update(id, item);
		return "redirect:/${6}";
	}

	// Handle delete
	@PostMapping("/{id}/delete")
	public String delete(@PathVariable Long id) {
		${8:service}.delete(id);
		return "redirect:/${6}";
	}
}