I have 2 project folders. The first one is a RESTful service and the other one is a client. What I'm trying to do is:
Getting all notes from the RESTful service (I do this as a list) of a specific user.
Then display the notes to the client in a table (html).
When I try to display the notes I get the following error:
javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
The HTML code (I'm using JSP). The error appears at the 'forEach' loop:
<table class="table table-striped">
<thead>
<tr>
<!-- Here we create the columns -->
<th> Id </th>
<th> Title </th>
<th> Text </th>
<th> Color </th>
<th> Date/Time </th>
<th> Actions </th> <!-- the table header for Actions -->
</tr>
</thead>
<!-- Table body - The data in the table -->
<tbody>
<c:forEach items="${note-all}" var="pp">
<tr>
<td><c:out value="${pp.id}" /></td>
<td><c:out value="${pp.title}" /></td>
<td><c:out value="${pp.text}" /></td>
<td><c:out value="${pp.color}" /></td>
<td><c:out value="${pp.datetime}" /></td>
<!-- The final column is the Actions, which is a list of buttons,
that we can perfom on our note Entities. -->
<td>
<div class="btn-group">
<!-- ***** Edit Button ***** -->
<a href="#Url.Action("Edit", new {pp.id})" class="btn btn-xs btn-primary">
<i class="glyphicon glyphicon-edit"></i>
Edit
</a>
<a href="#Url.Action("Delete", new {pp.id})" class="btn btn-xs btn-danger" data-post="Are you sure you want to delete this?">
<i class="glyphicon glyphicon-remove"></i>
Delete
</a>
</div>
</td>
</tr>
</c:forEach>
</tbody>
</table>
The RESTful service code:
#Path("/getAll")
#POST
#Consumes({MediaType.APPLICATION_FORM_URLENCODED/})
#Produces({MediaType.APPLICATION_XML})
public Response login(#FormParam("username") String uname
) throws ClassNotFoundException, SQLException{
System.out.println(uname);
//*First*: We get the id of the user
String sql = "SELECT user_id "
+ " FROM user_table "
+ " WHERE username = ?";
PreparedStatement ps = DbCon.getPreparedStatement(sql);
ps.setString(1, uname);
ResultSet rs = ps.executeQuery();
String id = "";
if(rs.next()){
id = rs.getString("user_id");
}
//*Second*: We get the users notes
String sql2 = "SELECT * "
+ " FROM notes_table "
+ " WHERE user_id_fk = ?";
PreparedStatement ps2 = DbCon.getPreparedStatement(sql2);
ps2.setString(1, id);
ResultSet rs2 = ps2.executeQuery();
ArrayList<Note> note_AL = new ArrayList<Note>();
if(rs2.next()){
Note note = new Note();
note.setId(rs2.getInt("note_id"));
note.setTitle(rs2.getString("title"));
note.setText(rs2.getString("text"));
note.setColor(rs2.getString("color"));
note.setDate(rs2.getString("datetime"));
note_AL.add(note);
}
//we wrap the ArrayList with Generic ENtity
GenericEntity<ArrayList<Note>> generic_list_of_notes = new GenericEntity<ArrayList<Note>>(note_AL){};
return Response.ok(generic_list_of_notes).build();
}
The client servlet code (the post method):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Form form = new Form();
form.add("username", "ali");
//We create a client object
Client client = Client.create();
//We create a resource object and pass a url to it
WebResource webR = client.resource("http://localhost:8080/MyNote/api/notes/getAll");
ClientResponse resp = webR.accept(MediaType.APPLICATION_XML/*"text/html"*/).post(ClientResponse.class, form);
//for debug
if (resp.getStatus() != 200){
System.err.println("Unable to connect to the RESTFUL web service");
}
List<Note> output = resp.getEntity(new GenericType<List<Note>>(){});
request.setAttribute("note-all", output);
RequestDispatcher rd = request.getRequestDispatcher("/Notes.jsp");
rd.forward(request, response);
}
Related
i am creating a simple crud system in Java Servlet. I am beginner of Servlet.I filled the form and clicked submit button and got the error - HTTP Status 404 - Not Found. I have attached the screen shot image below along with the code.
folder structure
Form
<form method = post action = "employee/employee.java">
<table class="table table-borederd">
<tr>
<td>Enter Employee ID:</td>
<td ><input class="form-control" type = "text" name = "txtEmpId"/></br></td>
</tr>
<tr>
<td>Enter Employee FirstName:</td>
<td ><input class="form-control" type = "text" name = "txtFName"/></td>
</tr>
<tr>
<td>Enter Employee LastName:</td>
<td ><input class="form-control" type = "text" name = "txtLName"/></td>
</tr>
<td><input type = "submit" value = "submit"/></td>
</form>
employee.java
public class employee extends HttpServlet
{
Connection con;
int row;
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException, ServletException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/empp","root","");
System.out.println("Connection Established");
}
catch(Exception e)
{
System.out.println("Sorry...........");
}
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
String empId = req.getParameter("txtEmpId");
String empFName = req.getParameter("txtFName");
String empLName = req.getParameter("txtLName");
try
{
PreparedStatement stat = con.prepareStatement("insert into record (id,fname,lname) Values(?,?,?)");
stat.setString(1,empId);
stat.setString(2,empFName);
stat.setString(3,empLName);
row = stat.executeUpdate();
}
catch(Exception e)
{
}
out.println("<html>");
out.println("<font color = 'red'>Sucessfully registered!</font>");
out.println("</body>");
out.println("<h2>");
out.println(row);
out.println("</h2>");
out.println("</body>");
}
}
I am trying to delete the data by checking multiple checkboxes, but when I choose the checkboxes from the screen and hit the delete button then the only top row gets deleted. Means no matter which row I select it deletes the only first entry of the table. Please help me.
Delete.servlet
delPage = request.getParameter("delPage");
patientId = request.getParameter("pid");
if(delPage.equals("true")) {
int p = Integer.parseInt(patientId);
patientDao = new PatientDAO();
boolean b = patientDao.isPatientDeleted(p);
if (b) {
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}else
System.out.println("Patient deleting failed ... ! ");
}
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
Masterpage.jsp
<script type="text/javascript">
function addNewPatient(){
debugger;
var addNewPat = "true";
document.form.method = "POST";
document.form.action = "addPatient?newPage="+addNewPat;
document.form.submit();
}
function deletePatient(){
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}">
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
<i class="trash ulternate icon"></i>
Delete
</div>
DeletePatientServlet.java
public class DeletePatientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private PatientBean patient = null;
private PatientDAO patientDao = null;
String delPage = null ;
String patientId = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
}
Okay so there are a bunch of mistakes in your code. I'll start with the jsp...
You are trying to pass parameters via the servlet url with a POST request
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
You cannot pass data in the url with post requests. You need to change your servlet to a GET if you want to do this.
Also, in this line:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
you are passing a value to your deletePatient method. But your deletePatient method does not have an option to pass a value:
function deletePatient(){ // no value being passed here?
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
You can also just do:
${user.patientId}
instead of:
<c:out value="${user.patientId}"></c:out>
Another problem with your code is this, you cannot have multiple elements in your HTML with the same id. This is illegal HTML, and it's the reason why you are getting the same id each time:
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}"> //no this is bad.
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
Your delete button is not even inside your loop, so it will not work:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)"> //this will pass the same id each time
<i class="trash ulternate icon"></i>
Delete
</div>
Try something like this instead (for delete only):
<script type="text/javascript">
function deletePatient(e){
var patientid = e.getAttribute("data-patientid");
deletePatientForm(patientid);
}
function deletePatientForm(pid) {
var form = document.createElement("form");
var input = document.createElement("input");
form.method = "POST";
form.action = "deletePatient";
input.value=pid;
input.name="pid";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
<th>phone</th>
<th></th>
<tr>
<tr>
<td>${user.patientId}</td>
<td>${user.patientName}</td>
<td>${user.patientAddress}</td>
<td>${user.patientPhone}</td>
<td>
<div class="ui small button" onClick="deletePatient(this)" data-patientid="${user.patientId}"><i class="trash ulternate icon"></i> Delete</div>
</td>
<tr>
</c:forEach>
Then in the post of your servlet:
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
If you have any problems or questions let me know.
I am quite new to hibernate frameworks and I am working on a Hibernate framework project in the netbeans IDE. I have a javadb that is connected to the project and I need to get the task list for each employee and display it as a bullet list in a <td> against each employee name. The following is the table displaying the employees' names and roles that are being fetched using the getEmployeeDetails method in the EmployeeHelper class.
Issue - The task list is always empty though I call the resultTaskList parameter that is passed from the Controller. - I know that I have to do an if conditional check for task within the nested forloop that will list the tasks to group them based on the employee names. But am not sure how to do an if within a jsp page.
Any suggestions on how to display the task list of each employee within the same table will be highly appreciated.
In this table, I intend to have the tasks pertaining to each employee as a bulletlist within each corresponding <td>.
Employee.jsp
...
<div class="content">
<!--Display table of roles with an edit button against each role-->
<form method="get" action="<%= request.getContextPath() %>/RoleController">
<br>
<table border ="2">
<thead class="thead-inverse">
<tr>
<th></th>
<th>Employee Name</th>
<th>Role</th>
<th>Tasks</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<c:forEach items="${result}" var="res">
<tr>
<th scope="row">
</th>
<td>
<c:out value="${res[0]}"></c:out>
</td>
<td>
<c:out value="${res[1]}"></c:out>
</td>
<td>
<c:out value="${resultTaskList[1]}"></c:out>
</td>
<td>
<input type="button" class="btn btn-info" value="Edit Role">
</td>
</tr>
</c:forEach>
</table>
</form>
</div>
...
EmployeeController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
EmployeeHelper helper = new EmployeeHelper();
List<Employee> resultTaskList = helper.getEmployeeTasks();
request.setAttribute("resultTaskList", resultTaskList);
List<Employee> result = helper.getEmployeeDetails();
request.setAttribute("result", result);
request.getRequestDispatcher("Employee.jsp").forward(request, response);
}
EmployeeHelper.java
public class EmployeeHelper {
Session session = null;
public EmployeeHelper(){
this.session = HibernateUtil.getSessionFactory().openSession();
}
public List getEmployeeDetails(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeList = null;
try{
Query query = session.createQuery("select e.name, r.title from Employee as e, Role as r where e.employeeid=r.employeeid");
employeeList = (List<Employee>)query.list();
tx.commit();
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeList;
}
public List getEmployeeTasks(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeTaskList = null;
try{
Query query = session.createQuery("select e.name, t.description from Employee as e, Role as r, Task as t, EmployeeTask as et where e.employeeid=r.employeeid and t.taskid=et.taskid and e.employeeid=et.employeeid");
employeeTaskList = (List<Employee>)query.list();
tx.commit();
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeTaskList;
}
}
SQL Query executed within the getEmployeeTasks() method
instead of List employeeTaskList use List and iterate loop and set values in employee list try following code .
public List getEmployeeTasks(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeTaskList = null;
try{
session.beginTransaction();
Query query = session.createQuery("select e.name, t.description from Employee as e, Role as r, Task as t, EmployeeTask as et where e.employeeid=r.employeeid and t.taskid=et.taskid and e.employeeid=et.employeeid");
List<Object[]> result = (List<Object[]>) query.list();
if (null != result && result.size() != 0) {
for (Object[] obj : result) {
//Set values over here
employeeTaskList.set.....
}
tx.commit();
}
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeTaskList;
}
These two lists are non-related as suggested by JB Nizet. Still You can do something like this.
<c:forEach items="${result}" var="res">
<tr>
<th scope="row">
</th>
<td>
<c:out value="${res[0]}"></c:out>
</td>
<td>
<c:out value="${res[1]}"></c:out>
</td>
<td>
<c:forEach items="${resultTaskList}" var="resultTaskList">
<c:if test = "${res[0] == resultTaskList[0]}">
<c:out value="${resultTaskList[1]}"></c:out>
</c:if>
</c:forEach>
</td>
<td>
<input type="button" class="btn btn-info" value="Edit Role">
</td>
</tr>
</c:forEach>
Hope this helps.
In table 10 rows are there..selected data has to delete (using check box) and display all the content in table....Here newsid in JSP file is auto incremented value....
This is DeleteSuccess.java File
public class DeleteSuccess extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase","root","root");
PreparedStatement ps = con.prepareStatement("delete from ROOT.NEWSTABLE where newsid='" + (* here what i have 2 write *) +"'");
int i= ps.executeUpdate();
PreparedStatement pss = con.prepareStatement("select NEWSID,NEWS from ROOT.NEWSTABLE");
ResultSet rs =pss.executeQuery();
ArrayList<News> listnewsobj = new ArrayList<News>();
while(rs.next())
{
News obj=new News();
obj.setNewsId(rs.getInt(1));
obj.setNews(rs.getString(2));
listnewsobj.add(obj);
}
session.setAttribute("listnewskey",listnewsobj);
System.out.println(listnewsobj);
if (i > 0)
{
System.out.println("Venkatesh");
//out.print("You are successfully registered...");
//RequestDispatcher rs = request.getRequestDispatcher("Login.html");
// RequestDispatcher rd = request.getRequestDispatcher("JSP/AddNews.jsp");
// rd.include(request, response);
response.sendRedirect("JSP/AddNews.jsp");
}
} catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
This is JSP file
<form method="post" action="../newsdelete">
<fieldset class="rt">
<legend> <b> Manage News </b> </legend>
<table>
<tr>
<th>News Id</th>
<th>News Name</th>
<th>Action</th>
</tr>
<c:forEach items="${listnewskey}" var="listnews">
<tr>
<td class="first_col">${listnews.newsId}</td>
<td>${listnews.news}</td>
<td class="third_col">
<input id="" type="checkbox" name="check" value="action"><label for="radio1"><span><span></span></span></label>
</td>
</tr>
</c:forEach>
</table>
<div> <br><input type="submit" value="Delete" name="delete"></div>
</fieldset>
</form>
This is web.xml
<servlet>
<servlet-name>Delete</servlet-name>
<servlet-class>com.venkatesh.DeleteSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Delete</servlet-name>
<url-pattern>/newsdelete</url-pattern>
</servlet-mapping>
Can anyone tell me how to delete the row which is checked and automatically display the information from the table in same JSP file which i have written the table in Loop...
Im having some little troubles with the UPDATE servlet.
Im trying to update my db but its just not happening. I'm new to this chapter of Java EE.
**NB: I'm just having trouble with the UpdateServlet because i dont know how to get the modified datas from the JSP in order to send it to the DAO and then to update the DB. The rest is OK
The purpose : When the user hits the "Update" button (screenshot below)...
... the JSP forwards the request to the "update user" page (below) where he'll be able to modify the first and last name attached to the email (which is the primaary key)(screenshot below)...
My question is : how do i implement the UpdateUserServlet (see code below) code that gets the User object from the session and updates the database with the new first and last name.
The JSP that displays the User List
<body>
<h1>Users List</h1>
<table cellpadding="5" border=1>
<tr valign="bottom">
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach var="user" items="${users}">
<tr valign="top">
<td><p>${user.firstName}</td>
<td><p>${user.lastName}</td>
<td><p>${user.emailAddress}</td>
<td>Update</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</body>
After hitting the "Update button" this JSP below takes over.
....
<body>
<h1>Update User</h1>
<form action="updateUser" method="post">
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName"
value="${user.firstName}">
</td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value="${user.lastName}">
</td>
</tr>
<tr>
<td align="right">Email address:</td>
<td>${user.emailAddress}</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Submit"></td>
</tr>
</table>
</form>
</body> ....
The Update servlet. Ineed help with this one.
package user;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import business.User;
import data.UserDB;
public class UpdateUserServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
User user = new User();
HttpSession session = request.getSession();
session.setAttribute("user", user);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmailAddress(emailAddress);
UserDB.update(user);
// TODO: add code that gets the User object from the session and updates the database
String url = "/displayUsers";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
The DAO
package data;
import java.sql.*;
import java.util.ArrayList;
import business.User;
public class UserDB
{
public static int update(User user) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE User SET " + "FirstName = ?, " + "LastName = ? "
+ "WHERE EmailAddress = ?";
try {
ps = connection.prepareStatement(query);
ps.setString(1, user.getFirstName());
ps.setString(2, user.getLastName());
ps.setString(3, user.getEmailAddress());
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
Try adding logs to update(User user) method. See whether control is coming to this place if atall.
I found the root cause in the second JSP see the code below.
<tr>
<td align="right">Email address:</td>
<td>${user.emailAddress}</td>
</tr>
The servlet's getParameter("emailAddress") method was actually getting a null value since there is no parameter name in the code above..
So, it should have been done like this:
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailaddress"
value="${user.emailaddress}">
</td>
</tr>
Note that the -input type="text"- is not necessary since the email address doesnt have to be modified like the name and firsname. So i should find a way to show the email address in something else than a input text box. But it works now