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
Related
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
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
Here I come up with problem with Operation like update,delete and view so now insert is working but other operation like update, delete, view showing error like. Could some one can guide to go right direction? This what I have tried up to now
Error:
HTTP Status 500 - java.lang.NullPointerException
type Exception report
message java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.NullPointerException
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
root cause
java.lang.NullPointerException
Action.Testiue.view(Testiue.java:115)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml" />
<package name="a" extends="struts-default">
<action name="adduser" class="Action.Testiue" method="add">
<result name="success">/insert.jsp</result>
<result name="success">/ssuccess.jsp</result>
</action>
<action name="viewuser" class="Action.Testiue" method="view">
<result name="success">/view.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="updateuser" class="Action.Testiue" method="update">
<result name="success">/edit.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="deleteuser" class="Action.Testiue" method="delete">
<result name="success">/dsuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
TestIUE.java
package Action;
import com.opensymphony.xwork2.ActionSupport;
import dao.UserDao;
import dbBean.UseBean;
public class Testiue
{
private String Name;
private String Password;
private String EmailID;
private String Phoneo;
private int ID;
public String getName()
{
return Name;
}
public void setName(String name)
{
Name = name;
}
public String getPassword()
{
return Password;
}
public void setPassword(String password)
{
Password = password;
}
public String getEmailID()
{
return EmailID;
}
public void setEmailID(String emailID)
{
EmailID = emailID;
}
public String getPhoneo()
{
return Phoneo;
}
public void setPhoneo(String phoneo)
{
Phoneo = phoneo;
}
public int getID()
{
return ID;
}
public void setID(int i)
{
ID = i;
}
#Override
public String toString()
{
return "UseBean [id=" + ID + ", Name=" + Name+ ", Password=" + Password + ", EmailID=" + EmailID + ", Phoneo="+ Phoneo + "]";
}
private UserDao dao;
private UseBean bean;
public String add()
{
dao=new UserDao();
bean=new UseBean();
System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.addUser(bean);
return ActionSupport.SUCCESS;
}
public String update()
{
dao=new UserDao();
bean=new UseBean();
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.updateUser(bean);
return ActionSupport.SUCCESS;
}
public String delete()
{
int userId =0;
dao.deleteUser(userId);
return ActionSupport.SUCCESS;
}
public String edit()
{
int userId =0;
bean = dao.getUserById(userId);
return ActionSupport.SUCCESS;
}
public String view()
{
dao.getAllUsers();
return ActionSupport.SUCCESS;
}
}
Index.jsp
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=viewuser.action">
view.jsp;
<%# taglib prefix="s" uri="/struts-tags"%>
<%#page import="java.util.*,dbBean.*,Dbconnect.*,java.util.*"%>
Insert
<table border=1>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>password</th>
<th>phoneno</th>
<th>emailid</th>
<th colspan=2>Action</th>
</tr>
</thead>
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
<tbody>
<tr>
<td><%= user.getID() %></td>
<td><%= user.getName() %></td>
<td><%= user.getPassword() %></td>
<td><%= user.getEmailID() %></td>
<td><%= user.getPhoneo() %></td>
<td>Update</td>
<td>Delete</td>
</tr>
<%
}
%>
</tbody>
</table>
edit.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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>
<form action="updateuser">
id:<input type="text" name="ID" ><br/>
Name:<input type="text" name="Name" ><br/>
Password:<input type="text" name="password" ><br/>
phoneno:<input type="text" name="Phoneo" ><br/>
Emailid:<input type="text" name="Emailid" > <br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
UserDao.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import dbBean.UseBean;
import Dbconnect.*;
public class UserDao
{
private Connection conn;
public UserDao()
{
conn=Dbconnect.getConnection();
}
public void addUser(UseBean bean)
{
try
{
String sql="insert into senthil (name,pass,phoneno,emailid) values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,bean.getName());
ps.setString(2,bean.getPassword());
ps.setString(3,bean.getPhoneo());
ps.setString(4,bean.getEmailID());
ps.executeUpdate();
}
catch (Exception e)
{
// TODO: handle exception
}
}
public void deleteUser(int userId)
{
try
{
PreparedStatement ps = conn.prepareStatement("delete from senthil where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void updateUser(UseBean bean)
{
try
{
PreparedStatement preparedStatement = conn.prepareStatement("update senthil set name=?, pass=?, phoneno=?, emailid=?"+ "where id=?");
// Parameters start with 1
preparedStatement.setString(1, bean.getName());
preparedStatement.setString(2, bean.getPassword());
preparedStatement.setString(3, bean.getPhoneo());
preparedStatement.setString(4, bean.getEmailID());
preparedStatement.setInt(5, bean.getID());
preparedStatement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public List<UseBean> getAllUsers()
{
List<UseBean> users = new ArrayList<UseBean>();
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from senthil");
while (rs.next())
{
UseBean user = new UseBean();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public UseBean getUserById(int userId)
{
UseBean user = new UseBean();
try
{
PreparedStatement preparedStatement = conn.prepareStatement("select * from senthil where id=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
{
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
}
} catch (SQLException e)
{
e.printStackTrace();
}
return user;
}
}
In the JSP the users should be available to the request scope.
public String view() {
UserDao userDao = new UserDao();
List<UseBean> users = userDao.getAllUsers();
ServletActionContext.getRequest().setAttribute("users", users);
return Action.SUCCESS;
}
public String update() {
UserDao dao = new UserDao();
UseBean bean=new UseBean();
HttpServletRequest request ServletActionContext.getRequest();
bean.setID(request.getParameter("ID");
bean.setName(request.getParameter("Name");
bean.setPassword(request.getParameter("Password");
bean.setPhoneo(request.getParameter("Phoneo");
bean.setEmailID(request.getParameter("EmailID");
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
dao.updateUser(bean);
return Action.SUCCESS;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("ID");
dao.deleteUser(userId);
return Action.SUCCESS;
}
for delete action
<s:param name='ID'><%=user.getID()%></s:param></s:url>">Delete
Inside view method you haven't initialized the dao object(i.e reference is null), add the following code :
In TestIUE.java add one more member variable :
List<UseBean> users = new ArrayList<UseBean>();
Also add Accessor method :
public List<UseBean> getUsers()
{
return users;
}
Now modify your view method as follows :
public String view()
{
dao = new UseDao();
users = dao.getAllUsers();
return ActionSupport.SUCCESS;
}
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.
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;
}
}
}