I tried to create a shopping site administrator function / screen with Java and Spring

Introduction

I have been studying Java for a couple of years. Recently (albeit late) I started studying Spring. Immediately, I tried to create a function / screen for the administrator of the shopping site. I'm still poor, but please refer to it if you like.

STS version: 4.7.0.RELEASE MySQL version: 8.0.15 Version of mysql-connector-java: 8.0.16

SampleApplication.java


package com.example.demo;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@SpringBootApplication
public class Sample1Application {
	@RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
		
		return "index";
    }
    
	public static void main(String[] args) {
		SpringApplication.run(Sample1Application.class, args);
	}
}

SampleController.java


package com.example.demo;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;


@Controller
public class SampleController {
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Autowired
	private SampleService sampleService;
	
	@ModelAttribute
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model) {
		LoginForm loginForm = new LoginForm();
		loginForm.setId("");
		loginForm.setName("");
        model.addAttribute("loginForm", loginForm);
        model.addAttribute("message", "Please enter your administrator information");
        
        return "login";
    }

	@ModelAttribute
	@RequestMapping(value = "/login_result", method = RequestMethod.POST)
	public String login_result(LoginForm loginForm, Model model) {
		       List<Map<String, Object>> list;
		       list = jdbcTemplate.queryForList("select * from user");
		       
               for(int i = 0; i < list.size(); i++) {
            	   if (("[" + loginForm.getId() + "," + " " + loginForm.getName() + "]").compareTo((list.get(i).values().toString())) == 0) {
            	        model.addAttribute("message", "Login was successful");
                   }
               
                   else {
            	         model.addAttribute("message", "I failed to login");
                   }
               }

	    	return "login_result";
	}
	
    @ModelAttribute
    @RequestMapping(value = "/admin_menu", method = RequestMethod.GET)
    public String admin_menu(Model model) {
	  model.addAttribute("message", "Please select a menu");

    return "admin_menu";
    }
    
    @ModelAttribute
    @RequestMapping(value = "/show_product", method = RequestMethod.GET)
    public String show_product(Model model) {
    	List<String> products = null;
    	products = sampleService.selectAll();
    	model.addAttribute("products",products);
	    model.addAttribute("message", "Displayed the product");

    return "show_product";
    }
    
    @ModelAttribute
    @RequestMapping(value = "/register_product", method = RequestMethod.GET)
    public String register_product(Model model) {
    	ProductForm productForm = new ProductForm();
    	model.addAttribute("productForm", productForm);
	    model.addAttribute("message", "Please register the product");

    return "register_product";
    }

	@ModelAttribute
    @RequestMapping(value = "/update_product", method = RequestMethod.GET)
    public String update_product(Model model) {
      ProductForm productForm = new ProductForm();
      model.addAttribute("productForm", productForm);
	  model.addAttribute("message", "Please update the product");

    return "update_product";
    }
	
    @ModelAttribute
    @RequestMapping(value = "/delete_product", method = RequestMethod.GET)
    public String delete_product(Model model) {
      ProductForm productForm = new ProductForm();
      model.addAttribute("productForm", productForm);    	
	  model.addAttribute("message", "Please delete the item");

    return "delete_product";
    }
    
    @ModelAttribute
    @RequestMapping(value = "/afeter_delete_product", method = RequestMethod.POST)
    public String afeter_delete_product(ProductForm productForm, Model model) {
      sampleService.delete(productForm);	
	  model.addAttribute("message", "Processing is complete");

    return "afeter_delete_product";
    }
    
    @ModelAttribute
    @RequestMapping(value = "/show_result", method = RequestMethod.POST)
    public String show_result(ProductForm productForm, Model model) {
    	sampleService.insert(productForm);
	    model.addAttribute("message", "Processing is complete");

    return "show_result";
    }
}

SampleService.java


package com.example.demo;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;


@Service
public class SampleService {  
  public List<String> selectAll() {
	  List<String> entities = null;
	  entities = new ArrayList<String>();
	  ResultSet resultSet = null;
	  Connection connection = null;
	  
	  try {
		  connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample?serverTimezone=JST", "root", "root");
          Statement statement = connection.createStatement();
          resultSet = statement.executeQuery("select * from product");

	  while (resultSet.next()) {
		  String str = resultSet.getString("code") + "  " + resultSet.getString("name") + "  " + resultSet.getString("description") + "  " + resultSet.getString("price") + "  " + resultSet.getString("evaluation");
		  entities.add(str);
	  }

		if (connection != null) {
			connection.close();
		}

	  } catch (SQLException e) {
          e.printStackTrace();
	  }
	  
      return entities;
   }
  
