[JAVA] Spring5 MVC Web application development with Visual Studio Code Spring Security usage 3/3 [Page creation 2/2]

Introduction

It is a continuation from here. This time, we will create a general user creation page.

Create controller

Create a controller for the general user creation page.

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("Roll 1", 		"ROLE_Role1");
					put("Roll 2", 		"ROLE_Role2");
					put("Roll 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", "Has registered.");
		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", "It has changed.");
		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", "It has been deleted.");
		return "redirect:/userReg/registered";
	}
}

view creation

Create a view of the general user creation page.

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>User deletion screen</title>
</head>
<body>
	<h1>User deletion</h1>

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

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

		<div>
			<button type="submit">Delete</button>
			&nbsp;&nbsp;&nbsp;
			<a th:href="@{/userReg/index}">Cancel</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>Registered user list screen</title>
</head>

<body>
	<h1>List of registered users</h1>
	<a href="insert.html" th:href="@{insert}">sign up</a>
	<div>
   		<table border="1">
    		<thead>
        		<tr>
            		<th>User ID</th>
            		<th>username</th>
            		<th>Department name</th>
            		<th>status</th>
            		<th>roll</th>
            		<th>command</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}">Can be used</td>
				<td th:unless="*{enabled}">Usage prohibited</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'}">Edit</a>
           			&nbsp;&nbsp;&nbsp;
           			<a th:href="@{*{userId} + '/delete'}">Delete</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>User registration screen</title>
</head>
<body>
	<h1>user registration</h1>

	<form method="post" action="#" th:action="@{insert}" th:object="${authForm}">
		<div th:if="${signupError}">
			<em>I couldn't register.</em>
		</div>

		<div>
			<label for="userId">Login 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">password</label>:
			<input type="password" th:field="*{password}">
			<em th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Password Error</em>
		</div>

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

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

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

		<div>
			<label class="control-label col-sm-2">roll</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">Registration</button>
			&nbsp;&nbsp;&nbsp;
			<a th:href="@{/userReg/index}">Cancel</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>User registration message</title>
</head>
<body>
	<h1><span th:text="${message}">message</span></h1>
	<a th:href="@{index}">Return to user list</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>User edit screen</title>
</head>
<body>
	<h1>User edit</h1>

	<form method="post" action="#" th:action="@{update}" th:object="${authForm}">
	<div th:if="${signupError}">
			<em>Could not update.</em>
		</div>
		<div>
			<label for="userId">Login ID</label>
			<span th:text="*{userId}"></span>
			<input type="hidden" th:field="*{userId}">
		</div>

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

</body>
</html>

This sample source

Uploaded to GitHub. https://github.com/t-skri1/SpringSample03

Summary

This completes the general user creation page. The project is now complete. Please compile and run it. Please also try the difference in behavior depending on the roll.

Practice Spring5 MVC web app development with Visual Studio Code

It was just a pain to not be hot deployed. I'm used to it, but I felt that Eclipse didn't suit me better. Is there not much demand now? Is it difficult to do because it is a non-Boot Spring? Next time, I will try to develop a web application with Boot with Visual Studio Code.

Recommended Posts

Spring5 MVC Web application development with Visual Studio Code Spring Security usage 2/3 [Page creation 1/2]
Spring5 MVC Web application development with Visual Studio Code Spring Security usage 3/3 [Page creation 2/2]
Spring5 MVC Web application development with Visual Studio Code Spring Security usage 1/3 [Preparation]
Spring5 MVC Web application development with Visual Studio Code Maven template creation
Spring5 MVC Web App Development with Visual Studio Code Hello World Creation
Spring5 MVC web application development with Visual Studio Code SQL Server connection
Spring Boot2 Web application development with Visual Studio Code Hello World creation
Spring Boot2 Web application development with Visual Studio Code SQL Server connection
Spring5 MVC Web application development with Visual Studio Code Environment construction (Installation of JDK11, Maven, Tomcat, Visual Studio Code)
Build WebAPP development environment with Java + Spring with Visual Studio Code
Start web application development with Spring Boot
Build Java program development environment with Visual Studio Code
[Spring Boot] Web application creation
Java web application development environment construction with VS Code (struts2)
Web application creation with Nodejs with Docker
A record of setting up a Java development environment with Visual Studio Code
Run WEB application with Spring Boot + Thymeleaf
Introduction to Java development environment & Spring Boot application created with VS Code
[Jakarta EE 8 application development with Gradle] 2. Project creation
Getting started with Java programs using Visual Studio Code
Why can I develop Java with Visual Studio Code?
Roughly the flow of web application development with Rails.
Web application development memo with MVN, Tomcat, JSP / Servlet with VScode
The first WEB application with Spring Boot-Making a Pomodoro timer-
To receive an empty request with Spring Web MVC @RequestBody