Displaying data from ArrayList (EJB + Servlet + JSP(JSTL)) - java

I have a stateless Session Bean in which I get the values ​​from the database and write them down in Arraylist, who returns to the servlet. In a servlet I send ArrayList on JSP page and try to show the value, but displays only the line "dataList", what is my mistake?
Here is my code:
ViewBean.java
//imports
#Stateless
#LocalBean
public class ViewBean {
public List getData() {
ResultSet rs = null;
List list = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/c_store", "root", "root");
Statement stmt = con.createStatement();
String query = "SELECT product.name_prod, product.price_prod, buy.number_buy, client.name_client, client.date_client FROM product, buy, client WHERE product.id_prod = buy.id_buy = client.id_client;";
stmt.executeQuery(query);
rs = stmt.getResultSet();
list = new ArrayList();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getInt(2));
list.add(rs.getInt(3));
list.add(rs.getString(4));
list.add(rs.getString(5));
}
rs.close();
stmt.close();
con.close();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
ViewServlet.java
//imports
#WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
ViewBean viewBean;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
List data = new ArrayList();
data = viewBean.getData();
request.setAttribute("dataList", data);
for(int i = 0; i<data.size(); i++){
out.println(data.get(i));
}
}
}
view.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Records</title>
</head>
<body>
<c:forEach var="item" items="dataList">
<b><c:out value="${item}" /></b>
</c:forEach>
</body>
</html>

You forgot to declare dataList as a variable, look at the items attribute in the loop:
<c:forEach var="item" items="${dataList}">
^ here is the bug, add the dollar sign and the curly braces
<b><c:out value="${item}" /></b>
</c:forEach>

Related

Getting empty list of (objects)teams in jsp page from a simple class

I have an jsp page in which I am trying to get list of teams(class objects) in jsp to show some data regarding teams but problem is that list getting to me on jsp is empty and I don't know why it is empty, I tried to search it on internet but could not find the solution, I also debugged my jsp page so finding the empty list.
here is my jsp code
`<%#include file="index.html" %>
<%#page import="java.util.List,java.util.ArrayList"%>
<%#page import="Models.Team" %>
<%#page import="Controller.HockeyLeagueInitialization"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
HockeyLeagueInitialization hli = new HockeyLeagueInitialization();
List<Team> teams = (ArrayList<Team>) hli.getTeamList();
%>
<ul class="dropdown-menu" role="menu" style="margin-left: 0%">
<% for (int i = 0; i < teams.size(); i++) {
Team currentTeam = teams.get(i);
%>
<li> <%= currentTeam.getTeamName()%></li>
<% }%>
</ul>`
and here is my function that return list
public List<Team> getTeamList() {
String selectAllTeams = "select * from team;";
List<Team> listOfTeam = new ArrayList<Team>();
try {
stmt = new DBInitialization().getStatement();
ResultSet rs = stmt.executeQuery(selectAllTeams);
while (rs.next()) {
listOfTeam.add(new Team(rs.getInt("id"), rs.getString("name")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listOfTeam;
}

Not able to display data from database on jsp page using setAttribute and getString() in Servlet

Here is the Servlet
public class displayServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection con = dbConnection.getConnection();
String query = "SELECT theaterNames, FROM thtrname where id in(11,12)";
try{
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
String str = null;
while(rs.next()){
str = rs.getString(1);
}
out.print(str);
HttpSession session = request.getSession();
session.setAttribute("thtr", str);
RequestDispatcher rd = request.getRequestDispatcher("success.jsp");
rd.forward(request, response);
rs.close();
ps.close();
con.close();
}catch(Exception ex){
}
}
}
Here is the success.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" session="true"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<font color="green">
<%= request.getAttribute("thtr") %>
<h1><c:out value="${sessionScope.thtr}" /></h1>
</font>
</body>
</html>
I just don't get it where I am going wrong. I am using both JSTL and Scriptlet but all I am getting on the success.jsp page is null.
You need to set the value to request instead of session
from
session.setAttribute("thtr", str);
to
request.setAttribute("thtr", str);
a then to show just use ${thtr} in jsp

Explain me some pieces of the following JSP code :

I am unable to get a piece of code in the following JSP code ( commented as d1, d2, d3, d4):
<%#page import="java.sql.*" errorPage="/MyError.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LoginProcess</title>
</head>
<body>
<%
Connection conn = null;
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
out.println("Error(class):"+e);
}
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentdb","root","mysql");
PreparedStatement stmt = conn.prepareStatement("select * from studentdb.userdetails where uname=? and pass=?");
stmt.setString(1, uname);
stmt.setString(2, pass);
ResultSet rs = stmt.executeQuery();
if(!rs.next())
{
out.println("username or password is incorrect");
%> <%--d1--%>
Try Again:<%#include file="Login.html" %> <%--d2--%>
</body> <%--d3--%>
</html> <%--d4--%>
<%
return;
} //if
} //try-sql
catch(SQLException e)
{
out.println("Error(SQL):" + e);
}
finally
{
conn.close();
}
%>
This is Home Page<br>
Welcome,<b> <%= uname%></b>
</body>
the following are appearing in an if block which I am not getting why and how do they work , I know the meaning of <%#include file="Login.jsp"> and selective tags but not I am getting how are they workign here.
%> <%--d1--%>
Try Again:<%#include file="Login.html" %> <%--d2--%>
</body> <%--d3--%>
</html> <%--d4--%>
<%
(the body and html tags are not appearing in the above piece of code).
Instead of if(!rs.next()), try using if(rs.isBeforeFirst()). If rs.isBeforeFirst() is false, then you have no records.

