[JAVA] Spring 5 MVC-Webanwendungsentwicklung mit Visual Studio Code Spring Security-Verwendung 3/3 [Seitenerstellung 2/2]

Einführung

Dies ist eine Fortsetzung von hier. Dieses Mal erstellen wir eine allgemeine Seite zur Benutzererstellung.

Controller erstellen

Erstellen Sie einen Controller für die allgemeine Benutzererstellungsseite.

D:\JAVA\Project\securitySample\src\main\java\com\example
└─controller
  └─UserRegController.java

UserRegController.java

UserRegController.java


package com.example.web.controller;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.example.persistence.entity.UserInfo;
import com.example.service.AuthService;
import com.example.web.form.AuthForm;

@Controller
@RequestMapping("/userReg")
public class UserRegController {
	@Autowired
	AuthService authService;

	final static Map<String, String> CHECK_ITEMS =
			Collections.unmodifiableMap(new LinkedHashMap<String, String>() {
				private static final long serialVersionUID = 1L;

				{
					put("Rolle 1", 		"ROLE_Role1");
					put("Rolle 2", 		"ROLE_Role2");
					put("Rolle 3", 		"ROLE_Role3");
				}
			});

	@GetMapping("/index")
	public String index(Model model) {
		List<UserInfo> userInfoList = authService.findUserAll();
		model.addAttribute("userInfoList", userInfoList);
		return "userReg/index";
	}

	@GetMapping("/registered")
	public String registeredGet() {
		return "userReg/registered";
	}

	@GetMapping("/insert")
	public String insertGet(Model model) {
		model.addAttribute("authForm", new AuthForm());
		model.addAttribute("checkItems", CHECK_ITEMS);
		return "userReg/insert";
	}

	@PostMapping("/insert")
	public String insertPost(Model model, RedirectAttributes attributes,
			@Valid AuthForm authForm, BindingResult bindingResult, HttpServletRequest request) {
		if (bindingResult.hasErrors()) {
			model.addAttribute("checkItems", CHECK_ITEMS);
			model.addAttribute("signupError", true);
			return "userReg/insert";
		}
		try {
			authService.insertUser(authForm);
		} catch (DataIntegrityViolationException e) {
			model.addAttribute("checkItems", CHECK_ITEMS);
			model.addAttribute("signupError", true);
			return "userReg/insert";
		}

		attributes.addFlashAttribute("message", "Hat sich registriert.");
		return "redirect:/userReg/registered";
	}

	@GetMapping("/{id}/update")
	public String updateGet(Model model, @PathVariable("id") String id) {
		AuthForm authForm = authService.userRegById(id);

		model.addAttribute("authForm", authForm);
		model.addAttribute("checkItems", CHECK_ITEMS);
		return "userReg/update";
	}

	@PostMapping("/{id}/update")
	public String updatePost(Model model,
			RedirectAttributes attributes,
			@Valid AuthForm authForm, BindingResult bindingResult, HttpServletRequest request) {

		if (bindingResult.hasErrors()) {
			model.addAttribute("checkItems", CHECK_ITEMS);
			model.addAttribute("signupError", true);
			return "userReg/update";
		}
		try {
			authService.updateUser(authForm);
		} catch (DataIntegrityViolationException e) {
			model.addAttribute("checkItems", CHECK_ITEMS);
			model.addAttribute("signupError", true);
			return "userReg/update";
		}

		attributes.addFlashAttribute("message", "es hat sich geändert.");
		return "redirect:/userReg/registered";
	}

	@GetMapping("/{id}/delete")
	public String deleteGet(Model model, @PathVariable("id") String id) {
		AuthForm authForm = authService.userRegById(id);

		model.addAttribute("authForm", authForm);
		model.addAttribute("checkItems", Arrays.asList(authForm.getAuthority()));
		return "userReg/delete";
	}

	@PostMapping("/{id}/delete")
	public String deletePost(Model model, @PathVariable("id") String id,
			RedirectAttributes attributes,
			@Valid AuthForm authForm, BindingResult bindingResult, HttpServletRequest request) {

		try {
			authService.deleteUser(authForm.getUserId());
		} catch (DataIntegrityViolationException e) {
			model.addAttribute("signupError", true);
			return "userReg/delete";
		}

		attributes.addFlashAttribute("message", "Es wurde gelöscht.");
		return "redirect:/userReg/registered";
	}
}

