Friday, February 13, 2015

Getting data to table in a jsp file from an SQL database.

Follow the steps to get the data from a SQL database to a jsp file.

Here in this tutorial we are creating two java classes and one jsp file to import the data from a SQL database. First we’ll create the two java classes.

Here I am creating this to get user details so, first I’m creating a java class called “users” with the getters and the setters.
First we declare the variables

private String username;
private String password;

then we create the getters and the setters to get data and to change the data.

public User() {
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
   




Then in the other java class we write the database queries to get the data from the database.
First write these import statements in the java class

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import pac.DatabaseConnection;

Then in the java class we write the below code which includes the SQL query

String sql="Select *from admin_users";
        DatabaseConnection db=new DatabaseConnection();
        ResultSet rs=db.getResult(sql, db.SetConnection());
        ArrayList<User> ar=new ArrayList<User>();
        while(rs.next()){
           User user=new User();
           user.setUsername(rs.getString(1));
           user.setPassword(rs.getString(2));
           ar.add(user);
        }
      
        return ar;
    }




Here in the above code we have inserted the sql query in the string and we have create a constructor and used the setters to get the data from the database. Then at last we return the resultset.
Then in the jsp file we create a table and view the data from the database. Below is the code for the jsp file.

<%@page import="user.User"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>UserDetails</title>
    </head>
    <body>
      
In the above code the java coding is written between <% %> tags.



No comments:

Post a Comment