I tried running a DB access application on IKS + Db2 on IBM Cloud (6. Preparation of DB access application (java))

Introduction

This is the 6th installment of "IKS + Db2 on IBM Cloud to run the DB access app". Here, we will describe the preparation of the sample application.

The details of the implementation are as follows.

--Overview of compilation environment --Source preparation --War file output

I'm not an application developer myself, so a better way I think there are higher quality codes etc., but in this article the main purpose is to move it, Please note that quality, security, error handling, etc. are not considered. I personally don't like the hard coded table names, but don't worry.

Preparing the compilation environment

To compile from Java application source, you need an IDE (Integrated development Environment) that includes the JDK. (Strictly speaking, you can compile with just the JDK ...)

Use Eclipse for the IDE. (There is no deep meaning. Anything is fine) I'm Eclipse, but I'm a beginner, so I use Pleiades All in One Package. It seems that it can support Java EE all in one. The person who made it will have a headache. ..

Download the file for Windows from Pleiades All in One Package. (This time, we are using Eclipse 2020 in the figure below.)

49.png

At the link, download from Java Full Edition.

50.png

After downloading, unzip the zip file. (If the path is long, an error may occur, so place and expand it as short as possible.)

After unpacking, double-click eclipse.exe in the eclipse folder. On the workspace selection screen, leave the defaults and press the "Start" button.

51.png

Source preparation

After starting eclipse, the package explorer screen is displayed, so Press the "Create Project ..." link. From the window that appears, select "Dynamic Web Project" and press "Next".

52.png

