Error passing ArrayList from Servlet to JSP - java

I have an important question but firs sorry for my english, I only know the basic. Well my problem is that I have an error passing an ArrayList from a servlet to jsp page:
<% ArrayList<Usuario> u= (ArrayList<Usuario>)session.getAttribute("listado");%>
<table align="left" cellpadding="0" cellspacing="1">
<tr bgcolor="blue">
<td>Usuario</td><td>Nombre</td>
<td>Apellido</td><td>Clave</td>
</tr>
<% for(int i=0;i<u.size();i++){ %>
<% Usuario usuario = u.get(i); %>
<tr>
<td> <%= usuario.getUsuario() %></td>
<td> <%= usuario.getNombre() %></td>
<td> <%= usuario.getApellido() %></td>
<td> <%= usuario.getClave() %></td>
</tr>
<%} %>
</table>
That's how I'm doing this but I receive an error in:
<% for(int i=0;i<u.size();i++){ %>
What I'm doing wrong? also my servlet Method is like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd;
try {
Connection cn = MySQLConnection.obtenerConexion();
String sql = "select * from tb_usuario";
PreparedStatement ps = cn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<Usuario> listado = new ArrayList<Usuario>();
while (rs.next()){
Usuario usu = new Usuario(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4));
listado.add(usu);
}
request.setAttribute("listado", listado);
request.getRequestDispatcher("/listado.jsp");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I hope you could help me!

You should not use scriptlets in your JSP. You should use EL and tags in your JSP.
e.g.
${listado}

You are setting the variable in request object while retrieving from session, which is not present hence the issue.
You are setting the attribute in doPost as below":
request.setAttribute("listado", listado);
You are retrieving the attribute in your JSP as below":
<% ArrayList<Usuario> u= (ArrayList<Usuario>)session.getAttribute("listado");%>
Please use the same scope session or request in both places.

you are setting the value in to request scope
request.setAttribute("listado", listado);
but then trying to access it in session scope.
session.getAttribute("listado");
due to this u might get a null pointer exception in
u.size()...
try to access it in request scope
request.getAttribute("xxxxxx")
try to avoid adding java code inside JSP whihc is a bad practice. use EL and JSTL instead. you can to the casting part inside the code too..

scriptletsare discouraged to use in ajsp page, use JSTL tags instead. use c-foreach tag to iterate over your arrayList in your jsp page. and you are setting an attribute in a request scope and trying to get it in session scope in your jsp.
heres the link which explains c-foreach tag

Related

Calling a method from servlet in a JSP page,method with parameters from that JSP page

I tried different ways to call that method, but none worked. My problem is that I want to give as variable parameters from that jsp page where I calling that method
those are my varabiles:
<c:forEach begin="0" end="21" step="1" var="time">
<c:forEach begin="${0}" end="${6}" step="1" var="day">
.............
</c:forEach>
.........................
</c:forEach>
<c:set var="sala" value='<%=session.getAttribute("room").toString()%>'/>
<c:set var="z" value='<%=Integer.parseInt(session.getAttribute("next").toString())%>'/>
Here I tried to call my method
<c:set var="getData" value='<%= try{
mysql a =new mysql();
a.getData( %>${time},${day}<%+%>${z},${sala}<%);
}catch (Exception ex){ return ex.toString();} %>'/>
we can't use the jstl variables directly in scriptlet tags.
We need to use the below syntax :
pageContext.getAttribute(String name);
According to your example,
<%
try
{
mysql a =new mysql();
String time=pageContext.getAttribute("time");
String day=pageContext.getAttribute("day");
String sala=pageContext.getAttribute("sala");
String getData=a.getData(time,day,sala);
}
catch (Exception ex){ return ex.toString();}
pageContext.setAttribute("getData", getData);
%>
<c:out value="${getData}"/>

Reset a scriplet variable on refresh

