Store image into database using Struts2 and EJB - database

I have to store my image into database Oracle using EJB through Struts2. It persists data but when I add input file to JSP I have NullPointerException on this line:
byte[] buffer=new byte[(int)this.telethoraxImg.length()];
Below are some parts of my code:
PictureAction.java
public class PictureAction extends ActionSupport implements SessionAware{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(MorphoRECAction.class);
private Map session ;
private ExamMorpho exMoR;
private Patient pat;
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
public ExamMorpho getExam(){
return exMoR;
}
public void setExam(ExamMorpho exMoR){
this.exMoR = exMoR;
}
public Patient getPat(){
return pat;
}
public void setPat(Patient pat){
this.pat = pat;
}
private Date dateExMorpho;
private String echoAbdo;
private String echoCard;
private String exGyneco;
private String exOphtalmo;
private String mamo;
private String telethoraxTxt;
private File telethoraxImg;
public String execute(){
log.info("Entrée dans la méthode execute() ");
System.out.println("creation examen");
ExamMorpho ex = new ExamMorpho();
System.out.println("fin création");
try{
Patient pt = (Patient)session.get("lepat");
InitialContext initialContext = new InitialContext();
ExMorphoRemote facade = (ExMorphoRemote) initialContext.lookup("PatProjet/ExMorphoBean/remote");
System.out.println("ID Patient RECUPERE /" + pt.getIdPat());
System.out.println("Debut conversion image");
byte[] buffer=new byte[(int)this.telethoraxImg.length()];
/*exMoR = new ExamMorpho(buffer, dateExMorpho, echoAbdo, echoCard, exGyneco, exOphtalmo, mamo, telethoraxTxt); */
System.out.println("Fin conversion image");
FileInputStream in=new FileInputStream(this.telethoraxImg);
in.read(buffer);
ex.setTelethoraxImg(buffer);
ex.setDateExMorpho(dateExMorpho);
ex.setEchoAbdo(echoAbdo);
ex.setEchoCard(echoCard);
ex.setExGyneco(exGyneco);
ex.setExOphtalmo(exOphtalmo);
ex.setMamo(mamo);
ex.setTelethoraxTxt(telethoraxTxt);
System.out.println("FIN AJOUT IMAAAGE");
exMoR = facade.AddExMorphoR(ex, pt);
System.out.println("FIN AJOUT MORPHOOS");
} catch(Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
/*private byte[] telethoraxImg = null;
public byte[] getTelethoraxImg() {
return this.telethoraxImg;
}
public void setTelethoraxImg(byte[] telethoraxImg) {
System.out.println("ENTREE ADD IMAGE");
this.telethoraxImg = telethoraxImg;
System.out.println("SORTIE ADD IMAGE");
}*/
/*private Date dateExMorpho = null;
public Date getDateExMorpho() {
return this.dateExMorpho;
}
public void setDateExMorpho(Date dateExMorpho) {
this.dateExMorpho = dateExMorpho;
}
private String echoAbdo = null;
public String getEchoAbdo() {
return this.echoAbdo;
}
public void setEchoAbdo(String echoAbdo) {
this.echoAbdo = echoAbdo;
}
private String echoCard = null;
public String getEchoCard() {
return this.echoCard;
}
public void setEchoCard(String echoCard) {
this.echoCard = echoCard;
}
private String exGyneco = null;
public String getExGyneco() {
return this.exGyneco;
}
public void setExGyneco(String exGyneco) {
this.exGyneco = exGyneco;
}
private String exOphtalmo = null;
public String getExOphtalmo() {
return this.exOphtalmo;
}
public void setExOphtalmo(String exOphtalmo) {
this.exOphtalmo = exOphtalmo;
}
private String mamo = null;
public String getMamo() {
return this.mamo;
}
public void setMamo(String mamo) {
this.mamo = mamo;
}
private String telethoraxTxt = null;
public String getTelethoraxTxt() {
return this.telethoraxTxt;
}
public void setTelethoraxTxt(String telethoraxTxt) {
this.telethoraxTxt = telethoraxTxt;
}
*/
public void setSession(Map session) {
this.session = session;
}
public Map getSession() {
return session;
}
}

jsp code
<form action="fileUpload" method="POST" enctype ="multipart/form-data"><table>
<thead>
<tr>
<th colspan="2"></th>
<th colspan="2" rowspan="3"><center><input type="text" name="dateExMorpho" id="dn"/></a></center></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
<tr><td colspan="2">Echographie Abdominale</td><td><textarea name="echoAbdo" rows=4 COLS=40></textarea></td></tr>
<tr><td colspan="2">Ecographie Cardiaque</td><td><textarea name="echoCard" rows=4 COLS=40></textarea></td></tr>
<tr><td colspan="2">Examen Gynécologique</td><td><textarea name="exGyneco" rows=4 COLS=40></textarea></td></tr>
<tr><td colspan="2">Examen Ophtalmoloique</td><td><textarea name="exOphtalmo" rows=4 COLS=40></textarea></td></tr>
<tr><td colspan="2">Mamographie</td><td><textarea name="mamo" rows=4 COLS=40></textarea></td></tr>
<tr>
<td ROWSPAN="2">Téléthorax</td>
<td >Image</td>
<td><s:file name="telethoraxImg" ContentEditable="false" style="float:left;"/></td>
</tr>
<tr>
<td>Remarques</td>
<td><textarea name="telethoraxTxt" rows=4 COLS=40></textarea></td>
</tr>
</tbody>

my Xml
<action name="fileUpload" class="clientStruts2.PictureAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/pjpeg,image/png,image/gif,image/jpeg,image/jpg,image/pjpeg</param>
<param name="maximumSize">2097152</param></interceptor-ref>
<interceptor-ref name="basicStack"/>
<result name="input">/login/dossierRec.jsp</result>
<result name="error">/login/dossierRec.jsp</result>
<result name="success">/login/dossierRec.jsp</result>
</action>

Related

Asp.net core database data displayed more often than existing

I'm wondering why my ASP.NET Core MVC Project is listing my data double.
What it should be:
What it gives me:
See the difference?
My Controller (Controller Class - Index()-Method):
[HttpGet()]
public async Task<IActionResult> Index(string id)
{
IQueryable<string> werkeQuery = from m in _context.TestDbSet
orderby m.Id
select m.Id;
var test = from t in _context.TestDbSet
orderby t.Id
select t;
if (!string.IsNullOrEmpty(id))
{
test = (IOrderedQueryable<TestSet>)_context.TestDbSet.Where(x => x.Id == id);
}
var filter = new TestSet
{
Werke = new SelectList(await werkeQuery.Distinct().ToListAsync()),
Liste = await test.ToListAsync()
};
return View(filter);
}
My Model-Class (could there be the error?):
`[Table("Test", Schema = "dbo")]
public class TestSet
{
[Key]
[Display(Name = "Werk")]
[Column("Id")]
public string Id { get; set; }
[Display(Name = "Mitarbeiter ID")]
[Column("M_ID")]
public string M_Id { get; set; }
[Column("Beginn")]
[DataType(DataType.Date)]
public DateTime Beginn { get; set; }
[Column("Ende")]
[DataType(DataType.Date)]
public DateTime Ende { get; set; }
[NotMapped]
public SelectList Werke { get; set; }
[NotMapped]
public List<TestSet> Liste { get; set; }
}`
My View (relevant code: displayed list):
`#model DienstplanAnzeige.Models.TestSet
#{
ViewData["Title"] = "Startseite";
}
<form asp-controller="Home" asp-action="Index" method="get">
<div class="input-group mb-3">
<select class="custom-select" asp-for="Id" asp-items="#Model.Werke">
<option value="" disabled selected>Werk auswählen</option>
</select>
<input type="submit" value="Anzeigen" class="btn btn-outline-secondary" />
</div>
</form>
<table class="table table-hover">
<thead>
<tr>
<th>#Html.DisplayNameFor(model => model.Liste[0].Id)</th>
<th>#Html.DisplayNameFor(model => model.Liste[0].M_Id)</th>
<th>#Html.DisplayNameFor(model => model.Liste[0].Beginn)</th>
<th>#Html.DisplayNameFor(model => model.Liste[0].Ende)</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model.Liste)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Id)</td>
<td>#Html.DisplayFor(modelItem => item.M_Id)</td>
<td>#Html.DisplayFor(modelItem => item.Beginn)</td>
<td>#Html.DisplayFor(modelItem => item.Ende)</td>
</tr>
}
</tbody>
</table>`
My Context-Class (named "TestContext"):
public class TestContext : DbContext
{
public TestContext(DbContextOptions<TestContext> options)
: base(options)
{
}
public DbSet<TestSet> TestDbSet { get; set; }
}
Can someone help me?
In your controller, since your id property and parameter is in string therefore instead of using == comparison operator you should use Equals(...) method of string class i.e.
if (!string.IsNullOrEmpty(id))
{
test = (IOrderedQueryable<TestSet>)_context.TestDbSet.Where(x => x.Id.Equals(id, StringComparison.InvariantCultureIgnoreCase);
}

ASP.NET MVC 4 data access

I am trying to show the employee details in a table. I created a model class EmployeeDetail, an EmployeeController and a view in EmployeeDetails.cshtml, plus a class for accessing the database.
EmployeeDetails is my model class:
[Serializable]
public class EmployeeDetails
{
private int _eid;
private string _ename;
private string _eaddress;
private string _gender;
private string _emobileno;
private bool _status;
private DateTime _ejoiningdate;
private DateTime _eleavedate;
#region ================= Code start for public variable =========================
[DataObjectField(true,true,false)]
public int eid {
get { return _eid; }
set { _eid = value; }
}
[DataObjectField(true, true, false)]
public string ename
{
get { return _ename; }
set { _ename = value; }
}
[DataObjectField(true, true, false)]
public string eaddress
{
get { return _eaddress; }
set { _eaddress = value; }
}
[DataObjectField(true, true, false)]
public string gender
{
get { return _gender; }
set { _gender = value; }
}
[DataObjectField(true, true, false)]
public string emobileno
{
get { return _emobileno; }
set { _emobileno = value; }
}
[DataObjectField(true, true, false)]
public bool status
{
get { return _status; }
set { _status = value; }
}
[DataObjectField(true, true, false)]
public DateTime ejoiningdate
{
get { return _ejoiningdate; }
set { _ejoiningdate = value; }
}
[DataObjectField(true, true, false)]
public DateTime eleavedate
{
get { return _eleavedate; }
set { _eleavedate = value; }
}
#endregion ==================== code end for public variable =================
}
Here is my EmployeeController:
public class EmployeeController : Controller
{
// GET: /Employee/
private Employeecon db = new Employeecon();
public ActionResult EmployeeDetails()
{
var studentList = new List<EmployeeDetails>{
new EmployeeDetails() { eid = 1, ename = "John", eaddress = "teszxs" } ,
new EmployeeDetails() { eid = 2, ename = "Steve", eaddress = "jfdsk" } ,
new EmployeeDetails() { eid = 3, ename = "Bill", eaddress = "jfdsk" } ,
new EmployeeDetails() { eid = 4, ename = "Ram" , eaddress = "jfdsk" } ,
new EmployeeDetails() { eid = 5, ename = "Ron" , eaddress = "jfdsk" } ,
new EmployeeDetails() { eid = 4, ename = "Chris" , eaddress = "jfdsk" } ,
new EmployeeDetails() { eid = 4, ename = "Rob" , eaddress = "jfdsk" }
};
return View();
}
}
I created EmployeeDetails.cshtml as a Razor view:
#model IEnumerable<Employee.Models.EmployeeDetails>
<html>
<head>
<title>Employee Details</title>
</head>
<body>
<div align="center">
<b> Employee Details</b>
</div>
<div align="right">
<p>
#Html.ActionLink("New Employee", "NewEmployee")
</p>
</div>
<table align="center" cellpadding="5" cellspacing="5" style="border:1px thin
black;" frame="box">
<tr>
<th>
Name
</th>
<th>
Address
</th>
<th>
Mobile no
</th>
<th>
Joining Date
</th>
</tr>
#foreach(var r in Model)
{
<tr>
<td>
#* #r.ename;*#
#Html.DisplayNameFor(m => r.ename); //but when I am declaring like that its showing error the call is ambiguous between the following methods or properties
</td>
</tr>
<tr>
<td>
#*#r.eaddress;*#
#Html.DisplayNameFor(m => r.eaddress);
</td>
</tr>
<tr>
<td>
#* #r.emobileno;*#
#Html.DisplayNameFor(m => r.emobileno);
</td>
</tr>
<tr>
<td>
#* #r.ejoiningdate;*#
#Html.DisplayNameFor(m => r.ejoiningdate);
</td>
</tr>
}
</table>
</body>
</html>
I am creating a separate folder for data access. I created a data context file Employeecon.cs:
public class Employeecon : DbContext
{
public Employeecon() : base("EmployeeContext")
{
}
public DbSet<EmployeeDetails> emp { get; set; }
}
And I added a connection string to the web.config file:
<add name="EmployeeContext"
connectionString="Data Source=LEVIOZA;Initial Catalog=Manali;Persist Security Info=True;User ID=sa;Password=pedcall"
providerName="System.Data.SqlClient" />
I want to connect to a SQL Server database, instead of local db, or I don't want to create database in the App_Data folder. Like we are did in the asp.net using SQL Server we pass the connection string using SqlConnection like that.
I am trying to connect but I don't know if it's working or not .
I don't know whats wrong with this program. I am trying to learn ASP.NET MVC and this is my first try. Please help me.
So you actually did a good job so far, let me point you to the rest.
Firstly, with database connection a side, you did created a simulation of data, which i assume you wonder why they did not shown in the view.
This is because you did not asked the controlled to use your data as model for the view. Yes, you did specify which type the model is, but you didn't supply it with data.
To fix it, pass the View() method the model instance you want, so it can bind it together.
return View(studentList);
Secondly, you want to extract those information from database, you only lacking querying the information you want from database and return it as model.
For example, lets create another url called /EmployeeDetailsFromDb
public ActionResult EmployeeDetailsFromDb()
{
var studentList = db.EmployeeDetails; // .EmployeeDetails should be changed to the table\dataset you want.
return View(studentList);
}
This will work, assuming the EmployeeDetails(if exists) is actually a collection of EmployeeDetails entities, which is what the view .cshtml expects.

Angularjs returnJson from database

I want to return a JSON Object in a datatable. I've provided the static working code that I found in an example in my angularjs template.
Thanks for help.
controller.js
function datatablesCtrl($scope,DTOptionsBuilder){
$scope.persons = [
{
id: '1',
firstName: 'Monica',
lastName: 'Smith'
},
{
id: '2',
firstName: 'Sandra',
lastName: 'Jackson'
}
];
}
Utenti.jsp
<div class="wrapper wrapper-content animated fadeInRight" ng-controller="datatablesCtrl">
<div class="row">
<div class="col-lg-12">
<table datatable="ng" dt-options="dtOptions" class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in persons">
<td>{{ person.id }}</td>
<td>{{ person.user }}</td>
<td>{{ person.password }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
I need to populate the $scope.person with data into a database.
The table of database is "utenti" with column id,fistName,lastName.
These are my classes.. There is also a class Utenti with a simple getter & setter.
UtentiService.class
#Service("UtentiService")
public class UtentiService implements IUtentiService{
private EntityManager entityManager;
final static Logger logger = Logger.getRootLogger();
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
#Transactional(readOnly = true)
public List<Utenti> getAll() {
Query queryFindAll = null;
try{
queryFindAll = entityManager.createNamedQuery("utenti.findAll");
}catch(Exception ex){
logger.error("Failed in method **getAll** of utentiService: ",ex);
}
return (List)queryFindAll.getResultList();
}
}
IUtentiService.class
public interface IUtentiService {
public List<Utenti> getAll(); //Restituisce una lista di tutti i siti
}
UtentiRest.class
#Path("/utenti")
#Component
#Scope("request")
public class UtentiRest {
#Autowired
IUtentiService nameUtentiService;
final static Logger logger = Logger.getRootLogger();
#GET
#Produces("application/json")
#Path("/getAll")
public JSONObject getAll() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
JSONObject jsonSitiTotal = new JSONObject();
try {
List<Utenti> soluzioni = nameUtentiService.getAll();
Iterator<Utenti> iter = soluzioni.iterator();
JSONArray jsonArray = new JSONArray();
while (iter.hasNext()) {
Utenti ut = (Utenti) iter.next();
JSONObject jsonSiti2 = new JSONObject();
jsonSiti2.put("id", ut.getId());
jsonSiti2.put("user", ut.getUserName());
jsonSiti2.put("password", ut.getPassword());
jsonArray.put(jsonSiti2);
}
jsonSitiTotal.put("Siti",jsonArray);
} catch (JSONException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.BAD_REQUEST)
.entity("JSON Exception " + ex.getMessage())
.build()
);
} catch (NullPointerException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.NO_CONTENT)
.entity("No process find ")
.build()
);
} catch (IllegalArgumentException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.NOT_ACCEPTABLE)
.entity("Couldn't process request with the provided argument: "
+ " (" + ex.getMessage() + ")")
.build()
);
}finally {
executorService.shutdown();
}
return jsonSitiTotal;
}
}

