[Java / PostgreSQL] Connect the WEB application to the database

Content of this article

How to connect a database with a web application developed in Eclipse

Why I wrote this article

To check when you forget

Characteristics of the person who wrote this article

Graduated from the Faculty of Education, National University in 2011 (at that time, I had no interest in programming) After graduating from university, worked at Isetan, Recruit, etc. Around 2016-Start studying programming by self-education (You will be able to develop apps with Rails) Worked as SE from 2018

In Rails, DB settings could be processed automatically by entering a command. In Java, I have to set it myself, so I wrote this article to study it.

Development environment

PC: Mac OS: MacOS Mojave Language: Java IDE: Eclipse DB: PostgreSQL DB administration tool: pgAdmin

Prerequisites

About the database to connect to

-The database of the connection destination is the local environment (port: 5432). ・ Customer table exists in sample database -The following sample data is stored in the customer table.

SQL


SELECT * FROM customer;

Execution result


  id  |   name   |        email        | password 
------+----------+---------------------+----------
 0001 | sample1  | [email protected]  | password
 0002 | sample2  | [email protected]  | password
 0003 | sample3  | [email protected]  | password
 0004 | sample4  | [email protected]  | password
 0005 | sample5  | [email protected]  | password
 0006 | sample6  | [email protected]  | password
 0007 | sample7  | [email protected]  | password
 0008 | sample8  | [email protected]  | password
 0009 | sample9  | [email protected]  | password
 0010 | sample10 | [email protected] | password
(10 rows)

About WEB application developed in Eclipse

・ This WEB application is created as a Dynamic WEB Project. ・ This WEB application assumes to access http: // localhost: 8080 / sample / sample2

Code example

Sampleapp2.java


package jp.co.sample;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Sampleapp2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<style>table,th,td,tr{border: 1px solid black};</style>");
		out.println("<body>");
		out.println("<h1>Sampleapp by Java Servlet</h1>");
		out.println("</body>");
		out.println("</html>");
		
		String url = "jdbc:postgresql://localhost:5432/sample";
		String user = "USERNAME";
		String password = "PASSWORD";
		
		try{
			Class.forName("org.postgresql.Driver");
			System.out.println("Successful database connection");
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		
        try {
        	Connection conn = DriverManager.getConnection(url, user, password);
        	conn.setAutoCommit(false);
        	Statement stmt = conn.createStatement();
            String sql = "SELECT * FROM customer";
            ResultSet rset = stmt.executeQuery(sql);
            
            out.println("<table>");
            out.println("<tr><th>ID</th><th>UserName</th><th>Email</th></tr>");
            
            while(rset.next()) {
            	out.println("<tr><td>" + rset.getString("id") + "</td><td>" + rset.getString("name") + "</td><td>" + rset.getString("email") + "</td></tr>");
            }
            
            out.println("</table>");
        	
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
		

	}
}

point

Place the **. Jar file ** in the WEB-INF / lib directory スクリーンショット 2019-05-12 16.50.05.png

Execution result

Run the web app server and access http: // localhost: 8080 / sample / sample2

Eclipse console


May 12, 2019 4:26:33 pm org.apache.catalina.startup.VersionLoggerListener log
information: Server version name:   Apache Tomcat/9.0.14

(Omitted)

May 12, 2019 4:26:35 pm org.apache.catalina.startup.Catalina start
information:Start the server[1,215]ms
Successful database connection

Check the screen with a browser スクリーンショット 2019-05-12 16.52.01.png It was confirmed that the data stored in the database was displayed on the browser.

What I want to do in the future

Save / edit / update / delete data Cooperation with DB placed on AWS

Impressions

In Rails, a DB that can be set automatically by writing a few lines of commands and executing them. In Java, it is troublesome to have to set each one by yourself.

Recommended Posts

[Java / PostgreSQL] Connect the WEB application to the database
[Mac / Java / Eclipse / PostgreSQL] Connect Java application and database
Connect from Java to PostgreSQL
Dynamically switch the database to connect to
Connect to Aurora (MySQL) from a Java application
[Java] Connect to MySQL
How to delete the database when recreating the application
The code I used to connect Rails 3 to PostgreSQL 10
Migrate GitBucket database to postgreSQL
Connect to DB with Java
Connect to MySQL 8 with Java
Input to the Java console
[Java] Deploy the Spring Boot application to Azure App Service
Operation to connect multiple Streams @Java
[java8] To understand the Stream API
Welcome to the Java Library Swamp! !!
The road from JavaScript to Java
[PostgreSQL] If you want to delete the Rails app, delete the database first!
Connecting to a database with Java (Part 1) Maybe the basic method
[Probably the easiest] WEB application development with Apache Tomcat + Java Servlet
I want to develop a web application!
Try using Java framework Nablarch [Web application]
Update JAVA to the latest version to 1.8.0_144 (when downloading from the web and updating)
Web application structure by Java and processing flow in the presentation layer
[Java] How to use the File class
Wait for PostgreSQL to start with Docker and then start the WEB service
Java reference to understand in the figure
Introduction to java for the first time # 2
[Java] How to use the hasNext function
Java SE8 Silver ~ The Road to Pass ~
About the procedure for java to work
[Java] How to use the toString () method
Web application scheduled to be created (editing)
Java beginner tried to make a simple web application using Spring Boot
[Processing × Java] How to use the loop
[Java] How to set the Date time to 00:00:00
[Java] How to get the current directory
Deploy the WEB application by Spring Boot to Tomcat server as WAR
[Processing × Java] How to use the class
How to install the legacy version [Java]
How to get the date in java
Output of the book "Introduction to Java"
[Processing × Java] How to use the function
Volume of trying to create a Java Web application on Windows Server 2016
Creating Java Web Applications to Azure Web Apps
The story that the Servlet could not be loaded in the Java Web application
I went to the Java Women's Club # 1
[Java] Color the standard output to the terminal
[Java] How to use the Calendar class
Role of JSP in Web application [Java]
Introduction to Java Web Apps Performance Troubleshooting
Build Web Application Server (Java) on VPS
Try connecting to the Autonomous Database with JDK6 (Java) + JDBC OCI Driver (type 2).
It took a month from application to taking the Oracle Java SE 11 Silver
Sign in to a Spring Boot web application on the Microsoft ID platform
Learn while making a WEB server Introduction to WEB application development from the basics
Understand Java Serializable while actually running the application
[Java] How to use Thread.sleep to pause the program
[Rails] rails new to create a database with PostgreSQL
Deploy Java web app to Azure with maven
How to display a web page in Java