Java,Spring,hibernate開發web application rest api 的功能

 本人用的是Dynamic Web Project, Class path 有jackson-core-2.15.2.jar,jackson-annotations-2.15.2.jar,jackson-databind-2.15.2.jar

根據請求的內容類型選擇適當的視圖解析器。我們將默認內容類型設置為jsp,prefix是"/WEB-INF/view/",suffix 是".jsp" ,之後如找不到適當的視圖解析器就改為application/json,並使用MappingJackson2JsonView作為JSON視圖解析器,

現在 http://localhost:8080/genbook/book/list 成功找到視圖文件 list-books.jsp,

另一個 http://localhost:8080/genbook/book/retrieve rest api 應該回應一個json



bookController程式:


package com.book.gen.controller;

import java.io.IOException;

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

import java.util.Base64;

import java.util.List;



import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.format.annotation.DateTimeFormat;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.util.StringUtils;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.multipart.commons.CommonsMultipartFile;


import com.book.gen.entity.*;

import com.book.gen.service.*;

import com.book.gen.utils.FileUtils;


@Controller

@RequestMapping("/book")

public class bookController {

// need to inject our book service

@Autowired

private BookService bookService;

@PostMapping(value = "/create", consumes = MediaType.APPLICATION_JSON_VALUE)

    public ResponseEntity<Book> createBook(@RequestBody Book book) {

        bookService.saveBook(book);

        return new ResponseEntity<>(book, HttpStatus.CREATED);

    }


@GetMapping("/retrieve")

    public ResponseEntity<List<Book>> retrieveBooks() {

        List<Book> books = bookService.getBooks();

        return new ResponseEntity<>(books, HttpStatus.OK);

    }


    @PutMapping(value = "/update", consumes = MediaType.APPLICATION_JSON_VALUE)

    public ResponseEntity<Book> updateBook(@RequestBody Book book) {

        bookService.saveBook(book);

        return new ResponseEntity<>(book, HttpStatus.OK);

    }


    @DeleteMapping("/delete/{bookId}")

    public ResponseEntity<Void> deleteBook(@PathVariable int bookId) {

        bookService.deleteBook(bookId);

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);

    }

@GetMapping("/list")

public String listBooks(Model theModel) {

// get books from the service

List<Book> theBooks = bookService.getBooks();

// add the customers to the model

theModel.addAttribute("Books", theBooks);

return "list-books";

}

@GetMapping("/showFormForAdd")

public String showFormForAdd(Model theModel) {

// create model attribute to bind form data

Book theBook = new Book();

theModel.addAttribute("Book", theBook);

return "book-form";

}

@PostMapping(value = "/saveBook", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

public String saveBook(@ModelAttribute("Book") Book theBook,

                       @RequestParam("coverImageFile") MultipartFile coverImageFile,

                       @RequestParam("creationDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate creationDate) {

    theBook.setCreationDate(creationDate);

    // Save the cover image

    if (!coverImageFile.isEmpty()) {

        try {

        String fileName = StringUtils.cleanPath(coverImageFile.getOriginalFilename());

            byte[] imageBytes = coverImageFile.getBytes();

            if(fileName.contains(".."))

    {

    System.out.println("not a a valid file");

    }else {

    theBook.setCoverImage(imageBytes);

    }

        } catch (IOException e) {

            // Handle the exception

            e.printStackTrace();

        }

    }

    // Save the book using our service

    bookService.saveBook(theBook);

    return "redirect:/book/list";

}

@GetMapping("/showFormForUpdate")

public String showFormForUpdate(@RequestParam("bookId") int theId,

Model theModel) {

// get the book from our service

Book theBook = bookService.getBook(theId);

if(theBook.getCreationDate()!=null) {

theModel.addAttribute("formattedCreationDate", theBook.getCreationDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

}

theModel.addAttribute("coverImageSrc", "data:image/jpeg;base64,"+theBook.getCoverImageBase64());

// set customer as a model attribute to pre-populate the form

theModel.addAttribute("Book", theBook);

// send over to our form

return "book-form";

}

@GetMapping("/delete")

public String deleteCustomer(@RequestParam("bookId") int theId) {

// delete the book

bookService.deleteBook(theId);

return "redirect:/book/list";

}

}



Spring配置文件:


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xmlns:context="http://www.springframework.org/schema/context"

    xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/tx 

http://www.springframework.org/schema/tx/spring-tx.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--  Add AspectJ autoproxy support for AOP  -->

<aop:aspectj-autoproxy/>

<!-- Add support for component scanning -->

<context:component-scan base-package="com.book.gen" />


<!-- Add support for conversion, formatting and validation support -->

<mvc:annotation-driven/>

<!-- Enable multipart support for file uploads -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <property name="maxUploadSize" value="10485760" /> <!-- Set the maximum file size (in bytes) -->

      

    <!-- 設置臨時存儲目錄 -->

    <property name="uploadTempDir" value="/upload"/>

    <!-- 如果需要處理中文文件名,請設置編碼 -->

    <property name="defaultEncoding" value="UTF-8"/>

</bean>

<!-- Define Spring MVC view resolver -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/view/" />

<property name="suffix" value=".jsp" />

<property name="order" value="1" />

</bean>

<!-- Define JSON view resolver -->

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">

<property name="order" value="2" />

<property name="contentNegotiationManager">

<bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">

<property name="ignoreAcceptHeader" value="true" />

<property name="defaultContentType" value="application/json" />

</bean>

</property>

<property name="defaultViews">

<list>

<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">

<property name="prefixJson" value="true" />

</bean>

</list>

</property>

</bean>

    <!-- Step 1: Define Database DataSource / connection pool -->

<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

          destroy-method="close">

        <property name="driverClass" value="com.mysql.cj.jdbc.Driver" />

        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/bookgendb?useSSL=false&amp;serverTimezone=UTC" />

        <property name="user" value="root" />

        <property name="password" value="1234qwer" /> 

        <!-- these are connection pool properties for C3P0 -->

<property name="initialPoolSize" value="5"/>

        <property name="minPoolSize" value="5" />

        <property name="maxPoolSize" value="20" />

        <property name="maxIdleTime" value="30000" />

</bean>  

    <!-- Step 2: Setup Hibernate session factory -->

<bean id="sessionFactory"

class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

<property name="dataSource" ref="myDataSource" />

<property name="packagesToScan" value="com.book.gen.entity" />

<property name="hibernateProperties">

   <props>

      <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

      <prop key="hibernate.show_sql">true</prop>

   </props>

</property>

   </bean>

   

    <!-- Step 3: Setup Hibernate transaction manager -->

<bean id="myTransactionManager"

            class="org.springframework.orm.hibernate5.HibernateTransactionManager">

        <property name="sessionFactory" ref="sessionFactory"/>

    </bean>

    

    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->

<tx:annotation-driven transaction-manager="myTransactionManager" />


<!-- Add support for reading web resources: css, images, js, etc ... -->

<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

</beans>















Comments

Popular posts from this blog

How to use Visual Studio Code to debug ReactJS application

Github Link & Web application demonstration on YouTube

Java Interview Questions and Answers 1.0