I have a table and I want the lines to be numbered.
In my jsp, I have something like that:
<%! int i = 0; %>
<c:forEach items="${clients}" var="client">
<tr>
<td align="center"><%= ++i %></td>
<td><c:out value="${client.nomPrenom}"/></td>
....
My problem is when I refresh the page, variable i is not reset to 0. It continues to ++
What do I do wrong?
You could do that using jstl as follows , as scriplets are not advised over decades
<c:forEach items="${clients}" var="client" varStatus="loop">
<tr>
<td align="center"><c:out value="${loop.index}" /></td>
<td><c:out value="${client.nomPrenom}"/></td>
</tr>
</ c:forEach>
see How to avoid Java code in JSP files? to learn more on using the jstl and EL
Your JSP is translated to servlet by server container. Every time you refresh your page _jspService is called.
Translation of JSP to servlet code :
public class HelloWorld2$jsp extends HttpJspBase {
//code declare inside <%! %> method goes here
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
{
// code declare inside <% %> method goes here
}
}
Instead of
<%! int i = 0; %>
Use Below Code:
<% int i = 0; %>

Prevent SQL statement from executing on JSP page load

How can I have a SQL statement that updates data when a button is clicked, not execute when the page loads?
I have a very simple table that has a player name, a player score, and player id attributes and only one row. When I am on this page, I want the button to execute the update query to increase player score, but it's happening every time the page loads.
Is there a boolean or something I can set to prevent it from adding 1 to the player score on every load?
Please don't ask why I'm using a JSP in this context. It's bad to do, I know, but these are my requirements.
Here is my code:
<%# page contentType="text/html" %>
<%# page import="java.text.DecimalFormat" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.ResultSet" %>
<%# page import="java.sql.Statement" %>
<%# page import="java.lang*" %>
<!DOCTYPE html>
<html>
<head>
<title>Player scores</title>
<script>
function reloadPage() {
location.reload();
}
</script>
</head>
<body>
<%!
String name = "";
Integer score = 0;
Integer pID = 0;
%>
<form name="form1" method="POST" onsubmit="return false">
<p align="center">
<input type="BUTTON" value="+" onclick="reloadPage();"/>
</p>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
stmnt.executeUpdate("update players set playerScore=playerScore+1 where playerID=1");
} catch (Exception e) {
}
%>
</form>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
ResultSet rs = stmnt.executeQuery("select playerID, playerName, playerScore from players where playerID=1");
if (rs.next()) {
name = rs.getString("playerName");
score = rs.getInt("playerScore");
pID = rs.getInt("playerID");
} else {
name = "-";
score = 0;
pID = 404;
}
} catch(Exception e) {
}
%>
<table align="center">
<tr>
<th>Player name:</th>
<td id="pID"><%=name%></td>
</tr>
<tr>
<th>Player score:</th>
<td id="pN"><%=score%></td>
</tr>
<tr>
<th>Player id:</th>
<td id="pi"><%=pID%></td>
</tr>
<p class="center">
Go back
</p>
</table>
</body>
</html>
The update code always gets executed because you have your code written that way.
This code:
<form name="form1" method="POST" onsubmit="return false">
<p align="center">
<input type="BUTTON" value="+" onclick="reloadPage();"/>
</p>
that calls:
<script>
function reloadPage() {
location.reload();
}
</script>
is just a refresh with no extra parameters. You always perform a GET.
You need to tell the JSP to do something different when you click the + button. You might try something like this (please have a look at this tutorial first):
<form name="form1" method="POST" action="yourJSPWhateverIsCalled.jsp">
<p align="center">
<input type="submit" value="+" name="increaseScore" />
</p>
Then guard your update code with an if:
<%
if (request.getParameter("increaseScore") != null) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
stmnt.executeUpdate("update players set playerScore=playerScore+1 where playerID=1");
} catch (Exception e) {
}
}
%>
Class.forName is needed only once and you could reuse the connection to create the statements but that's another story. Also, a JSP isn't the place to postprocess a form submit (use a plain vanilla servlet).
One other problem with your code is that the JSP is thread UNsafe because of this definition:
<%!
String name = "";
Integer score = 0;
Integer pID = 0;
%>
If you use <%! the code is placed at servlet class level when your JSP gets translated to a servlet and not inside the _jspService method where it belongs. You are basically adding state to your JSP which is thread unsafe because the servlet container can reuse the same servlet instance to handle multiple requests.
Finally, I would strongly suggest you to read a JSP tutorial before continuing. An official tutorial is here.

JSP display first then do business logic