Give the project name (LibertyCounter this time) and select Java8 as the target runtime. (It doesn't have to be Java8 ...) Then press the "Finish" button.

53.png

The Package Explorer will be displayed, so expand the project tree displayed there. Right-click in the src part> select "New"> "Class".

54.png

Here, the package name is counter and the class name is Counter. Specify up to that point and press "Finish".

55.png

Counter.java appears in the Package Explorer tree, and the Counter.java source appears in the right pane.

56.png 57.png

Overwrite that source window with the following source. The source itself is Deploy an existing JDBC application to Liberty (https://www.ibm.com/support/knowledgecenter/en/SSEQTP_liberty/com.ibm.websphere.wlp.doc/ae/twlp_dep_jdbc.html). ) Is based on the one described in. I will post the full text first, but after that I will pick up the point part and supplement it.

Counter.java


package counter;

import java.io.*;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.sql.DataSource;

/**
 * Servlet implementation class Counter
 */
@WebServlet("/Counter")
public class Counter extends HttpServlet {
	@Resource(name = "jdbc/sample")
	private DataSource ds1;
	private Connection con = null;
	private String hostname = null;
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Counter() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		hostname = getHostName();
		
	        response.setContentType("text/html");
	        PrintWriter out = response.getWriter();
	        out.println("<H1>Response from : "+ hostname +"</H1>\n");
	        try {
	           con = ds1.getConnection();
	           Statement stmt = null;
	           stmt = con.createStatement();

	           // check if hostname exists
	           ResultSet result = stmt.executeQuery("select distinct hostname from test01 where hostname='"+hostname+"'");
	       
	           if( !result.next() ) {
	        	   out.println("Insert hostname into test01<br>\n");
			   stmt.executeUpdate("insert into test01 values ('"+hostname+"','1')");
	           } else {
	    	       out.println("Update hostname access count in test01<br>\n");
		       stmt.executeUpdate("update test01 set count=count+1 where hostname='"+hostname+"'");
	           }
	       
		   ResultSet result2 = stmt.executeQuery("select * from test01");
		   
		   while(result2.next()) {
			   out.println("<font size=\"+2\">"+result2.getString(1)+" : </font><font size=\"+2\" color=\"red\">"+result2.getInt(2)+"</font><br>\n");
		   }
	        }	    
	        catch (SQLException e) {
		    e.printStackTrace();
	        }
                finally {
                    if (con != null){
    	                out.println("<H1>DB2 Output Completed</H1>\n");
                        try{
                            con.close();
                        }
                        catch (SQLException e) {
                           e.printStackTrace();
                        } 
                }
            }
        }

	/**
	 *  getHostName
	 * 
	 */
	
	public static String getHostName() {
	    try {
	        return InetAddress.getLocalHost().getHostName();
	    }catch (Exception e) {
	        e.printStackTrace();
	    }
	    return "UnknownHost";
	}
	
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

The following is an excerpt.

Access with / Counter. Also, use jdbc / sample as a JDBC resource for DB connection. (Hard code ...)

@WebServlet("/Counter")
public class Counter extends HttpServlet {
	@Resource(name = "jdbc/sample")

In the doGet method, use getHostName of the private method I am getting the host name. Also, as a response, the character string is stored in the form of solid HTML.

		hostname = getHostName();
		
	        response.setContentType("text/html");
	        PrintWriter out = response.getWriter();
	        out.println("<H1>Response from : "+ hostname +"</H1>\n");

Get a connection to the DB. This area is a magical target.

	        try {
	           con = ds1.getConnection();
	           Statement stmt = null;
	           stmt = con.createStatement();

The first thing to do is to use the select distinct ... SQL statement to see if hostname is already registered. If it cannot be obtained (that is, the first access), the ʻInsert statement stores the host name and the data 1 in the table. If so, the count column is +1 in the ʻUpdate statement.

	           // check if hostname exists
	           ResultSet result = stmt.executeQuery("select distinct hostname from test01 where hostname='"+hostname+"'");
	       
	           if( !result.next() ) {
	        	   out.println("Insert hostname into test01<br>\n");
			   stmt.executeUpdate("insert into test01 values ('"+hostname+"','1')");
	           } else {
	    	       out.println("Update hostname access count in test01<br>\n");
		       stmt.executeUpdate("update test01 set count=count+1 where hostname='"+hostname+"'");
	           }
	       

Then we get all the data in the table and store it in the response variable in HTML format.

		   ResultSet result2 = stmt.executeQuery("select * from test01");
		   
		   while(result2.next()) {
			   out.println("<font size=\"+2\">"+result2.getString(1)+" : </font><font size=\"+2\" color=\"red\">"+result2.getInt(2)+"</font><br>\n");

That's all for the logical part. If you are interested in other parts, please check.

War file output

Originally, it is a place to test with tomcat etc. registered in eclipse, but Skip that area and output the war file.

Right-click on the LibertyCounter project and select Export.

58.png

Open a folder on the web, select "WAR File" and press "Next".

59.png

Click the "Browse" button, specify the output destination folder / file name, and then press "Finish". The WAR file is output.

60.png


Thank you for your hard work. That's all for this time, and next time we will perform [7. Preparing the WebSphere Liberty container].

←: I tried running the DB access app on IKS + Db2 on IBM Cloud (5. Db2 on IBM Cloud preparation) ↑: I tried running the DB access app on IKS + Db2 on IBM Cloud (1. Overview) →: I tried running the DB access app on IKS + Db2 on IBM Cloud (7. Preparing the WebSphere Liberty container)


Recommended Posts

I tried running a DB access application on IKS + Db2 on IBM Cloud (6. Preparation of DB access application (java))
I tried running Java on a Mac terminal
I built a Java EE environment on AWS and tried running a web application
I tried running a letter of credit transaction application with Corda 1
I tried running Ansible on a Docker container
I tried using Log4j2 on a Java EE server
I tried to modernize a Java EE application with OpenShift.
I tried running a Docker container on AWS IoT Greengrass 2.0
I tried to make a client of RESAS-API in Java
I tried using the cache function of Application Container Cloud Service
Access Teradata from a Java application
I tried using GoogleHttpClient of Java
I tried to make a talk application in Java using AI "A3RT"
Volume of trying to create a Java Web application on Windows Server 2016
I tried running Docker on Windows Server 2019
Memory measurement of Java application on Windows
[Java] Let's make a DB access library!
I tried to clone a web application full of bugs with Spring Boot
I tried putting Java on my Mac easily
java I tried to break a simple block
I tried hitting a Java method from ABCL
I touched on the new features of Java 15
I tried to break a block with java (1)
Since I use it often, I make a note of DB related things on Android.
[Azure] I tried to create a Java application for free ~ Connect with FTP ~ [Beginner]
I want to implement it additionally while using kotlin on a site running Java
I tried using Google Cloud Vision API in Java
Deploy Java apps on the IBM Cloud Kubernetes service
I tried to create a Clova skill in Java
I tried OCR processing a PDF file with Java
I tried scraping a stock chart using Java (Jsoup)
[October 2019 version] I tried running a demo of SSO of Quarkus REST API with KeyCloak with docker-compose.
I tried to make the sample application into a microservice according to the idea of the book "Microservice Architecture".
I tried to develop a web application from a month and a half of programming learning history
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.
I tried to develop the cache function of Application Container Cloud Service in the local environment