MySQL classNotFoundException & no suitable Driver found for jdbc - java

I'm new to study JSP.
I have added this jar file mysql-connector-java-5.1.38-bin.jar
mysql-connector
The IML file:
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/mysql-connector-java-5.1.38/mysql-connector-java-5.1.38/mysql-connector-java-5.1.38-bin.jar!/" />
</CLASSES>
I made a class of a table like this:
package test;
public class Student {
private int id;
private String name;
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public Student(int id,String name){
super();
this.name = name;
this.id = id;
}
}
and a operating class:
package test;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StudentOperation {
public List readStudent(){
List<Student> list = new ArrayList<>();
com.mysql.jdbc.Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
try{
connection = (com.mysql.jdbc.Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root",null);
String sql = "SELECT * FROM student WHERE student_id>=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String studentName = resultSet.getString("student_name");
int studentId = resultSet.getInt("student_id");
Student student = new Student(studentId,studentName);
list.add(student);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
try{
if(resultSet!=null){
resultSet.close();
}
if(preparedStatement!=null){
preparedStatement.close();
}
if(connection!=null){
connection.close();
}
}catch (SQLException e){
e.printStackTrace();
}
}
return list;
}
public static void main(String[] args){
StudentOperation studentOperation = new StudentOperation();
List<Student> list = studentOperation.readStudent();
System.out.println(list.size());
for(Student student : list){
System.out.println(student.getName()+"\t");
System.out.println(student.getId());
}
}
}
run the main method, it output the result like this:
3
student3
201592385
student2
201592386
student1
201592387
It's the right result. But when I add to the jsp file:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="test.Student" %>
<%# page import="test.StudentOperation" %>
<%# page import="java.util.List" %>
<html>
<head>
<title>Homework</title>
</head>
<body>
<h1 align="center">Student Database</h1>
<table border="1">
<tr>
<td>Student Name</td>
<td>Student ID</td>
</tr>
<%
try {
StudentOperation studentOperation = new StudentOperation();
List<Student> list = studentOperation.readStudent();
for(Student student : list){ %>
<tr>
<td><%= student.getName() %></td>
<td><%= student.getId() %></td>
</tr>
<% }
}catch (Exception e){e.printStackTrace();}
%>
</table>
</body>
</html>
It is like this:
the result
And throw the exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/student
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
What's wrong?

put the jar of driver in the server lib folder
i.e. at ($CATALINA_HOME/lib) Then check. Hope it helps

Related

How to fetch data from dynamically generated JSP page in Struts 2?

I am generating below page using Struts2. It is generating properly.
My question is how fetch the value from generated page when I click on delete button so I can further process for delete data from database and regenerate page with remaining data?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s" %>
<!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>
<h3>All Records:</h3>
<table>
<s:form action="upload">
<s:iterator value="list">
<tr>
<td ><s:property value="id"/></td>
<td ><s:property value="name"/></td>
<td><s:property value="password"/></td>
<td><s:property value="email"/></td>
<td><s:property value="gender"/></td>
<td><s:checkbox name="checked" label="isChecked" theme="simple" /></td>
</tr>
</s:iterator>
<s:submit value="delete" name="delete" />
</s:form>
</table>
</body>
</html>
RegisterAction.java
package com.javatpoint;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class RegisterAction {
private String name,password,email,gender,country;
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
public String execute(){
int i=RegisterDao.save(this);
if(i>0){
Connection con=RegisterDao.con;
try {
PreparedStatement ps=con.prepareStatement("select * from STRUTSUSER");
ResultSet rs=ps.executeQuery();
// rs = ps.getGeneratedKeys();
while(rs.next()){
User user=new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(1));
user.setPassword(rs.getString(2));
user.setEmail(rs.getString(3));
user.setGender(rs.getString(4));
list.add(user);
// System.out.println("yo");
}
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
return "error";
}
you can try something as below:
public class RegisterAction {
....
public String execute(){
...
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
Connection con=RegisterDao.con;
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from STRUTSUSER");
while (rs.next())
{
User user = new User();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("id");
deleteUser(userId);
return SUCCESS;
}
private void deleteUser(int userId)
{
Connection con=RegisterDao.con;
try
{
PreparedStatement ps = conn.prepareStatement("delete from STRUTSUSER where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
JSP page : view.jsp
<s:iterator value="list">
...
</s:iterator>
<s:hidden name="id" value="%{#list.id}" />
<s:submit value="delete" name ="delete" action="deleteUserAction"/>
In Struts.xml
<action name="deleteUserAction" class="example.RegisterAction" method="delete">
<result name="success">view.jsp</result>
</action>
After deleting user, you can call getAllUsers() from action
Hope this Helps

delete from jsp view. can't get the table id while deleting it’s row

My task: I have to delete operation over the table “testtable” each row from jsp view.
My problem: not able to get the table id while deleting it’s row.
Application technology used: jsp as view , servlet as controller, setter and getter method as model and jdbc code for database operation.
Backend mysql:=I have two table one “userinfo” for aurtherntication and another table “testtable”.
For the two table connection I have used hidden field input in jsp as instead of using foreign key relation.
In the console print we can see after clicking the delete button
com.mysql.jdbc.JDBC4PreparedStatement#1f4bcaf: delete from testtable where id=0 and email='myswagt#yahoo.com'
at home servlet
userid is 0
please help me according to jsp,servlet,model,jdbc post below:
//expense model
package com.intermediateDemo.home.dto;
public class ItemBean {
private int id;
private String email;
private String itemName;
private Double itemPrice;
private String transactionTime;
private int userid;
public ItemBean() {
}
public ItemBean(int id, String email, String itemName, Double itemPrice, String transactionTime) {
this.id = id;
this.itemName = itemName;
this.itemPrice = itemPrice;
this.transactionTime = transactionTime;
this.email = email;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n----------------------------------------------------------------------------------------------\n");
stringBuilder.append("Id: " + id);
//stringBuilder.append("\tName: " + firstName + ' ' + middleName + ' ' + lastName);
stringBuilder.append("\titemname: " + itemName);
stringBuilder.append("\titemprice: " + itemPrice);
stringBuilder.append("\ttime: " + transactionTime);
stringBuilder.append("\n----------------------------------------------------------------------------------------------\n");
return stringBuilder.toString();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Double getItemPrice() {
return itemPrice;
}
public void setItemPrice(Double itemPrice) {
this.itemPrice = itemPrice;
}
public String getTransactionTime() {
return transactionTime;
}
public void setTransactionTime(String transactionTime) {
this.transactionTime = transactionTime;
}
}
//user model
package com.intermediateDemo.login.dto;
public class LoginBean {
private int userid;
private String email;
private String password;
public boolean valid;
private String lastName;
private String firstName;
public LoginBean() {
}
public LoginBean(String email, String lastname, String firstname) {
this.email = email;
this.firstName = firstname;
this.lastName = lastname;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
//delete servlet
package com.intermediateDemo.home.controller;
import com.intermediateDemo.home.dao.ItemDao;
import com.intermediateDemo.home.dao.ItemDaoFactory;
import com.intermediateDemo.home.dto.ItemBean;
import com.intermediateDemo.login.dto.LoginBean;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class DeleteExpense extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, ServletException, IOException {
ItemBean item = new ItemBean() ;
try {
ItemDao dao = ItemDaoFactory.getItemDao();
HttpSession session = request.getSession(false);
LoginBean user = (LoginBean) session.getAttribute("user");
item.setId(Integer.parseInt(request.getParameter("id")));
item.setEmail(user.getEmail());
dao.deleteItem(item, user);
} catch (Exception e) {
e.printStackTrace();
}
finally {
response.sendRedirect("homeservlet");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher view;
view = request.getRequestDispatcher("/home/home.jsp");
view.forward(request,response);
}
}
//jdbc code
public void deleteItem(ItemBean item, LoginBean user) throws Exception {
try {
JdbcConnection connection = new JdbcConnection();
String query = "delete from testtable where id=? and email=?";
Connection con = connection.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
pstm.setInt(1, item.getId());
pstm.setString(2, user.getEmail());
System.out.println(pstm);
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
//jsp view
<%--
Created by IntelliJ IDEA.
User: Dell
Date: 3/13/14
Time: 8:12 PM
To change this template use File | Settings | File Templates.
--%>
<%# page import="com.intermediateDemo.home.dto.ItemBean" %>
<%# page import="java.util.List" %>
<%# page import="com.intermediateDemo.login.dto.LoginBean" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>home</title>
<link rel="stylesheet" type="text/css" href="style_css/mystylesheet.css">
<link rel=”stylesheet” href=”resource/css/bootstrap.css” type=”text/css”/>
</head>
<body>
<jsp:include page="../includes/header.jsp"/>
<div id="content" style="margin-left: 330px;margin-bottom: 10px">
Welcome <%=session.getAttribute("email")%>
your id is <%=session.getAttribute("userid")%>
your firstname is <%=session.getAttribute("firstname")%>
<h2>Your Financial Management</h2>
<form action="homeservlet" method="post">
<!--start display-->
<legend>
<h2>Expense list</h2>
</legend>
<div>
<table class="table table-bordered table-striped" style="padding- left:200px;border:2px;border-bottom-color: limegreen">
<thead>
<tr style="background: limegreen">
<th >Expense title</th>
<th>Expense amount</th>
<th>Expense Date</th>
</tr>
</thead>
<tbody>
<c:forEach var="item" items="${requestScope.itemList}" >
<tr style="background:#808080;color:#ffffff">
<td><c:out value="${item.getItemName()}"> </c:out></td>
<td><c:out value="${item.getItemPrice()}"> </c:out></td>
<td><c:out value="${item.getTransactionTime()}"> </c:out></td>
<td>
<form method="post" action="/deleteexpense">
<input type="hidden" name="id" value="${item.id}">
<input class="btn btn-mini btn-danger " type="submit" value="Delete"/>
<a class="btn btn-mini " href="edit?id=${item.id}">Edit</a>
</form>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</form>
</div>
<jsp:include page="../includes/footer.jsp"/>
</body>
</html>
//DAO where I retrieve the data of ItemBean
public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
List<ItemBean> itemList = new ArrayList<ItemBean>();
JdbcConnection connecton = new JdbcConnection();
//String query = "select * from testtable where userid = ?";
String query = "select * from testtable where email = ?";
ResultSet rs;
try {
Connection con = connecton.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
// pstm.setInt(1, user.getUserid());
pstm.setString(1,user.getEmail());
rs = pstm.executeQuery();
while (rs.next()) {
ItemBean item = new ItemBean();
item.setItemName(rs.getString("itemname"));
item.setItemPrice(rs.getDouble("itemprice"));
item.setTransactionTime(rs.getString("transactiontime"));
// item.setUserid(rs.getInt("userid"));
item.setEmail(rs.getString("email"));
itemList.add(item);
}
System.out.println("at jdbc code");
for (ItemBean item1 : itemList) {
System.out.println(item1.getItemName());
System.out.println(item1.getItemPrice());
System.out.println(item1.getTransactionTime());
}
} catch (SQLException e) {
e.printStackTrace();
}
return itemList;
}
//jdbc code for item insert,retrieve and delete like operation in one page is
package com.intermediateDemo.home.dao.mysql;
import com.intermediateDemo.common.JdbcConnection;
import com.intermediateDemo.home.dto.ItemBean;
import com.intermediateDemo.login.dto.LoginBean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class JdbcItemMysql {
public void itemtodb(ItemBean item, LoginBean user) throws Exception {
JdbcConnection connection = new JdbcConnection();
//String query = "insert into testtable (itemname,itemprice,transactiontime,userid) values (?,?,?,?)";
String query = "insert into testtable (itemname,itemprice,transactiontime,email) values (?,?,?,?)";
try {
Connection con = connection.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
pstm.setString(1, item.getItemName());
pstm.setDouble(2, Double.parseDouble(String.valueOf(item.getItemPrice())));
pstm.setString(3, item.getTransactionTime());
pstm.setString(4, user.getEmail());
// pstm.setInt(4,user.getId());
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
List<ItemBean> itemList = new ArrayList<ItemBean>();
JdbcConnection connecton = new JdbcConnection();
//String query = "select * from testtable where userid = ?";
String query = "select * from testtable where email = ?";
ResultSet rs;
try {
Connection con = connecton.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
// pstm.setInt(1, user.getUserid());
pstm.setString(1,user.getEmail());
rs = pstm.executeQuery();
while (rs.next()) {
ItemBean item = new ItemBean();
item.setItemName(rs.getString("itemname"));
item.setItemPrice(rs.getDouble("itemprice"));
item.setTransactionTime(rs.getString("transactiontime"));
// item.setUserid(rs.getInt("userid"));
item.setEmail(rs.getString("email"));
itemList.add(item);
}
System.out.println("at jdbc code");
for (ItemBean item1 : itemList) {
System.out.println(item1.getItemName());
System.out.println(item1.getItemPrice());
System.out.println(item1.getTransactionTime());
}
} catch (SQLException e) {
e.printStackTrace();
}
return itemList;
}
public void deleteItem(ItemBean item, LoginBean user) throws Exception {
try {
JdbcConnection connection = new JdbcConnection();
String query = "delete from testtable where id=? and email=?";
Connection con = connection.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
pstm.setInt(1, item.getId());
pstm.setString(2, user.getEmail());
System.out.println(pstm);
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
You are not passing the record id to the jsp page from your method. Your getItemFromdb() should be some thing like this
public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
// whatever you are doing comes here
while (rs.next()) {
ItemBean item = new ItemBean();
item.setId(rs.getInt("id"); // you need to have this, here id is the the primary key of the table
item.setItemName(rs.getString("itemname"));
item.setItemPrice(rs.getDouble("itemprice"));
item.setTransactionTime(rs.getString("transactiontime"));
// item.setUserid(rs.getInt("userid"));
item.setEmail(rs.getString("email"));
itemList.add(item);
}
// rest of the code
}
so that in the jsp page you can use this id to identify the record do whatever operation you want to do

How can i display all column of a database table using servlet and jsp

I have a database table users containing columns id(int),name(string),department(string),password(string).I am storing table contents in an arrayList object in a servlet (display.java) and then forwarding it to a jsp page(home1.jsp). But i am unable to display all tables using that jsp page.Id contents is not showing and the columns of table has been shifted 1 unit right. i.e not under correct header.
#WebServlet("/Display3")
public class Display3 extends HttpServlet {
private static final long serialVersionUID = 1L;
public Display3() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
Statement st;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/test?user=root&password=Tpg#1234");
ArrayList al=null;
ArrayList userList =new ArrayList();
String query = "select id,name,department,password from users";
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
al = new ArrayList();
al.add(rs.getInt(1));
al.add(rs.getString(2));
al.add(rs.getString(3));
al.add(rs.getString(4));
userList.add(al);
}
request.setAttribute("userList",userList);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/home1.jsp");
dispatcher.forward(request,response);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
the jsp code is here
<%# page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*;" %>
<!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>
<script language ="javascript">
function editData(id){
}
function deleteData(id){
}
</script>
</head>
<body>
<br>
<table align="center">
</table>
<br>
<table border='1' width='300' cellpadding='1' cellspacing='0'>
<tr>
<td colspan=6 align="center"></td>
</tr>
<tr>
<td>Id</td>
<td>Name</td><td>Department</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<%
List Li = new ArrayList();
Iterator lr;
if(request.getAttribute("userList")!=null && request.getAttribute("userList")!="")
{
List userList = (ArrayList)request.getAttribute("userList");
Iterator itr = userList.iterator();
while(itr.hasNext())
{
Li = (ArrayList)itr.next();
lr = Li.iterator();
Integer id = (Integer)lr.next();
%>
<tr>
<%
while(lr.hasNext())
{
%>
<td><%=lr.next()%></td>
<%
}
%>
<td><input type="button" name="edit" value="edit" onclick="editData(<%=id%>);" ></td>
<td><input type="button" name="delete" value="Delete" onclick="deleteData(<%=id%>);"></td>
</tr>
<%
}
}
%>
}
</table>
</body>
</html>
When you cast Integer id = (Integer)lr.next(); you are shifting the position of the iterator by one position.
The method Iterator#next() automatically moves your iterator by one position. When in your while you call
<td><%=lr.next()%></td>
you start from 2nd position, leaving out your id.
I strongly suggest you to read about generics for your array list, object-relational mapping and above all foreach loop.
The most important is ORM, you should create a POJO java class to contain a row of your table:
public class User {
int id;
String name;
String departament;
String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartament() {
return departament;
}
public void setDepartament(String departament) {
this.departament = departament;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Then you can iterate your result set and add a new user for each row:
//...
List<User> users = new ArrayList<User>();
//...
while(rs.next())
{
user = new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setDepartament(rs.getString(3));
user.setPassword(rs.getString(4));
users.add(user);
}
now you can iterate over the list using
for(User user: users){
//Whatever...
}
In iterator Once you have called the .next() the pointer is moved to next element. Since you have called the id using Integer id = (Integer)lr.next();. The pointer will move to the next value in the list. So if you are trying to print the id in <td><%=lr.next()%></td> it wont. Instead it will print the name.
instead you can change your jsp with the below one
Integer id = (Integer)lr.next();
%>
<tr>
<td><%=id%></td>
<%
while(lr.hasNext())
{
%>
<td><%=lr.next()%></td>
<%
}

How to download data from database into JSP table?

To be shortly: here is simple web app. On the main page there is a button, after clickig on it it has to be another page with table that contains data from database.
Im using servlets/jsp MySQL
Here is code
Main page
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>University</title>
</head>
<body>
<h2 style="text-align: center">Welcome to university!</h2>
<p style="text-align: center"><img src="Images/university.jpg"></p>
<form>
<p style="text-align: center">
<button formmethod="GET" formaction="SelectStudents.do">See all students</button>
</p>
</form>
</body>
</html>
Page with table
<%# page import="java.util.List" %>
<%# page import="model.StudentDAO" %>
<%# page import="model.Student" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Students</title>
</head>
<body>
<table border="1" >
<caption>Students</caption>
<tr>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
<th>Country</th>
<th>City</th>
<th>Street</th>
<th>House</th>
<th>Flat</th>
<th>Group</th>
</tr>
<%
List<Student> students = new StudentDAO().selectAll();
for (Student s : students) {
%>
<tr>
<td><%=s.getId()%>></td>
<td><%=s.getName()%>></td>
<td><%=s.getSurname()%>></td>
<td><%=s.getAge()%>></td>
<td><%=s.getAddress().getCountry()%>></td>
<td><%=s.getAddress().getCity()%>></td>
<td><%=s.getAddress().getStreet()%>></td>
<td><%=s.getAddress().getHouseNumber()%>></td>
<td><%=s.getAddress().getFlatNumber()%>></td>
<td><%=s.getGroup().getName()%>></td>
</tr>
<%
}
%>
</table>
</body>
</html>
Class Student
public class Student {
private int id;
private String name;
private String surname;
private int age;
private Address address;
private Group group;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String name) {
this.surname = surname;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
public void setGroup(Group group) {
this.group = group;
}
public Group getGroup() {
return group;
}
}
JDBCConnecto
package model;
import java.sql.*;
public class ConnectionManager {
private static final String JDBC_LOADER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/";
private static final String LOGIN = "root";
private static final String PASSWORD = "15021990";
private Connection connection;
public ConnectionManager() throws ClassNotFoundException, SQLException{
Class.forName(JDBC_LOADER);
connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
}
public Connection getConnection() throws SQLException{
return connection;
}
}
DAO
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
private static final String SELECT_ALL =
"SELECT student.id, student.name, student.surname, student.age, \n" +
"\t address.country, address.city, address.street, address.house, address.flat, \n" +
"\t class.name\n" +
"\t FROM University.student join University.address \n" +
"\t on university.student.address = university.address.id join university.class\n" +
"\t on university.student.class = university.class.id";
public List<Student> selectAll() {
List<Student> result = new ArrayList<Student>();
Connection c = null;
try {
c = new ConnectionManager().getConnection();
Statement s = c.createStatement();
ResultSet students = s.executeQuery(SELECT_ALL);
while (students.next()) {
int id = students.getInt(1);
String name = students.getString(2);
String surname = students.getString(3);
int age = students.getInt(4);
String country = students.getString(5);
String city = students.getString(6);
String street = students.getString(7);
int house = students.getInt(8);
int flat = students.getInt(9);
String groupName = students.getString(10);
Address address = new Address();
address.setCountry(country);
address.setCity(city);
address.setStreet(street);
address.setHouseNumber(house);
address.setFlatNumber(flat);
Group group = new Group();
group.setName(groupName);
Student student = new Student();
student.setId(id);
student.setName(name);
student.setSurname(surname);
student.setAge(age);
student.setAddress(address);
student.setGroup(group);
result.add(student);
}
} catch (SQLException e) {
System.out.print(e.getErrorCode());
} catch (ClassNotFoundException e) {
} finally {
try {
if (c != null)
c.close();
} catch (SQLException e) {
System.out.print(e.getErrorCode());
}
}
return result;
}
}
Servlet
package controller;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class StudentsSelect extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher view = request.getRequestDispatcher("table.jsp");
try {
view.forward(request, response);
} catch (ServletException e) {
} catch (IOException e) {
}
}
}
The problem is that after pressing the button there is no information about students in table in table.jsp.
You obviously forgot to add your MySQL connector (select platform independent and click download zip package, if your didn't download it). Add MySQL connector jar file to lib directory in your project. That should solve your problem.

Java EE Struts 2- combo box- database retrieving of elements for a drop down

my jsp file is:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="java.util.*" %>
<%# page import="com.elc.util.*" %>
<%#taglib uri="/struts-tags" prefix="s" %>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Select Your Department</h1>
<s:form action="Comapny">
<table bordercolor="red">
<tr>
<td>Select your Option</td>
<td>
<s:combobox name ="Depart"list="%{depat}" value="Select" headerValue="-1"
headerKey="select your option"></s:combobox>
</td>
</tr>
<tr>
<td></td>
<td>
<s:submit value="Select"></s:submit>
</td>
</tr>
</table>
</s:form>
</body>
</html>
AAnd my Action class is...
package com.elc.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")
public class Department extends ActionSupport {
private String Dept;
private List<Object> depat;
public List<Object> getDepat() {
return depat;
}
public void setDepat(List<Object> depat) {
this.depat = depat;
}
public String getDept() {
return Dept;
}
public void setDept(String dept) {
Dept = dept;
}
//#SuppressWarnings("unchecked")
public String Select(){
Collection<String> o = DBConnection.getConnection();
depat = new ArrayList<Object>();
Iterator<String> i = o.iterator();
while(i.hasNext()){
depat.add(i);
}
System.out.println("the list contains..........."+depat);
return "success";
}
//#SuppressWarnings("static-access")
public String execute(){
return SUCCESS;
}
}
my DAO class is.......
package com.elc.action;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
public class DBConnection {
public static Collection<String> getConnection(){
ArrayList<String> l = new ArrayList<String>();
try{
Class.forName(DBConstants.Driver);
Connection con = DriverManager.getConnection(DBConstants.url,
DBConstants.userName, DBConstants.password);
Statement st = con.createStatement();
String query = DBConstants.SELECT +"* from role";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
rs.getInt(1);
String dept = rs.getString(2);
l.add(dept);
}
}catch(ClassNotFoundException c){
System.out.println("the classs u are asking not found");
c.printStackTrace();
}catch(SQLException s){
System.out.println("the sql exception is occured");
s.printStackTrace();
}
return l;
}
}
firstly i have used return of Object in my DBConnection.getconnection method it retrieved my table as[HR,Tester, Software Engineer] but when i use to drop down in my web they were coming as it is...i.e [HR,Tester, Software Engineer] so i want the output as first Hr and beneath of that Tester and beneath of that Software engineer. when i use Collection or List return in DBConnection.getconnection method i got jasper exception..
will anyone tell me the answer.....
my jsp does not have any errors and i changed my Action class it is only i am posting now.. remaining program is same only...
public class Department extends ActionSupport {
#SuppressWarnings("rawtypes")
ArrayList deptList;
#SuppressWarnings("rawtypes")
public ArrayList getDeptList() {
return deptList;
}
#SuppressWarnings("rawtypes")
public void setDeptList(ArrayList deptList) {
this.deptList = deptList;
}
public String Select(){
deptList = DBConnection.getConnection();
System.out.println("the list contains..........."+deptList);
return "checked";
}
public String execute(){
return SUCCESS;
}
}
firstly i created a Collection interface and i didn't have getters and setters to that variable.. now i created a Arraylist and have getters and setters now it is working fine.....
public class Mainlist {
DBLayer db;
public Mainlist() {
db = new DBLayer();
}
public ArrayList getCategoryname() {
ArrayList<String> list = new ArrayList();
try {
String sql = "select category_name from category";
PreparedStatement ps = db.getConnection().prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs != null) {
while (rs.next()) {
list.add(rs.getString("category_name"));
// System.out.println(list);
}
}
return list;
} catch (Exception e) {
e.printStackTrace();
return list;
}
}
}

Categories