我正在尝试将我在另一个页面中拥有的表单实现为列表页面上的模式,但问题是由于重定向方法,我无法找到一种无需重定向页面的方法控制器。我该如何解决?我认为JavaScript可能会有所帮助,但我对其了解不多。
表格:
<form method="post" th:action="${marca.id == null} ? @{/marcas/salvar} : @{/marcas/editar} " th:object="${marca}">
<div class="form-row col-md-6">
<!--<label for="id">Codigo</label>-->
<label for="descricao">Descricao</label>
<input type="text" class="form-control" id="descricao" autofocus="autofocus" placeholder="Marca"
th:field="*{descricao}" th:classappend="${#fields.hasErrors('descricao')} ? 'is-invalid'"/>
<div class="invalid-feedback" >
<span th:errors="*{descricao}"></span>
</div>
<br/>
</div>
<input type="hidden" id="id" th:field="*{id}"/>
<br/>
<button type="submit" class="btn btn-primary btn-sm">Salvar</button>
</form>
列表:
<div class="container" id="listagem">
<div th:replace="fragments/alert"></div>
<div class="table-responsive">
<table class="table table-striped table-hover table-sm">
<thead>
<tr>
<th>Cod.</th>
<th>Descricao</th>
<th>Acao</th>
</tr>
</thead>
<tbody>
<tr th:each="m : ${marcas}">
<td th:text="${m.id}"></td>
<td th:text="${m.descricao}"></td>
<td><a class="btn btn-info btn-sm" th:href="@{/marcas/editar/{id} (id=${m.id})}" role="button">
<span class="oi oi-pencil" title="Editar" aria-hidden="true"></span>
</a>
<a class="btn btn-danger btn-sm" th:href="@{/marcas/excluir/{id} (id=${m.id})}" role="button" >
<span class="oi oi-circle-x" title="Excluir"></span>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
控制器:
@Controller
@RequestMapping("/marcas")
public class MarcaController {
@Autowired
private MarcaService service;
@GetMapping("/cadastrar")
public String cadastrar(ModelMap model){
model.addAttribute("marca", new Marca());
return "/marca/form";
}
@GetMapping("/listar")
public String listar(ModelMap model){
model.addAttribute("marcas", service.buscarTodos());
return "/marca/list";
}
@PostMapping("/salvar")
public String salvar(@Valid Marca marca, BindingResult result, RedirectAttributes attr) {
if (result.hasErrors()){
return "/marca/form";
}
service.salvar(marca);
attr.addFlashAttribute("success", "Marca inserida com sucesso!");
return "redirect:/marcas/listar";
}
@GetMapping("/editar/{id}")
public String preEditar(@PathVariable("id") Long id, ModelMap model) {
model.addAttribute("marca", service.buscarPorId(id));
return "/marca/form";
}
@PostMapping("/editar")
public String editar(@Valid Marca marca, BindingResult result, RedirectAttributes attr) {
if (result.hasErrors()){
return "/marca/form";
}
service.editar(marca);
attr.addFlashAttribute("success", "Marca editada com sucesso!");
return "redirect:/marcas/listar";
}
@GetMapping("/excluir/{id}")
public String excluir(@PathVariable("id") Long id, RedirectAttributes attr) {
service.excluir(id);
attr.addFlashAttribute("success", "Marca excluida com sucesso");
return "redirect:/marcas/listar";
}
}