My requirement is to display userName and FirstName first then try logic next....but here after some time in try block(few secs for try logic loading/execution) then userName and password displaying in page...How can i display userName/Firstanme then try logic next.
<html>
<head>
</head>
<body>
<%
String lastname= request.getParameter("lastname");
String firstname= request.getParameter("firstname");
%>
<tbody>
<tr>
<td>Firstname</td>
<td>:</td>
<td><%=firstname %></td>
</tr>
<tr>
<td>Lastname</td>
<td>:</td>
<td><%=lastname %></td>
</tr>
</tbody>
<%
try
{
System.out.println("Inside Thread");
Thread.currentThread().sleep(10000);
}
catch(Exception ex1)
{
System.out.println(ex1.getMessage());
}
%>
</body>
</html>
JSP is serverside language, the whole page is rendered, then send back to browser/client.
So with JSP you cannot do this.
You can include javascript in your jsp page, which talks to a webservice that does the logic you want it to do. The webservice can also return data that you can use to update your page...
I suggest you lookup AJAx on the web, a good place to start is:
http://www.w3schools.com/ajax/

Convert a List to String to populate webpage in JSP

I have DAO bean rows retrieved in a List. In my JSP I am accessing the List to iterate thru to populate my page. My JSP can't access the List because it says it must be a String when I execute a request.getParameter. How I convert this to String eventually populate my page?
public List getAccessRequest()
{
List accessRequesttList = new ArrayList()); // parse List to string
//AccessRequest accessrequest = null;
AccessRequest accessRequest = new AccessRequest());
try
{
System.out.println("Try statement begins AccessRequestDAO");
PreparedStatement accrqststmt = super.getConnection().prepareStatement(AccRqstSqlStmt);
ResultSet resultSet = accrqststmt.executeQuery();
while (resultSet.next())
{
// Creating an instant of job follows
accessRequest = new Accessrequest();
accessRequest.setJOB_NAME(resultSet.getString("job_name"));
accessRequest.setRequest_ts(resultSet.getTime("request_ts"));
accessRequestList.add(accessRequest);
Iterator iterator = accessRequestList.iterator();
while (iterator.hasNext())
{
accessRequest = (Accessrequest) iterator.next();
}
}
return (accessRequestList);
My JSP look like below:
<%
List jobList = request.getParameter("acccessrequests"); // parse List to String
Iterator iterator = jobList.iterator();
while (iterator.hasNext())
{
accessRequest = (AccessRequest) iterator.next());
%>
<tr>
<td><input type="checkbox" name="<%accessRequest.getApproval_ind(); %>"></td>
<td><input type="text" id="jobname' name="accessRequests" value="job_name"></td>
HttpServletRequest#getParameter() returns a String, not a List. So the compiler is right.
I am not sure how you have ever set the List as a request parameter, there's no such method like HttpServletRequest#setParameter(). So you're probably misinterpreting something. The normal approach is to set the list as request attribute by HttpServletRequest#setAttribute() and access it in JSP by EL (expression language) like as ${attributeName}. You also normally iterate over the list using JSTL <c:forEach> tag.
Assuming that you've set the list in the request scope using a Servlet like follows...
request.setAttribute("list", list);
...here's a kickoff example how to iterate over the list:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.property1}</td>
<td>${item.property2}</td>
<td>${item.property3}</td>
</tr>
</c:forEach>
</table>
Alhamdulillah, thanks God!
This help me a lot. I try to build my own java Web framework.
Before reading this QA, I don't know how to access an object (say, row of table) from a JSP.
I just redirect it, and leave the database code in JSP, generated by DreamWeaver. Now I know how to do it. For example, this is a BiroController, which display data from Biro Table :
public void index() throws IOException, ServletException {
List list=new ArrayList();
list.add(BiroModel.create("1", "SDM"));
list.add(BiroModel.create("2", "Keuangan"));
request.setAttribute("list", list);
super.index();
}
firstly, I populate an array (subsequently, this will come from database table). and then set request attribute, then call superclass index method :
public void index() throws IOException, ServletException {
RequestDispatcher rd = request.getRequestDispatcher(viewPage);
if(rd!=null){
rd.forward(request, response);
}else{
PrintWriter out = response.getWriter();
out.print("can not dispatch to " + viewPage);
}
//OLD Code : response.sendRedirect(ServletUtil.getBaseUrl(request) + viewPage)
}
And, I did as you instructed in the JSP :
<c:forEach items="${list}" var="item">
<tr>
<td>${item.idbiro}</td>
<td>${item.biro}</td>
</tr>
</c:forEach>
I use Netbeans, so I can easily pick JSTL library from the list of available library
It works charmingly.. :) tq

Categories

Resources