  public void insert(ProductForm productForm) {
	  Connection connection = null;
	  
	  try {
		  connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample?serverTimezone=JST", "root", "root");
		  PreparedStatement statement = connection.prepareStatement("INSERT INTO product VALUES (?, ?, ?, ?, ?)");

		  statement.setString(1, productForm.getCode());
          statement.setString(2, productForm.getName());
          statement.setString(3, productForm.getDescription());
          statement.setString(4, productForm.getPrice());
          statement.setString(5, productForm.getEvaluation());
          
          connection.setAutoCommit(true);
          statement.execute();

		if (connection != null) {
			connection.close();
		}

	  } catch (SQLException e) {
          e.printStackTrace();
	  }
   }

  public void update(ProductForm productForm) {
	  Connection connection = null;
	  
	  try {
		  connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample?serverTimezone=JST", "root", "root");
		  PreparedStatement statement = connection.prepareStatement("UPDATE product SET code=?, name=?, description=?, price=?, evaluation=? WHERE code=?");

		  statement.setString(1, productForm.getCode());
          statement.setString(2, productForm.getName());
          statement.setString(3, productForm.getDescription());
          statement.setString(4, productForm.getPrice());
          statement.setString(5, productForm.getEvaluation());
          statement.setString(6, productForm.getCode());

          connection.setAutoCommit(true);
          statement.execute();

		if (connection != null) {
			connection.close();
		}

	  } catch (SQLException e) {
          e.printStackTrace();
	  }
   }
  
  public void delete(ProductForm productForm) {
	  Connection connection = null;
	  
	  try {
		  connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample?serverTimezone=JST", "root", "root");
		  PreparedStatement statement = connection.prepareStatement("DELETE FROM product WHERE code=?");

          statement.setString(1, productForm.getCode());

          connection.setAutoCommit(true);
          statement.execute();
          
		if (connection != null) {
			connection.close();
		}

	  } catch (SQLException e) {
          e.printStackTrace();
	  }
   }
}

LoginForm.java


package com.example.demo;


public class LoginForm {
    private String id;
    private String name;
    
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

ProductForm.java


package com.example.demo;


public class ProductForm {
    private String code;
    private String name;
    private String description;
    private String price;
    private String evaluation;
    
	public String getCode() {
		return code;
	}
	
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getDescription() {
		return description;
	}
	
	public void setDescription(String description) {
		this.description = description;
	}
	
	public String getPrice() {
		return price;
	}
	
	public void setPrice(String price) {
		this.price = price;
	}

	public String getEvaluation() {
		return evaluation;
	}
	