Ansicht erstellen

Erstellen Sie eine Ansicht der allgemeinen Benutzererstellungsseite.

D:\JAVA\Project\securitySample\src\main\webapp\WEB-INF\templates
└─userReg
  ├─delete.html
  ├─index.html
  ├─insert.html
  ├─register.html
  ├─registered.html
  └─update.html

delete.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Bildschirm zum Löschen des Benutzers</title>
</head>
<body>
	<h1>User Löschung</h1>

	<form method="post" action="#" th:action="@{delete}" th:object="${authForm}">
		<div>
			<label for="userId">Anmelde-ID</label>
			<span th:text="*{userId}"></span>
			<input type="hidden" th:field="*{userId}">
		</div>

		<div>
			<label for="userNameJP">Benutzername (Japanisch)</label>
			<span th:text="*{userNameJP}"></span>
			<input type="hidden" th:field="*{userNameJP}">
		</div>

		<div>
			<button type="submit">Löschen</button>
			&nbsp;&nbsp;&nbsp;
			<a th:href="@{/userReg/index}">Stornieren</a>
		</div>
	</form>

</body>
</html>

index.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Bildschirm für registrierte Benutzerlisten</title>
</head>

<body>
	<h1>Liste der registrierten Benutzer</h1>
	<a href="insert.html" th:href="@{insert}">Anmelden</a>
	<div>
   		<table border="1">
    		<thead>
        		<tr>
            		<th>Benutzeridentifikation</th>
            		<th>Nutzername</th>
            		<th>Abteilungsname</th>
            		<th>Status</th>
            		<th>rollen</th>
            		<th>Befehl</th>
        		</tr>
       		</thead>
       		<tr th:each="userInfo : ${userInfoList}" th:object="${userInfo}">
           		<td th:text="*{userId}"></td>
           		<td th:text="*{userNameJP}"></td>
           		<td th:text="*{sectionNameJP}"></td>
           		<td th:if="*{enabled}">Kann verwendet werden</td>
				<td th:unless="*{enabled}">Verwendung verboten</td>
				<td>
					<th:block th:each="userRoles : *{userRolesList}" th:object="${userRoles}">
						<th:block th:utext="*{authority} + '<br />'"></th:block>
					</th:block>
				</td>
           		<td>
           			<a th:href="@{*{userId} + '/update'}">Bearbeiten</a>
           			&nbsp;&nbsp;&nbsp;
           			<a th:href="@{*{userId} + '/delete'}">Löschen</a>
           		</td>
       		</tr>
	    </table>
   	</div>
</body>
</html>

insert.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Benutzerregistrierungsbildschirm</title>
</head>
<body>
	<h1>Benutzer Registration</h1>

	<form method="post" action="#" th:action="@{insert}" th:object="${authForm}">
		<div th:if="${signupError}">
			<em>Ich konnte mich nicht registrieren.</em>
		</div>

		<div>
			<label for="userId">Anmelde-ID</label>
			<input type="text" autofocus="autofocus" th:field="*{userId}">
		</div>

		<div th:insert="userReg/register :: register"></div>
	</form>

</body>
</html>

register.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

	<div th:fragment="register" th:remove="tag">
		<div>
			<label for="password">Passwort</label>:
			<input type="password" th:field="*{password}">
			<em th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Password Error</em>
		</div>

		<div>
			<label for="userNameJP">Benutzername (Japanisch)</label>
			<input type="text" th:field="*{userNameJP}">
		</div>

		<div>
			<label for="userId">Abteilungsname (Japanisch)</label>
			<input type="text" th:field="*{sectionNameJP}">
		</div>

		<div>
			<label>
				<input type="checkbox" id="enabled" th:field="*{enabled}">Aktivierung
			</label>
		</div>

		<div>
			<label class="control-label col-sm-2">rollen</label>
				<div th:each="item : ${checkItems}">
					<label>
						<input type="checkbox" name="authority" th:value="${item.value}" th:text="${item.key}" th:field="*{authority}">
					</label>
				</div>
			<span th:if="${#fields.hasErrors('authority')}" th:errors="*{authority}" class="help-block">error!</span>
		</div>

		<div>
			<button type="submit">Anmeldung</button>
			&nbsp;&nbsp;&nbsp;
			<a th:href="@{/userReg/index}">Stornieren</a>
		</div>
	</div>
