Spring 徹底入門の「BookWebService」のサンプル(Eclipseプロジェクトを作成)
ディレクトリ構成
フォルダー パスの一覧
ボリューム シリアル番号は 00000070 A959:5E70 です
C:\ECLIPSE\PLEIADES\WORKSPACE\BOOKWEBSERVICEDINAMICPROJECT
│ .classpath
│ .project
│
├─.settings
│ .jsdtscope
│ org.eclipse.jdt.core.prefs
│ org.eclipse.wst.common.component
│ org.eclipse.wst.common.project.facet.core.xml
│ org.eclipse.wst.jsdt.ui.superType.container
│ org.eclipse.wst.jsdt.ui.superType.name
│
├─build
│ └─classes
│ └─example
│ ├─api
│ │ BookResource.class
│ │ BooksRestController.class
│ │
│ ├─app
│ │ EchoController.class
│ │ EchoForm.class
│ │ WelcomeController.class
│ │
│ ├─config
│ │ AppConfig.class
│ │ WebMvcConfig.class
│ │
│ └─domain
│ └─service
│ Book.class
│ BookResourceNotFoundException.class
│ BookService.class
│
├─src
│ └─main
│ │
│ └─java
│ └─example
│ ├─api
│ │ BookResource.java
│ │ BooksRestController.java
│ │
│ ├─app
│ │ EchoController.java
│ │ EchoForm.java
│ │ WelcomeController.java
│ │
│ ├─config
│ │ AppConfig.java
│ │ WebMvcConfig.java
│ │
│ └─domain
│ └─service
│ Book.java
│ BookResourceNotFoundException.java
│ BookService.java
│
└─web
│ index.jsp
│
├─META-INF
│ MANIFEST.MF
│
└─WEB-INF
│ include.jsp
│ web.xml
│
├─echo
│ input.jsp
│ output.jsp
│
└─lib
classmate-1.3.4.jar
hibernate-validator-6.1.5.Final.jar
jackson-annotations-2.11.1.jar
jackson-core-2.11.1.jar
jackson-databind-2.11.1.jar
jackson-datatype-jsr310-2.11.1.jar
jakarta.validation-api-2.0.2.jar
javax.annotation-api-1.3.2.jar
jboss-logging-3.3.2.Final.jar
slf4j-api-1.7.30.jar
spring-aop-5.2.7.RELEASE.jar
spring-beans-5.2.7.RELEASE.jar
spring-context-5.2.7.RELEASE.jar
spring-core-5.2.7.RELEASE.jar
spring-expression-5.2.7.RELEASE.jar
spring-jcl-5.2.7.RELEASE.jar
spring-tx-5.2.7.RELEASE.jar
spring-web-5.2.7.RELEASE.jar
spring-webmvc-5.2.7.RELEASE.jar
taglibs-standard-impl-1.2.5.jar
taglibs-standard-jstlel-1.2.5.jar
taglibs-standard-spec-1.2.5.jar
■BookResource.java
package example.api;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonFormat;
public class BookResource implements Serializable {
private static final long serialVersionUID = 1L;
private String bookId;
private String name;
@JsonFormat(pattern = "yyyy-MM-dd")
private java.time.LocalDate publishedDate;
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.time.LocalDate getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(java.time.LocalDate publishedDate) {
this.publishedDate = publishedDate;
}
}
■BooksRestController.java
package example.api;
import java.net.URI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import example.domain.service.Book;
import example.domain.service.BookResourceNotFoundException;
import example.domain.service.BookService;
@RestController
@RequestMapping("books")
public class BooksRestController {
@Autowired
BookService bookService;
@RequestMapping(path = "{bookId}", method = RequestMethod.GET)
public BookResource getBookResurce(@PathVariable String bookId) {
Book book = bookService.find(bookId);
if (book == null ) {
throw new BookResourceNotFoundException(bookId);
}
BookResource resource = new BookResource();
resource.setBookId(book.getBookId());
resource.setName(book.getName());
resource.setPublishedDate(book.getPublishedDate());
return resource;
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> createBook(@Validated @RequestBody BookResource newResource, UriComponentsBuilder uriBuilder) {
Book book = new Book();
book.setName(newResource.getName());
book.setPublishedDate(newResource.getPublishedDate());
Book createBook = bookService.create(book);
// String resourceUri = "http://localhost:8080/bookwebservice/" + createBook.getBookId();
URI resourceUri = uriBuilder.path("/books/{bookId}").buildAndExpand(createBook.getBookId()).encode().toUri();
System.out.println(resourceUri);
System.out.println(createBook.getName());
System.out.println(createBook.getPublishedDate());
return ResponseEntity.created(resourceUri).build();
// return ResponseEntity.created(URI.create(resourceUri)).build();
}
}
■EchoController.java
package example.app;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("echo")
public class EchoController {
@RequestMapping(method = RequestMethod.GET)
public String viewInput(Model model) {
EchoForm form = new EchoForm();
model.addAttribute(form);
return "echo/input";
}
@RequestMapping(method = RequestMethod.POST)
public String echo(@Valid EchoForm form, BindingResult result) {
if (result.hasErrors()) {
return "echo/input";
}
return "echo/output";
}
}
■EchoForm.java
package example.app;
import java.io.Serializable;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class EchoForm implements Serializable {
private static final long serialVersionUID = 1L;
@NotEmpty
@Size(max = 100)
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
■WelcomeController.java
package example.app;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class WelcomeController {
@RequestMapping("/")
public String home() {
return "index";
}
}
■AppConfig.java
package example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import example.domain.service.BookService;
@Configuration
public class AppConfig {
@Bean
BookService bookService() {
return new BookService();
}
}
■WebMvcConfig.java
package example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
@ComponentScan({"example.app","example.api"})
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp();
}
}
■Book.java
package example.domain.service;
import java.io.Serializable;
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
private String bookId;
private String name;
private java.time.LocalDate publishedDate;
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.time.LocalDate getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(java.time.LocalDate publishedDate) {
this.publishedDate = publishedDate;
}
}
■BookResourceNotFoundException.java
package example.domain.service;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookResourceNotFoundException extends RuntimeException {
public BookResourceNotFoundException(String bookId) {
super("Book is not found (bookId = " + bookId + ")");
}
}
■BookService.java
package example.domain.service;
import java.time.LocalDate;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Service;
@Service
public class BookService {
private final Map<String, Book> bookRepository = new ConcurrentHashMap<>();
@PostConstruct
public void loadDummyData() {
Book book = new Book();
book.setBookId("00000000-0000-0000-0000-000000000000");
book.setName("書籍名");
book.setPublishedDate(LocalDate.of(2010,4,20));
bookRepository.put(book.getBookId(), book);
Book book2 = new Book();
book2.setBookId("00000000-0000-0000-0000-000000000002");
book2.setName("http://aaa.co.jp?pl=222&accountStatusPolicy=P1&ct=aaaa");
book2.setPublishedDate(LocalDate.of(2010,4,20));
bookRepository.put(book2.getBookId(), book2);
Book book3 = new Book();
book3.setBookId("00000000-0000-0000-0000-000000000003");
book3.setName("\"書籍\"名");
book3.setPublishedDate(LocalDate.of(2010,4,20));
bookRepository.put(book3.getBookId(), book3);
}
public Book find(String bookId) {
Book book = bookRepository.get(bookId);
return book;
}
public Book create(Book book) {
String bookId = UUID.randomUUID().toString();
book.setBookId(bookId);
bookRepository.put(book.getBookId(), book);
return book;
}
}
■index.jsp
<html>
<body>
<h2>Hello World! BookWebClient</h2>
<ul>
<li><a href="<c:url value='/echo' />">エコーアプリケーションへ</a></li>
</ul>
</body>
</html>
■MANIFEST.MF
Manifest-Version: 1.0
Class-Path:
■include.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
■web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>example.config.AppConfig</param-value>
</context-param>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>
<!-- DispatcherServletクラスをサーブレットコンテナに登録します. -->
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<!-- contextClassパラメータにAnnotationConfigWebApplicationContextを指定します. -->
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<!-- contextConfigLocationパラメータに作成したコンフィギュレーションクラスを指定します. -->
<param-name>contextConfigLocation</param-name>
<param-value>example.config.WebMvcConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!-- DispatcherServlet を使用してリクエストをハンドリングするURLのパターンを定義します. -->
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
<include-prelude>/WEB-INF/include.jsp</include-prelude>
</jsp-property-group>
</jsp-config>
</web-app>
■input.jsp
<html>
<body>
<h2>入力画面</h2>
<form:form modelAttribute="echoForm">
<div>テキストを入力してください :</div>
<div>
<form:input path="text" />
<form:errors path="text" />
</div>
<div>
<form:button>送信</form:button>
</div>
</form:form>
</body>
</html>
■output.jsp
<html>
<body>
<h2>出力画面</h2>
<div>入力したテキストは・・・</div>
<div>
「<span><c:out value="${echoForm.text}" /></span>」
</div>
<div>です。</div>
<br>
<div>
<a href="<c:url value='/' />">トップ画面へ戻る</a>
</div>
</body>
</html>