How to display/store and retrieve image as varbinary(MAX) using ASP.NET MVC view

I am new to ASP.NET MVC, so kindly excuse for mistakes.
I need a view page (index.cshtml) where I can display the image, change/delete the image by storing it in Varbinary(max) column in a SQL Server table.
There are these columns in the database table:
ID int primary key Identity not null,
ImageName nvarchar(50) ,
ImagePicInBytes varbinary(MAX) null
I am using a Image.cs with this code:
public class Image
{
public int ID {get; set;}
public string ImageName {get; set;}
public byte[] ImagePicInBytes {get; set;}
}
ImageContext class as below
public class ImageContext : DbContext
{
public DbSet<Image> Images { get; set; }
}
Connection string as below
<connectionStrings>
<add name="ImageContext"
connectionString="server=.; database=Sample; integrated security =SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
ImageController as below
public class ImageController : Controller
{
private ImageContext db = new ImageContext();
// GET: /Image/
public ActionResult Index()
{
return View(db.Images.ToList());
}
// GET: /Image/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
}
Have created views as below
public class ImageController : Controller
{
private ImageContext db = new ImageContext();
// GET: /Image/
public ActionResult Index()
{
return View(db.Images.ToList());
}
// GET: /Image/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
// GET: /Image/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
// POST: /Image/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Image image = db.Images.Find(id);
db.Images.Remove(image);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
My create.cshtml (view) as below
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ImageName)
</th>
<th>
#Html.DisplayNameFor(model => model.ImagePicInBytes)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ImageName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ImagePicInBytes)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
I have the below 3 questions
How can I create a new record in datatable by uploading new image from file system to Varbinary column in database?
How can I have the view to have FILEUPLOAD control in the 'create View' and 'Edit view'
Can I use HttpPostedFileBase to achieve the above from Create.cshtml? If yes: how? Any suggestions or reference links available?
first of all create a viewmodel for Image class
public class ImageViewModel
{
public string ImageName {get; set;}
public HttpPostedFileBase ImagePic {get; set;}
}
then for uploading a photo in your create view
#model ExmpleProject.Models.ImageViewModel
#using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, new {enctype="multipart/form-data"})){
#Html.AntiForgeryToken()
#Html.LabelFor(m => m.ImageName)
#Html.TextBoxFor(m => m.ImageName)
#Html.LabelFor(m => m.ImagePic )
#Html.TextBoxFor(m => m.ImagePic , new { type = "file" })
<br />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
then in post method of your controller for create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageViewModel model)
{
if (ModelState.IsValid)
{
var uploadedFile = (model.ImagePic != null && model.ImagePic.ContentLength > 0) ? new byte[model.ImagePic.InputStream.Length] : null;
if (uploadedFile != null)
{
model.ImagePic.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
}
Image image = new Image
{
ImageName = model.ImageName,
ImagePicInBytes = uploadedFile
}
db.Create(image);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
so for your edit method you can do similar implementation but instead of Create(image) use Update(image)

how to use jstl arraylist in jsp

I have problem to show data in jsp page with help of jstl. there is code and also error that i have got ;
my JSP PAGE is
<body>
<table border="1">
<thead>
<tr>
<th>UserId </th>
<th>First Name </th>
<th>Last Name </th>
<th>DOB </th>
<th>Email Id </th>
<th colspan="2" >Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user" >
<tr>
<td><c:out value="${user.userid}" /></td>
<td><c:out value="${user.firstName}" /></td>
<td><c:out value="${user.lastName}" /></td>
<td><fmt:formatDate pattern="yyyy-MMM-dd" value="${user.dob}" /></td>
<td><c:out value="${user.email}" /></td>
<td>Update</td>
<td>Delete</td>
</tr>
</c:forEach>
</tbody>
</table>
<p>Add User
this code where we fetch ALLUSERLIST IS :
public ArrayList getAllUsers()
{
ArrayList<User> USER = new ArrayList<User>();
try
{
iduQuery = "select * from user";
Statement st = conn.createStatement();
ResultSet rs =st.executeQuery(iduQuery);
while(rs.next())
{
User user =new User();
user.setUserid(rs.getString("userid"));
System.out.println("USER ID : " + user);
user.setFirstname(rs.getString("firstname"));
user.setLastname(rs.getString("lastname"));
user.setDob( new java.sql.Date(rs.getDate("dob").getTime()));
user.setEmail(rs.getString("email"));
USER.add(user);
}
}catch(Exception e)
{
e.printStackTrace();
System.out.println("Error : GetALLUSER " + e);
}
return USER;
}
Where we call jsp page :
forward ="/listUser.jsp";
ArrayList<User> myList = new ArrayList<User>();
myList = userdao.getAllUsers();
System.out.println("THis List of data arte : " + myList);
request.setAttribute("users", myList);
and error is show that:
HTTP Status 500 -
org.apache.jasper.JasperException: org.apache.jasper.JasperException: An exception occurred processing JSP page /listUser.jsp at line 33
30: <tbody>
31: <c:forEach items="${users}" var="user">
32: <tr>
33: <td><c:out value="${user.userid}" /></td>
34: <td><c:out value="${user.firstName}" /></td>
35: <td><c:out value="${user.lastName}" /></td>
36: <td><fmt:formatDate pattern="yyyy-MMM-dd" value="${user.dob}" /></td>
User.class
package com.d.model;
import java.util.Date;;
public class User {
private String userid;
private String firstName;
private String lastName;
private Date dob;
private String email;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
/**
* #return the firstname
*/
public String getFirstname() {
return firstName;
}
/**
* #param firstname the firstname to set
*/
public void setFirstname(String firstName) {
this.firstName = firstName;
}
/**
* #return the dob
*/
public Date getDob() {
return dob;
}
/**
* #param dob the dob to set
*/
public void setDob(Date dob) {
this.dob = dob;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the lastname
*/
public String getLastname() {
return lastName;
}
/**
* #param lastname the lastname to set
*/
public void setLastname(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "User [userid= " + userid + ", firstName= '" + firstName
+ "', lastName=" + lastName + ", dob=" + dob + ", email="
+ email + "]";
}
}
spelling mistake setUsrid.change it setUserid
you are setting usrid but you are accessing userid
user.setUsrid(rs.getString("userid")); //usrid
${user.userid} // userid
spelling mistake setUsrid.change it to setUserid
you are setting usrid but you are accessing userid
user.setUsrid(rs.getString("userid")); //usrid
${user.userid} // userid

Resources