hana
hana

Reputation: 13

How to properly display Mysql tables using servlets and java?

I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected) So, basically, in mySql i write this,

create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');

and i create loginDisp.java in the servlet using eclipse. This is my command

 package Servlet;

import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class loginDisp extends HttpServlet {
  public void service(HttpServletRequest request,
  HttpServletResponse response)
  throws IOException, ServletException{
    //  String username=request.getParameter("Username");
     // String password=request.getParameter("Password");

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head><title>Servlet JDBC</title></head>");
  out.println("<body>");
  out.println("<h1>Servlet JDBC</h1>");
  out.println("</body></html>");  
  // connecting to database
  Connection con = null;  
  Statement stmt = null;
  ResultSet rs = null;
  try {
  Class.forName("com.mysql.jdbc.Driver");
  con =DriverManager.getConnection 
  ("url/tablename","uname","pssword");
  stmt = con.createStatement();
  rs = stmt.executeQuery("SELECT * FROM login2");
  // displaying records
  while(rs.next()){
  out.print(rs.getObject(1).toString());
  out.print("\t\t\t");
  out.print(rs.getObject(2).toString());
  out.print("<br>");
  }

  } catch (SQLException e) {
 throw new ServletException("Servlet Could not display records.", e);
  } catch (ClassNotFoundException e) {
  throw new ServletException("JDBC Driver not found.", e);
  } finally {
  try {
  if(rs != null) {
  rs.close();
  rs = null;
  }
  if(stmt != null) {
  stmt.close();
  stmt = null;
  }
  if(con != null) {
  con.close();
  con = null;
  }
  } catch (SQLException e) {}
  }
  out.close();
  }
  }

When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<body>
<center>
    <div class="wrapper">
    <br>
    <br>
    <h2>Doctor</h2>

    <form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
        <table width="326" border="1" align="center">
        <center> <tr>
                <th width="138" scope="row">Username</th>
                <td width="142"><input type="text" name="Username"></td>

            </tr>
            </center>


            <tr>
                <th height="31" style="width: 162px;"><span class="style2">Password</span>
                </th>

                <td width="142"><input type="password" name="Password"></td>
            </tr>

            <tr>


            </tr>
        </table>
        <p align="center">
                    <input type="submit" name="Submit" value="Submit">
                </p> ${message}
    </form>
    </div>
    </center>

</body>

</body>
</html>

and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java

package Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

 //Get username and password from the JSP page


String username=request.getParameter("Username");
String password=request.getParameter("Password");

//Print the above got values in console

System.out.println("The username is" +username);

System.out.println("\nand the password is" +password);
    }
}

The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.

Upvotes: 1

Views: 17790

Answers (3)

Elorry
Elorry

Reputation: 33

Create a new package (called dao or model) where you put your logic to access to the DB.

Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.

package model: class DaoAccess (methods to connect with DB) class Login (properties of the table with getXXX and setXXX of each one)

package Servlet. class loginDisplay:

    public class loginDisplay extends HttpServlet {
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Servlet JDBC</title></head>");
        out.println("<body>");
        out.println("<h1>loginDisplay</h1>");
        out.println("</body></html>");
        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        DaoAccess dao = new DaoAccess();

        List<Login> list = dao.readAll();

        for(Login obj: list){
            out.write(obj.getName());
            out.write(obj.getPassword());
        }
        out.close();
    }
}

Upvotes: 0

Shivam
Shivam

Reputation: 714

You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use

  <servlet>
    <servlet-name>log</servlet-name>
    <servlet-class>loginDisplay</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>log</servlet-name>
    <url-pattern>/loginDisplay</url-pattern>
  </servlet-mapping>

and now you can use the action = "loginDisplay" in the action tag and by using this

I hope you did not face the problem of 404 error.

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 122026

You entered a wrong action in form.

Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml

action="loginDisplay.java"  

should be action="/loginDisplay"

<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">

It should be

<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">

If /loginDisplay is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.

A quick example

Upvotes: 1

Related Questions