connect JSP with mysql in Linux

Let us make a simple application to connect and access mysql database from jsp code. This covers example jsp program to connect mysql, installing apache tomcat server, configuring mysql connector to establish jdbc driver, setting up the connection. 1st application using jsp.

To run a java server page in localhost, we need to setup a server.

Installing Latest Apache Tomcat server :

Run the following command in the terminal,

                         sudo apt-get install tomcat8            

To test whether tomcat is installed and working, do the following. Run the below url in a browser.

                           http://localhost:8080/

installing apache tomcat8 in linux

______________________________________________________________________________

 

Installing JDBC Driver:

JDBC driver (connector J) is required to establish a  connection between mysql and jsp.

             1.Download mysql Connector/J from here

             2.Run the following command

              sudo nautilus         

             3.Extract and paste the jar file in the location /usr/share/tomcat8/lib

Restart the tomcat server

                     sudo /etc/init.d/tomcat8 restart      
If you are using tomcat version 7 then change the number accordingly.
 
Last step is to create jsp page to access database. Also data can be read or fetched.
Change password and database name in the below code.
 

<!DOCTYPE HTML>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <html>

    <head>
    <title>Techie Tet | Mysql connectivity</title>
    </head>
    <body>
    <h1>Connection status </h1>
    <%
    try {
    String connectionURL = "jdbc:mysql://localhost:3306/pph";
    Connection connection = null;
    // Load JBBC driver "com.mysql.jdbc.Driver"
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    /* user name = root
    password =ur mysql password. */
    connection = DriverManager.getConnection(connectionURL, "root", "can");
    if(!connection.isClosed())
    %>
    <font size="+3" color="green"></b>
    <%
    out.println("Successfully connected to " + "MySQL server using TCP/IP...");
    connection.close();
    }
    catch(Exception ex){
    %>
    </font>
    <font size="+3" color="red"></b>
    <%
    out.println("Unable to connect to database."+ex);
    }
    %>
    </font>
    <p>TechieTet.com</p>
    <p>For more details..<a href=" http://techietet.com">Visit</a></p>
    </body>
    </html>

 
Save the above code as test.jsp in the location /var/lib/tomcat8/webapps/ROOT/
Java server page should go inside ROOT folder. I hope you still not closed the window, which opened using sudo nautilus command. It gives super user  permission to paste the test.jsp in that location.
 
Run the test.jsp page in browser : http://localhost:8080/test.jsp
run jsp page in browser
 
 
Jsp program to fetch or read mysql table contents