</html>

registered.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Benutzerregistrierungsnachricht</title>
</head>
<body>
	<h1><span th:text="${message}">Botschaft</span></h1>
	<a th:href="@{index}">Zurück zur Benutzerliste</a>
</body>
</html>

update.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Benutzerbearbeitungsbildschirm</title>
</head>
<body>
	<h1>Benutzer bearbeiten</h1>

	<form method="post" action="#" th:action="@{update}" th:object="${authForm}">
	<div th:if="${signupError}">
			<em>Konnte nicht aktualisiert werden.</em>
		</div>
		<div>
			<label for="userId">Anmelde-ID</label>
			<span th:text="*{userId}"></span>
			<input type="hidden" th:field="*{userId}">
		</div>

		<div th:insert="userReg/register :: register"></div>
	</form>

</body>
</html>

Diese Beispielquelle

Auf GitHub hochgeladen. https://github.com/t-skri1/SpringSample03

Zusammenfassung

Damit ist die allgemeine Seite zur Benutzererstellung abgeschlossen. Das Projekt ist nun abgeschlossen. Bitte kompilieren und ausführen. Bitte versuchen Sie auch den Unterschied im Verhalten je nach Rolle.

Üben Sie die Entwicklung von Spring5 MVC-Webanwendungen mit Visual Studio Code

Es war nur ein Schmerz, nicht heiß eingesetzt zu werden. Ich bin daran gewöhnt, aber ich hatte das Gefühl, dass Eclipse nicht besser zu mir passt. Gibt es jetzt nicht viel Nachfrage? Ist es schwierig, weil es sich um eine Nicht-Boot-Feder handelt? Nächstes Mal werde ich versuchen, eine Webanwendung mit Boot mit Visual Studio Code zu entwickeln.

Recommended Posts

Spring 5 MVC-Webanwendungsentwicklung mit Visual Studio Code Spring Security-Verwendung 2/3 [Seitenerstellung 1/2]
Spring 5 MVC-Webanwendungsentwicklung mit Visual Studio Code Spring Security-Verwendung 3/3 [Seitenerstellung 2/2]
Spring 5 MVC-Webanwendungsentwicklung mit Visual Studio Code Spring Security-Nutzung 1/3 [Vorbereitung]
Entwicklung von Spring5 MVC-Webanwendungen mit Visual Studio Code Maven-Vorlagenerstellung
Spring5 MVC-Webanwendungsentwicklung mit Visual Studio-Code Hello World Creation
Spring5 MVC-Webanwendungsentwicklung mit Visual Studio Code SQL Server-Verbindung
Spring Boot2-Webanwendungsentwicklung mit Visual Studio Code Hello World-Erstellung
Spring Boot2-Webanwendungsentwicklung mit Visual Studio Code SQL Server-Verbindung
Entwicklung von Spring5 MVC-Webanwendungen mit Visual Studio Code Environment-Konstruktion (Installation von JDK11 / Maven / Tomcat / Visual Studio Code)
Erstellen Sie mit Java + Spring eine Web-APP-Entwicklungsumgebung mit Visual Studio Code
Starten Sie die Entwicklung von Webanwendungen mit Spring Boot
Erstellen Sie eine Java-Programmentwicklungsumgebung mit Visual Studio Code
[Spring Boot] Erstellung von Webanwendungen
Erstellung einer Java-Webanwendungsentwicklungsumgebung mit VS-Code (struts2)
Eine Aufzeichnung zum Einrichten einer Java-Entwicklungsumgebung mit Visual Studio Code
Führen Sie die WEB-Anwendung mit Spring Boot + Thymeleaf aus
[Jakarta EE 8 Anwendungsentwicklung mit Gradle] 2. Projekterstellung
Erste Schritte mit Java-Programmen mit Visual Studio Code
Warum können Sie Java mit Visual Studio Code entwickeln?
Etwa der Ablauf der Entwicklung von Webanwendungen mit Rails.
Memo zur Entwicklung von Webanwendungen mit MVN, Tomcat, JSP / Servlet mit VScode
Die erste WEB-Anwendung mit Spring Boot-Making a Pomodoro Timer-
So erhalten Sie eine leere Anfrage mit Spring Web MVC @RequestBody