Hi I'm trying to fetch a object from a class and displaying it and I'm getting error "value map is not a member of models.TimeSheetDataStore"
Here is my model class files
TimeSheetDataStore.java
package models;
public class TimeSheetDataStore {
String ID;
String EmployeeID;
String RoleID;
String Task;
String TimeSheetDate;
String CreateDate;
String UpdateDate;
String TaskHour;
String IsBilled;
String ClientID;
String ProjectID;
String atHome;
String atClientSite;
}
TimeSheet.java
package models;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import models.TimeSheetDataStore;
public class Timesheet {
public static List<TimeSheetDataStore> PopulateProject() {
List<TimeSheetDataStore> TimeSheetList = new ArrayList<TimeSheetDataStore>();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433","SUMEET","sumeet");
Statement sta = conn.createStatement();
String Sql = "select * from Project";
ResultSet rs = sta.executeQuery(Sql);
while (rs.next()) {
TimeSheetDataStore TSDS= new TimeSheetDataStore();
TSDS.ID=rs.getString("ID");
TSDS.EmployeeID=rs.getString("EmployeeID");
TSDS.RoleID=rs.getString("RoleID");
TSDS.Task=rs.getString("Task");
TSDS.TimeSheetDate=rs.getString("TimeSheetDate");
TSDS.CreateDate=rs.getString("CreateDate");
TSDS.UpdateDate=rs.getString("UpdateDate");
TSDS.TaskHour=rs.getString("TaskHour");
TSDS.IsBilled=rs.getString("IsBilled");
TSDS.ProjectID=rs.getString("ProjectID");
TSDS.ClientID=rs.getString("ClientID");
TSDS.atHome=rs.getString("atHome");
TSDS.atClientSite=rs.getString("atClientSite");
TimeSheetList.add(TSDS);
}
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException |SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return(TimeSheetList);
}
}
Controller file
Application.java
public static Result myAction(String ClientFilter,String ConsultantFilter) {
DynamicForm requestData = Form.form().bindFromRequest();
if (requestData.get("Submit")!=null) {
return ok(index.render(Client.PopulateClient(),Consultant.PopulateConsultant(),Project.PopulateProject(ClientFilter)));
} else if (requestData.get("Generate Timesheet")!=null) {
//return ok(list.render(Client.PopulateClient(),Consultant.PopulateConsultant(),Project.PopulateProject()));
return ok(DisplayTimeSheet.render(Timesheet.PopulateProject()));
} else {
return badRequest("This action is not allowed");
}
}
View file DisplayTimeSheet.scala.html
#(currentPage:List[TimeSheetDataStore])
<html>
<head></head>
<body>
<form>
<table>
<thead>
<tr>
<td>ID</td>
<td>EmployeeID</td>
<td>RoleID</td>
<td>Task</td>
<td>TimeSheetDate</td>
<td>CreateDate</td>
<td>UpdateDate</td>
<td>TaskHour</td>
<td>IsBilled</td>
<td>ProjectID</td>
<td>ClientID</td>
<td>atHome</td>
<td>atClientSite</td>
</tr>
</thead>
<tbody>
#for(i <- currentPage.indices) {
#for(element <- currentPage.get(i)) {
<tr>
<td>#element.ID</td>
<td>#element.EmployeeID</td>
<td>#element.RoleID</td>
<td>#element.Task</td>
<td>#element.TimeSheetDate</td>
<td>#element.CreateDate</td>
<td>#element.UpdateDate</td>
<td>#element.TaskHour</td>
<td>#element.IsBilled</td>
<td>#element.ProjectID</td>
<td>#element.ClientID</td>
<td>#element.atHome</td>
<td>#element.atClientSite</td>
</tr>
}
}
</tbody>
</table>
</form>
</body>
</html>
Can some one tell me what I'm doing wrong?
try instead of
#for(i <- currentPage.indices) {
#for(element <- currentPage.get(i)) {
<tr>
<td>#element.ID</td>
<td>#element.EmployeeID</td>
<td>#element.RoleID</td>
.
.
.
</tr>
}
}
use only one for loop because you have list of currentPage: List[TimeSheetDataStore] so when you do #for(element <- currentPage) it will return you one object assigned to the element variable so now you have TimeSheetDataStore object in element variable so you can directly access it's fields
Do it like this:
<tbody>
#for(element <- currentPage) {
<tr>
<td>#element.ID</td>
<td>#element.EmployeeID</td>
<td>#element.RoleID</td>
<td>#element.Task</td>
<td>#element.TimeSheetDate</td>
<td>#element.CreateDate</td>
<td>#element.UpdateDate</td>
<td>#element.TaskHour</td>
<td>#element.IsBilled</td>
<td>#element.ProjectID</td>
<td>#element.ClientID</td>
<td>#element.atHome</td>
<td>#element.atClientSite</td>
</tr>
}
</tbody>
Related
So here is my issue. I am working on a school project and I am basically hitting a wall. I cannot get my RegistrationServer to work at all. I can get it to run, and correctly display the Registration.jsp that it is built behind, but none of the information is entered into the database at all. In fact, I cannot even tell if that is where exactly I am failing. Here is the code for the Registration function:
Registration.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style>
div.container {
//width: 100%;
// border: 1px solid gray;
// padding:5px;
}
table, th, td {
//border: 1px solid black;
}
.textright{float:right;padding:10px}
</style>
<title>Registration</title>
<script>
function validate()
{
var firstname = document.form.firstname.value;
var lastname = document.form.lastname.value;
var username = document.form.username.value;
var password = document.form.password.value;
var address = document.form.address.value;
var contact = document.form.contact.value;
if (firstname==null || firstname=="")
{
alert("First Name can't be blank");
return false;
}
else if (lastname==null || lastname=="")
{
alert("Last Name can't be blank");
return false;
}
else if (username==null || username=="")
{
alert("Username can't be blank");
return false;
}
else if (password==null || password=="")
{
alert("Password can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
else if (address==null || address=="")
{
alert("Address can't be blank");
return false;
}
else if (contact==null || contact=="")
{
alert("Contact can't be blank");
return false;
}
}
</script>
</head>
<body bgcolor="#D3D3D3">
<form name="form" action="RegistrationServlet" method="post"
onsubmit="return
validate()">
<td style="float:left"><image
src="file:///G:/College/Winter%202018/CSC%20363/Computer%20logo.png"
width="100px" height="100px"></image></td>
<p style="float:right"><b> ${members[3]} <br> CSC 363<br>Final Project</b>
</p>
<td style="clear:float"></td>
<p style="align-text"left">Team</p>
<p style="float:left">${members[0]} <br> ${members[1]} <br>
${members[2]} </p>
<td style="close:float"></td>
<table style="float:right">
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Contact</td>
<td><input type="text" name="contact" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></input>
</tr>
</table>
</form>
</body>
</html>
RegistrationServlet
package com.mvc.RegistrationServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mvc.Bean.RegistrationBean;
import com.mvc.Dao.RegistrationDao;
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegistrationServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String[] members = new String[4];
members[0] = "Jamie W.";
members[1] = "Evan D.";
members[2] = "Tim D.";
members[3] = "Hardware Plus";
request.setAttribute("members", members);
request.getRequestDispatcher("/Registration.jsp").forward(request,
response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String userName = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
RegistrationBean registrationBean = new RegistrationBean();
registrationBean.setFirstName(firstName);
registrationBean.setLastName(lastName);
registrationBean.setUserName(userName);
registrationBean.setPassword(password);
registrationBean.setAddress(address);
registrationBean.setContact(contact);
RegistrationDao registrationDao = new RegistrationDao();
String userRegistered = registrationDao.registrationUser(registrationBean);
if(userRegistered.equals("SUCCESS"))
{
request.getRequestDispatcher("/ProductSalesPage.jsp").forward(request,
response);
}
else
{
request.setAttribute("errMessage", userRegistered);
request.getRequestDispatcher("/RegistrationServlet.jsp").forward(request,
response);
}
}
}
RegistrationDao
package com.mvc.Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mvc.Bean.RegistrationBean;
import com.mvc.RegistrationDB.RegistrationDB;
public class RegistrationDao {
public String registrationUser(RegistrationBean registrationBean)
{
String firstName = registrationBean.getFirstName();
String lastName = registrationBean.getLastName();
String userName = registrationBean.getUserName();
String password = registrationBean.getPassword();
String address = registrationBean.getAddress();
String contact = registrationBean.getContact();
Connection con = null;
PreparedStatement preparedStatement = null;
try
{
con = RegistrationDB.createConnection();
String query = "insert into
users(SlNo,firstName,lastName,userName,password,address,contact) values
(NULL,?,?,?,?,?,?)";
preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, firstName);
preparedStatement.setString(2, lastName);
preparedStatement.setString(3, userName);
preparedStatement.setString(4, password);
preparedStatement.setString(5, address);
preparedStatement.setString(6, contact);
int i= preparedStatement.executeUpdate();
if (i!=0)
return "SUCCESS";
}
catch(SQLException e)
{
e.printStackTrace();
}
return "Oops.. Something went wrong there..!";
}
}
RegistrationDB
package com.mvc.RegistrationDB;
import java.sql.Connection;
import java.sql.DriverManager;
public class RegistrationDB {
public static Connection createConnection()
{
Connection con = null;
String url = "jdbc:mysql#localhost:3306/project/users";
String username = "root";
String password = "password";
try
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
con = DriverManager.getConnection(url, username, password);
System.out.println("Printing connection object "+con);
}
catch (Exception e)
{
e.printStackTrace();
}
return con;
}
}
RegistrationBean
package com.mvc.Bean;
public class RegistrationBean
{
private String firstName;
private String lastName;
private String userName;
private String password;
private String address;
private String contact;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getContact() {
return contact;
}
}
Anything anyone can offer as far as why this servlet will not run would be gladly appreciated. The error messages that Eclipse throws are so generic, but the issue seems to be basically writing the registration information to the database. I can load the registration page and enter the information, and the if statements work because the page wont forward with blank text entry boxes or a password less than 6 characters. The problem is when you submit, and it throws HTTP Status 404 and says the requested resource is unavailable.
It might be because you're retrieving the incorrect parameter names in your RegistrationServlet.
For example: you are retrieving with request.getParameter("firstname") but your input have name="firstName". Note the upper case 'N' (java EE servers are case sensitive for URIs).
Try this in your RegistrationServlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName"); // upper case N
String lastName = request.getParameter("lastName"); // upper case N
String userName = request.getParameter("userName"); // upper case N
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
//...
I'm relatively new to Java. Tried my first web application with server Tomcat, which went rather well. However, with another server Glassfish, problems arouse. After application deployment jsp doesn't connect to servlet, therefore error 404 appears. I added project structure and several classes. Any help appreciated.
empBean:
package app.bean;
import app.entity.Emp;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
#Stateless
public class EmpBean {
#PersistenceContext(unitName = "DEVMODE")
private EntityManager em;
public Emp add(Emp emp) {
return em.merge(emp);
}
public Emp get(Integer empno) {
return em.find(Emp.class, empno);
}
public void update(Emp emp) {
add(emp);
}
public void delete(long empno){
em.remove(get((int) empno));
}
public List<Emp> getAll(){
TypedQuery<Emp> namedQuery = em.createNamedQuery("Emp.getAll", Emp.class);
return namedQuery.getResultList();
}
}
Emp:
package app.entity;
import javax.persistence.*;
import java.sql.Date;
#Entity(name="emp")
#NamedQuery(name = "Emp.getAll", query = "SELECT e from emp e")
public class Emp {
#Id
#Column(name="empno")
private Integer empno ;
#Column(name="ename")
private String ename;
#Column(name="job")
private String job;
#Column(name="mgr")
private Integer mgr;
#Column(name="hiredate")
private Date hiredate;
#Column(name="sal")
private Integer sal;
#Column(name="comm")
private Integer comm;
#Column(name="deptno")
private Integer deptno;
public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Integer sal, Integer comm, Integer deptno, String id) {
this.empno = empno;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
}
public Emp() {
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public Integer getSal() {
return sal;
}
public void setSal(Integer sal) {
this.sal = sal;
}
public Integer getComm() {
return comm;
}
public void setComm(Integer comm) {
this.comm = comm;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
}
Select1Servlet:
package app.servlets;
import app.bean.DeptBean;
import app.bean.EmpBean;
import app.bean.SalgradeBean;
import app.entity.Dept;
import app.entity.Emp;
import app.entity.Salgrade;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
#WebServlet("/search")
public class Select1Servlet extends HttpServlet {
#EJB
private EmpBean empBean;
private DeptBean deptBean;
private SalgradeBean salgradeBean;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
req.setCharacterEncoding("UTF-8");
req.getRequestDispatcher("/searchview.jsp").forward(req, resp);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/users";
String userName = "root";
String password = "7777";
Statement st;
try {
// Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(url , userName, password);
System.out.println("Connected!");
String numb = request.getParameter("numb");
ArrayList al = null;
ArrayList pid_list = new ArrayList();
// String query = "SELECT emp.ename, emp.job, emp.sal, dept.dname, salgrade.grade FROM dept,emp,salgrade WHERE (emp.empno = '" + numb + "' ) AND (emp.deptno = dept.deptno) and (emp.sal BETWEEN losal and hisal) ";
// System.out.println("query " + query);
st = conn.createStatement();
// ResultSet rs = st.executeQuery(query);
Emp emp = empBean.get(Integer.valueOf(numb));
String ename= emp.getEname();
String job = emp.getJob();
Integer sal = emp.getSal();
Integer deptnoEmp= emp.getDeptno();
Dept dept = deptBean.get(Integer.valueOf(deptnoEmp));
String dname = dept.getDname();
Salgrade salgrade = salgradeBean.get(sal);
Integer grade = salgrade.getGrade();
// while (rs.next()) {
al = new ArrayList();
// out.println(rs.getString(1));
// out.println(rs.getString(2));
// out.println(rs.getString(3));
// out.println(rs.getString(4));
al.add(ename);
al.add(job);
al.add(sal);
al.add(dname);
al.add(grade);
System.out.println("al :: " + al);
pid_list.add(al);
// }
request.setAttribute("piList", pid_list);
RequestDispatcher view = request.getRequestDispatcher("/searchview.jsp");
view.forward(request, response);
conn.close();
System.out.println("Disconnected!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
select1.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Enter the number </title>
<link rel="stylesheet" href="design/w3.css">
</head>
<body>
<br/><br/>
<form method="post" name="frm" action="search">
<table border="0" width="375" align="center" class = "w3-pink w3-text-white" >
<tr><td colspan=2 style="font-size:12pt;" align="center">
<h3>Search User</h3></td></tr>
<br/>
<tr><td ><b>User Number</b></td>
<td>: <input type="number" name="numb" id="numb">
</td></tr>
<tr><td colspan=2 align="center">
<br/>
<input type="submit" name="submit" value="Search" onclick="form.action='/search';"></td></tr>
</table>
</form>
</body>
</html>
searchview.jsp:
<%# page import="java.util.*" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%--<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>--%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title> List of emp </title>
<link rel="stylesheet" href="design/w3.css">
</head>
<body>
<form method="get" name="frm" action="searchview">
<table width="700px"
class = "w3-text-pink">
<tr>
<td colspan=5 align="center"
class = "w3-black w3-text-pink">
<b>User Record</b></td>
</tr>
<tr class = "w3-black ">
<td><b>User Name</b></td>
<td><b>Job</b></td>
<td><b>Sal</b></td>
<td><b>Dname</b></td>
<td><b>Grade</b></td>
</tr>
<%
int count = 0;
String color = "#ffffff";
if (request.getAttribute("piList") != null) {
ArrayList al = (ArrayList) request.getAttribute("piList");
System.out.println(al);
Iterator itr = al.iterator();
while (itr.hasNext()) {
if ((count % 2) == 0) {
color = "#ffffff";
}
count++;
ArrayList pList = (ArrayList) itr.next();
%>
<tr style="background-color:<%=color%>;">
<td><%=pList.get(0)%></td>
<td><%=pList.get(1)%></td>
<td><%=pList.get(2)%></td>
<td><%=pList.get(3)%></td>
<td><%=pList.get(4)%></td>
</tr>
<%
}
}
if (count == 0) {
%>
<tr>
<td colspan=5 align="center"
style="background-color:#ffffff"><b>No Record Found..</b></td>
</tr>
<% }
%>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Select1</servlet-name>
<servlet-class>app.servlets.Select1Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Select1</servlet-name>
<url-pattern>/search</url-pattern>
</servlet-mapping>
so I am working in a Spring MVC project where I have this class with a few Date fields and I am creating a CRUD for it. Problem is, I read an instance of the class from the database and then send it to the view for editing, and although I am not manipulating any of the Date fields, only the strings, when I collect the object using a post form, the Date fields come as null even though they came from the database with a value and I sent them to the view with that value.
The class:
package com.sophos.mat.beans;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Length;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="IN_PROYECTO")
#GeneratedValue(strategy=GenerationType.AUTO, generator="SECUENCIA_IN_PROYECTO")
#SequenceGenerator(name="SECUENCIA_IN_PROYECTO", sequenceName="SECUENCIA_IN_PROYECTO", allocationSize=1, initialValue= 1)
private long id;
#Column(name="VC_NOMBRE")
#Length(max = 50, message = "El campo no puede exceder los 50 caracteres")
private String nombre;
#Column(name="VC_DESCRIPCION")
#Length(max = 200, message = "El campo no puede exceder los 200 caracteres")
private String descripcion;
#Column(name="VC_CODIGO_SOPHOS")
#Length(max = 20, message = "El campo no puede exceder los 20 caracteres")
private String codigoSophos;
#Column(name="DT_FECHACREACION")
private Date fechaCreacion;
#Column(name="VC_USUARIOACTUALIZACION")
private String usuarioActualizacion;
#Column(name="DT_FECHAACTUALIZACION")
private Date fechaActualizacion;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getCodigoSophos() {
return codigoSophos;
}
public void setCodigoSophos(String codigoSophos) {
this.codigoSophos = codigoSophos;
}
public Date getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public String getUsuarioActualizacion() {
return usuarioActualizacion;
}
public void setUsuarioActualizacion(String usuarioActualizacion) {
this.usuarioActualizacion = usuarioActualizacion;
}
public Date getFechaActualizacion() {
return fechaActualizacion;
}
public void setFechaActualizacion(Date fechaActualizacion) {
this.fechaActualizacion = fechaActualizacion;
}
}
The controller:
package com.sophos.mat.controller;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.sophos.mat.beans.Proyecto;
import com.sophos.mat.services.IProyectoService;
#Controller
public class ProyectoController {
#Autowired
private IProyectoService proyectoService;
#RequestMapping(value = "/editarproyecto/{id}", method = RequestMethod.GET)
public String editarProyectoGet(ModelMap model, #PathVariable long id){
try {
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
model.put("proyectoData", proyectoData);
return "editarproyecto";
} catch (Exception e) {
e.printStackTrace();
return "redirect:/proyectos";
}
}
#RequestMapping(value="/editarproyecto/{id}", method = RequestMethod.POST)
public String editarProyectoPost(ModelMap model, #PathVariable long id, #ModelAttribute("proyectoData")#Valid Proyecto proyectoData, BindingResult result){
if(result.hasErrors()){
return "editarproyecto";
}
try{
proyectoData.setFechaActualizacion(new Date());
proyectoService.actualizarProyecto(proyectoData);
return "redirect:/proyectos";
}catch(Exception e){
e.printStackTrace();
return "redirect:/proyectos";
}
}
public IProyectoService getProyectoService() {
return proyectoService;
}
public void setProyectoService(IProyectoService proyectoService) {
this.proyectoService = proyectoService;
}
}
And the view: editarproyecto.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib uri= "http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>>Nuevo Proyecto</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h1>Nuevo Proyecto</h1>
<form:form method="post" modelAttribute="proyectoData">
<table >
<tr>
<td align="right">
Nombre proyecto:
</td>
<td>
<form:input path="nombre"/>
</td>
<td>
<form:errors path="nombre" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Descripción
</td>
<td>
<form:input path="descripcion"/>
</td>
<td>
<form:errors path="descripcion" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Cód. Sophos
</td>
<td>
<form:input path="codigoSophos"/>
</td>
<td>
<form:errors path="codigoSophos" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Usuario que actualiza
</td>
<td>
<form:input path="usuarioActualizacion"/>
</td>
<td>
<form:errors path="usuarioActualizacion" cssClass="error"/>
</td>
</tr>
</table>
<br>
<input type="submit" value="Guardar">
</form:form>
Proyectos
</body>
</html>
When processing POST, I get an exception from hibernate telling me that I'm trying to update to NULL the column 'DT_FECHACREACION' corresponding to the class field 'fechaCreacion'. As a temporary fix, I had to add in the POST method a query to the database to reset 'fechaCreacion' back to its previous value which I don't want to change and then update the entity with the rest of the captured values. That works but is ugly af and adds extra and unwanted overhead. My database is Oracle 11g. Thanks in advance folks!
PD: Very newbie spring developer, am in my internship and trying my best to get a full contract when the internship is over :D so any help will be much appreciated.
When you call the service you have to control which fields you return to the view.
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
You can omit fields your DAO is returning with #JsonIgnore annotation.
....
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
...
#JsonIgnore
public Date getFechaCreacion() {
return fechaCreacion;
}
....
}
I made wrong HQL trying to access column from another table. Sorry.
This question is solved.
I have ArrayList of type Object. Fetched from session.
It exists. I check. But I cant print it it from jsp or java. even I create methods.
// with type List I cant even fetch information from session. A change it to ArrayList.
My goal is to print result. I select some sql columns and I just wanna output them. Of course it would be object.
I have no error and that is problem. Only existing arraylist object of my type prod.
ArrayList <prod> goodlist = (ArrayList <prod>) session.getAttribute("goodlist_s");
for (prod glst : goodlist) {
%>
<tr>
<td><%//=out.println(u.getname())%></td>
<td><%=glst.getcatid()%></td>}
I try convert it to String ArrayList .
ArrayList<String> jlistTitles = new ArrayList<String>((ArrayList<String>) session.getAttribute("goodlist_s")); //converted fine
for(int i = 0; i < goodlist.size(); i++) {
System.out.println(goodlist.get(i).getprice());
//print object type
}
**Shows nothing**
This is my function
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
Query query = session.createQuery("from prod where catname=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}
BTW i would sent all code
index.jsp
<%#page import="java.util.List"%>
<%#page import="service.IndexService"%>
<%#page import="java.util.Date"%>
<%#page import="goods.prod"%>
<%#page import="goods.cat"%>
<%#page import ="java.util.ArrayList"%>
<%#page import ="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charprods=UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>Result Page</title>
</head>
</head>
<body>
<form action="IndexServlet" method="POST">
<table align="center" cellpadding = "10">
<tr>
<td>Category</td>
<td><input type="text" name="catname" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Category id</td>
<td><input type="number" name="catid" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Naimenovanie</td>
<td><input type="text" name="name" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Price low</td>
<td><input type="number" name="pricel" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Price high</td>
<td><input type="number" name="priceh" maxlength="100" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</td>
</tr>
</table>
prodsAttribute
<%
prod prod = (prod) session.getAttribute("prod");
%>
<%
ArrayList <prod> goodlist = (ArrayList <prod>) session.getAttribute("goodlist_s");
%>
<b>You have<% if (null == prod) out.println("No text entered.");%></b>
<b>You have<% if (null == goodlist) out.println("goodlist does NOT exists.");%></b>
<b>You have<% if (null != goodlist) {
ArrayList<String> jlistTitles = new ArrayList<String>((ArrayList<String>) session.getAttribute("goodlist_s"));
if (null == jlistTitles) out.println("convertedStringlist does NOT exists.");
if (null != jlistTitles) out.println("convertedStringlist exists. How can I use it?");
for(int i = 0; i < goodlist.size(); i++) {
System.out.println(goodlist.get(i).getprice());
//print object type
}
out.println("goodlist exists. How can I use it?");}%></b>
<br>
<b><%if (null!=prod) out.println(prod.getid()+ " "+prod.getname()+ " "+prod.getprice());%></b>
<br/>
<%
if (null!=goodlist) {
for (prod glst : goodlist) {
%>
<tr>
<td><%//=out.println(u.getname())%></td>
<td><%=glst.getcatid()%></td>
<td><%=glst.getprice()%></td>
<td><%="hh"%></td>
</tr>
<%}}%>
</form>
</body>
</html>
Indexservlet.java
package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import goods.prod;
import service.IndexService;
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = -8670416133536111566L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charprods=UTF-8");
//Long id = Long.parseLong(request.getParameter("id"));
String name = request.getParameter("name");
String catname = request.getParameter("catname");
Integer pricel = Integer.parseInt(request.getParameter("pricel"));
Integer priceh = Integer.parseInt(request.getParameter("priceh"));
prod dot = IndexService.getprodbyparam(catname,name,pricel,priceh);
List<prod> goodlist = IndexService.getListOfProds(catname,name,pricel,priceh);
request.getSession().setAttribute("goodlist_s", goodlist);
request.getSession().setAttribute("prod", dot);
response.sendRedirect("index.jsp");
}
}
Indexservice with functions
package service;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import HibernateUtil.HibernateUtil;
import goods.prod;
public class IndexService {
public static prod getprodbyparam(String catname,String name,Integer pricel, Integer priceh) {
Session session = HibernateUtil.openSession();
Transaction tx = null;
prod prod = null;
try {
tx = session.getTransaction();
tx.begin();
//Query query = session.createQuery("select prod.id from prod as prod inner join cat.id as id where name=?");
Query query = session.createQuery("from prod where name=? and price between ? and ?");
query.setString(0, name);
query.setInteger(1, pricel);
query.setInteger(2, priceh);
//query.prodsInteger(3, catid);
prod = (prod)query.uniqueResult();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return prod;
}
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
Query query = session.createQuery("from prod where catname=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}
}
prod with getters
package goods;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name = "prod")
public class prod implements Serializable {
#Id #GeneratedValue
#Column(name = "id")
private Long id;
private Integer catid;
private String name;
private Integer price;
public prod() {
}
public prod(Long id, Integer catid, String name, Integer price) {
this.id = id;
this.catid = catid;
this.name = name ;
this.price = price;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
public Integer getcatid() {
return catid;
}
public void setcatid(Integer catid) {
this.catid = catid;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public Integer getprice() {
return price;
}
public void setprice(Integer price) {
this.price = price;
}
}
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">
<display-name>Improve</display-name>
<servlet>
<servlet-name>IndexServlet</servlet-name>
<servlet-class>servlet.IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IndexServlet</servlet-name>
<url-pattern>/IndexServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Can you please try the below code and see if it works
ArrayList<String> goodlist_s= (ArrayList<String>)session.getAttribute("goodlist_s");
<%
for(int i = 0; i < goodlist_s.size(); i++)
{
String myString = (String) goodlist_s.get(i);
}
%>
Hello i'm new to hava and i'm having a problem viewing my records from an arraylist in JSP page,
whenever i load the page i get:
[content.animalBean#1e8614a, content.animalBean#14b52aa, content.animalBean#2026f3, content.animalBean#dd20b6, content.animalBean#18eb00c] 1 which is not the database records
here is my code:
selectAnimalServlet:
package content;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class selectAnimalServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
List<animalBean> beans = DAO.selectListAnimal();
request.setAttribute("beans", beans);
request.getRequestDispatcher("checkAnimal.jsp").forward(request, response);
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
AnimalBean:
package content;
public class animalBean {
private String animalName;
private String animalDob;
private String animalGender;
private String animalSource;
private String animalBreed;
private String animalRemark;
public String getAnimalName() {return animalName;}
public String getAnimalDob() {return animalDob;}
public String getAnimalGender() {return animalGender;}
public String getAnimalSource() {return animalSource;}
public String getAnimalBreed() {return animalBreed;}
public String getAnimalRemark() {return animalRemark;}
public void setAnimalName(String animalName) {this.animalName = animalName;}
public void setAnimalDob(String animalDob) {this.animalDob = animalDob;}
public void setAnimalGender(String animalGender) {this.animalGender = animalGender;}
public void setAnimalSource(String animalSource) {this.animalSource = animalSource;}
public void setAnimalBreed(String animalBreed) {this.animalBreed = animalBreed;}
public void setAnimalRemark(String animalRemark) {this.animalRemark = animalRemark;}
}
DAO class:
package content;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DAO
{
static Connection currentCon = null;
static ResultSet rs = null;
public static loginAuth login(loginAuth bean) {
//preparing some objects for connection
Statement stmt = null;
String username = bean.getUsername();
String password = bean.getPassword();
String searchQuery =
"select * from user where username='"
+ username
+ "' AND password='"
+ password
+ "'";
// "System.out.println" prints in the console; Normally used to trace the process
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: "+searchQuery);
try
{
//connect to DB
currentCon = dbConnection.getConnection();
stmt=currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();
// if user does not exist set the isValid variable to false
if (!more)
{
System.out.println("Sorry, you are not a registered user! Please sign up first");
bean.setValid(false);
}
//if user exists set the isValid variable to true
else if (more)
{
String firstName = rs.getString("FirstName");
String lastName = rs.getString("LastName");
System.out.println("Welcome " + firstName);
bean.setfname(firstName);
bean.setlname(lastName);
bean.setValid(true);
}
}
catch (Exception ex)
{
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
//some exception handling
finally
{
if (rs != null) {
try {
rs.close();
} catch (Exception e) {}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {}
stmt = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
return bean;
}
public static List<animalBean> selectListAnimal() throws SQLException {
Statement stmt = null;
List<animalBean> beans = new ArrayList<animalBean>();
try {
currentCon = dbConnection.getConnection();
String animalSearchQuery = "select a.aname ,a.dob, a.gender , a.source, s.sname, a.remark from animal as a , specie as s where a.specie_id = s.specie_id and a.available ='y'";
stmt=currentCon.createStatement();
rs = stmt.executeQuery(animalSearchQuery);
while (rs.next()) {
animalBean bean = new animalBean();
bean.setAnimalName(rs.getString("aname"));
bean.setAnimalDob(rs.getString("dob"));
bean.setAnimalGender(rs.getString("gender"));
bean.setAnimalSource(rs.getString("source"));
bean.setAnimalBreed(rs.getString("sname"));
bean.setAnimalRemark(rs.getString("remark"));
beans.add(bean);
}
} finally {
if (rs != null) try { rs.close(); } catch (SQLException logOrIgnore) {}
if (stmt != null) try { stmt.close(); } catch (SQLException logOrIgnore) {}
if (currentCon != null) try { currentCon.close(); } catch (SQLException logOrIgnore) {}
}
return beans;
}
}
and last the JSP page animalCheck.jsp:
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
import="content.animalBean"
import="content.DAO"
%>
<!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=windows-1256">
<title>Animal list</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Animal list</h1>
<center>
<table width="100 % " id='table1' border="1" cellspacing="2" cellpadding="2">
<tr class="tab-highlighted-2">
<td class="tab-highlighted-2" width="15">
<div align="left">Name</div>
</td>
<td class="tab-highlighted-2" width="20">
<div align="left">Age</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Gender</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Status</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Breed</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Remarks</div>
</td>
</tr>
<c:forEach items="${beans}" var="view">
<tr>
<td>${view.animalName} </td>
<td>${view.animalDob}</td>
<td>${view.animalGender}</td>
<td>${view.animalSource}</td>
<td>${view.animalBreed}</td>
<td>${view.animalRemark}</td>
</tr>
</c:forEach>
</table>
</center>
</body></html>
I've been struggeling on this since 2 days and i checked many websites and followed many guides but still nothing worked for me :(
I appreciate any kind of help
You forgot to declare the JSTL core taglib. Add the following to top of your JSP:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
See also:
Our JSTL wiki page - contains information about how to install and use JSTL
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to avoid Java code in JSP files?
Unrelated to the concrete problem, there are several other problems in your code:
You should never declare DB resources as static. This is not threadsafe and is prone to resource leaking. Declare them inside the very same method block as you're executing the SQL query.
You have a SQL injection hole in login() method. Use PreparedStatement.
You don't need to use #page import in your JSP if you aren't using any scriptlets.
Classnames are supposed to start with uppercase.
Can you try something like this on top of your page
<% List<animalBean> animals = (animalBean)request.getAttribute("beans"); %>
and then change your c:forEach tag to point it to animals instead of beans?