redirects not working in jsp

i have created a jsp page view.jsp and corresponding to that i have created a servlet admin.java
code of both below...
when i click on register a blank page appears...redirects are not working. please help me in resolving this
view.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">
<title>Insert title here</title>
</head>
<body>
<form action="admin">
username <input type="text" name="username" value="" />
password <input type="text" name="password" value="" />
<input type="submit" name="register" value="register" />"
</form>
</body>
</html>
admin.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class admin extends HttpServlet {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/inventory";
static final String USER = "root";
static final String PASS = "root";
Connection conn = null;
Statement stmt = null;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
String user = req.getParameter("username");
String pass = req.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "select * from admins";
//String sql = "select * from admins WHERE username='"+user+"' AND
password='"+pass+"'";
ResultSet rs = stmt.executeQuery(sql);
PrintWriter pw = res.getWriter();
//res.setContentType("text/html");
while (rs.next())
{
if((user.equals(rs.getString(0))) && (pass.equals(rs.getString(1))))
{
//String n=rs.getString("username");
//String p=rs.getString("password");
res.sendRedirect("loginsuccess.jsp");
}
else
{
res.sendRedirect("loginfailure.jsp");
}
}
pw.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use RequestDispatcher instead of sendRedirect():
RequestDispatcher reqDispatcher = req.getRequestDispatcher("path/loginsuccess.jsp");
reqDispatcher.forward(req, res);
Read more about RequestDispatcher.
Read the difference between RequestDispatcher and sendRedirect, and whento use both of them.
Try this
getServletContext().getRequestDispatcher("/loginsuccess.jsp").forward(request, response);
sample code :
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
request.setAttribute("error", "Unknown login, please try again."); // Set error.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}
you should try that method, but my suggestion as:
I think you should not close the statement, result set and connection,.
And then you should check the if condition. if maybe your condition have an error the page like empty. so should check that..
source from : https://stackoverflow.com/a/2048640/3242978
When you click 'register' button it submits the form as a HTTP POST request. You need to implement doPost() instead.

Servlets/JSP and multiple inserts to a database

I have a page that takes student attendance. It prints out a student list with a checkbox next to each student. Then the person clicks submit and send the selected student's ids and the lab ids to the database.
The problem I'm having is its sending the last ticked box to the database and none of the rest. I'm assuming its overwriting the ones previous to it but I am unsure how I can fix this problem.
Here is my doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt((String)request.getParameter("user_id"));
int lab_id = Integer.parseInt((String)request.getParameter("lab_id"));
System.out.println("I got a blow job");
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successful attendance.";
response.sendRedirect("Tutor_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
}
and here is my JSP page:
<%# 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">
<title>Mars University Lab System</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>
<body>
<jsp:include page="headerTutor.jsp"/>
<div id = "centrecontent">
<h3>Students In Tutorial</h3>
<h2>Attendance List</h2>
<%
String[] list1 = (String[])request.getAttribute("res1");
String[] list2 = (String[])request.getAttribute("res2");
String[] list3 = (String[])request.getAttribute("res3");
String[] list4 = (String[])request.getAttribute("res4");
if(null == list1){%>
<th>Uni Id</th><th>Name</th><th>Email</th>
<%
}else{ %>
<form name="ViewStudentsTutor" ACTION="http://www.crackman.net.au/ICE/test.php\" method="post">
<% for(int i=0; i<list1.length; i++)
{
%> <input type="hidden" name="lab_id" value=<%=request.getParameter("labid")%>>
<%out.println(list2[i]);%>
<%out.println(list3[i]);%>
<%out.println(list4[i]); %>
<input type="checkbox" name="user_id" value=<%out.println(list1[i]);%>><br>
<% }}
%>
<input type="submit" value="Submit" name="Submit"/>
</form>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
You are taking only one user_id using request.getParameter("user_id")
Instead you should use request.getParameterValues("user_id") that will return an array of String of all user_ids which you want and not a single user_id which currenlty you are getting
Similar is for lab_id

Categories

Resources