	public void setEvaluation(String evaluation) {
		this.evaluation = evaluation;
	}	
}

Store the above source files in src / main / java of the project.

index.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p>Spring-Welcome to Shopsite!</p>
<a href="/login" >If you are an administrator, please click here</a>
</body>
</html>

login.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
<form th:action="@{/login_result}" th:object="${loginForm}" method="post">  
ID:<input type="text" th:field="*{id}">
<BR/>
name:<input type="text" th:field="*{name}"> 
<BR/>
<input type="submit" value="Login"/>
<BR/>
</form>
</body>
</html>

login_result.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
<div th:if="${#strings.equals(message, 'Login was successful')}">
<a href="/admin_menu">Administrator menu</a>
</div>
<div th:if="${#strings.equals(message, 'I failed to login')}">
<a href="/login">Please log in again</a>
</div>
</body>
</html>

admin_menu.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
<a href="/show_product">Display of all registered products</a>
<br/>
<a href="/register_product">Product registration</a>
<br/>
<a href="/update_product">Product update</a>
<br/>
<a href="/delete_product">Delete product</a>
</body>
</html>

show_product.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
<table th:each="product : ${products}">
<tr>
<td>
<p th:text="${product}"></p>
</td>
</tr>
</table>
</body>
</html>

register_product.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
<form th:action="@{/show_result}" th:object="${productForm}" method="post">
Product code:<input type="text" th:field="*{code}">
<BR />
Product name:<input type="text" th:field="*{name}">
<BR />
Description :<input type="text" th:field="*{description}">
<BR />
price:<input type="text" th:field="*{price}">
<BR />
Evaluation:<input type="text" th:field="*{evaluation}">
<BR />
<input type="submit" value="Registration"/>
<BR />
</form>
</body>
</html>

update_product.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
<form th:action="@{/show_result}" th:object="${productForm}" method="post">
Product code:<input type="text" th:field="*{code}">
<BR />
Product name:<input type="text" th:field="*{name}">
<BR />
Description :<input type="text" th:field="*{description}">
<BR />
price:<input type="text" th:field="*{price}">
<BR />
Evaluation:<input type="text" th:field="*{evaluation}">
<BR />
<input type="submit" value="update"/>
<BR />
</form>
</body>
</html>

delete_product.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
<form th:action="@{/afeter_delete_product}" th:object="${productForm}" method="post">
Product code:<input type="text" th:field="*{code}">
<BR />
<input type="submit" value="Delete"/>
<BR />
</form>
</body>
</html>

after_delete_product.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
</body>
</html>

show_result.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring-Shopsite</title>
</head>
<body>
<p th:text="${message}"></p>
</body>
</html>

Store the above template files in templates under src / main / resources.

in conclusion

After that, build the project and it should run normally. Of this time Unfortunately, the project cannot handle product images, but I intend to keep only the basic functions. Perhaps we will continue this project, but thank you again at that time. See you again.

By the way

I will also post pom just in case.

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>Sample-1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Sample-1</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
    
</project>

Recommended Posts

I tried to create a shopping site administrator function / screen with Java and Spring
I tried to create a java8 development environment with Chocolatey
I want to make a function with kotlin and java!
I tried to break a block with java (1)
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to modernize a Java EE application with OpenShift.
[Rails] I tried to create a mini app with FullCalendar
I want to make a list with kotlin and java!
I tried to interact with Java
[Azure] I tried to create a Java application for free ~ Connect with FTP ~ [Beginner]
I tried to create a padrino development environment with Docker
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
A new employee tried to create an authentication / authorization function from scratch with Spring Security
I tried to make a message function of Rails Tutorial extension (Part 2): Create a screen to display
I tried printing a form with Spring MVC and JasperReports 1/3 (JasperReports settings)
I tried printing a form with Spring MVC and JasperReports 3/3 (Spring MVC control)
I want to return to the previous screen with kotlin and java!
I tried to create a Spring MVC development environment on Mac
I tried to make a group function (bulletin board) with Rails
Create a simple CRUD with SpringBoot + JPA + Thymeleaf ② ~ Screen and function creation ~
I tried printing a form with Spring MVC and JasperReports 2/3 (form template creation)
I want to display images with REST Controller of Java and Spring!
I want to create a dark web SNS with Jakarta EE 8 with Java 11
How to create a server executable JAR and WAR with Spring gradle
I wrote a Lambda function in Java and deployed it with SAM
I tried to make Basic authentication with Java
java I tried to break a simple block
I tried to create a LINE clone app
I tried to link JavaFX and Spring Framework.
I tried to create Alexa skill in Java
I tried to create a portfolio with AWS, Docker, CircleCI, Laravel [with reference link]
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java
I tried printing a form with Spring MVC and JasperReports Extra edition (Variables edition)
I tried printing a form with Spring MVC and JasperReports Extra edition (image edition)
[Android] I tried to make a material list screen with ListView + Bottom Sheet
I tried to clone a web application full of bugs with Spring Boot
[Azure] I tried to create a Java application for free-Web App creation- [Beginner]
I tried to create a method to apply multiple filters at once with Java Stream API. Is this okay?
[Java] I installed JDBC and tried to connect with servlet + MySQL. (There is a version using DAO / Bean)
Create a portfolio app using Java and Spring Boot
I tried to implement file upload with Spring MVC
I tried to read and output CSV with Outsystems
I tried to implement TCP / IP + BIO with JAVA
[Java 11] I tried to execute Java without compiling with javac
Create an EC site with Rails 5 ⑨ ~ Create a cart function ~
I started MySQL 5.7 with docker-compose and tried to connect
I tried to get started with Spring Data JPA
I tried OCR processing a PDF file with Java
I tried to implement Stalin sort with Java Collector
Create a simple demo site with Spring Security with Spring Boot 2.1
I want to transition screens with kotlin and java!
I tried using Wercker to create and publish a Docker image that launches GlassFish 5.
I tried to make a message function of Rails Tutorial extension (Part 1): Create a model
I made a function to register images with API in Spring Framework. Part 1 (API edition)
Java to play with Function
I tried to summarize the basics of kotlin and java
I tried to verify this and that of Spring @ Transactional
I tried to make Java Optional and guard clause coexist