I have one jsp page and one servlet, In servlet i want to fetch some rows from a particular table and pass them to jsp .I am able to retrieve in servlet and trying to pass them in jsp it is not getting displayed please anyone help me out here...
public class TimeDetail extends HttpServlet {
#SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
HttpSession session = request.getSession(true);
String eid = (String) session.getAttribute("eid");
int count = 0;
Connection con = ConnectionManager.getConnection();
try {
Statement st = con.createStatement();
Statement st1 = con.createStatement();
String Query = "select date, intime, outtime, eid from fulltime where eid='" + eid + "'";
ArrayList Rows = new ArrayList();
ResultSet rs = st.executeQuery(Query);
List agentList = new ArrayList();
while (rs.next()) {
ArrayList row = new ArrayList();
for (int i = 1; i <= 4; i++) {
row.add(rs.getString(i));
}
String n1 = rs.getString("date");
String n2 = rs.getString("intime");
String n3 = rs.getString("outtime");
String n4 = rs.getString("eid");
session.setAttribute("n1", n1);
session.setAttribute("n2", n2);
session.setAttribute("n3", n3);
session.setAttribute("n4", n4);
// response.sendRedirect("TimeDetail.jsp");
Rows.add(row);
}
request.getSession().setAttribute("results", Rows);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/TimeDetail.jsp");
rd.forward(request, response);
} catch (Throwable theException) {
System.out.println(theException);
}
}
}
and here is jsp code
<tr><td>
<table width="600" height="300"align=center cellspacing=0 border="0"
<caption><h2>List of users</h2></caption>
<tr>
<th>date</th>
<th>intime</th>
<th>outtime</th>
<th>eid</th>
</tr>
<c:forEach var="user" items="${Rows.rows}">
<tr>
<td><c:out value="${user.date}" /></td>
<td><c:out value="${user.intime}" /></td>
<td><c:out value="${user.outtime}" /></td>
<td><c:out value="${user.eid}" /></td>
</tr>
</c:forEach>
</table>
</div>
</table><BR>
</fieldset>
</td></tr></table>
</td></tr>
</table>
</body>
</html>
Your for each loop should be like this ,
<c:forEach var="user" items="${results}">
<tr>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
</tr>
</c:forEach>
And your servlet as ,
try {
Statement st = con.createStatement();
Statement st1 = con.createStatement();
String Query = "select date, intime, outtime, eid from fulltime where eid='" + eid + "'";
ArrayList row = new ArrayList();
ResultSet rs = st.executeQuery(Query);
while (rs.next()) {
row.add(rs.getString("date"));
row.add(rs.getString("intime"));
row.add(rs.getString("outtime"));
row.add(rs.getString("eid"));
}
}
request.getSession().setAttribute("results", row);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/TimeDetail.jsp");
rd.forward(request, response);
Hope this helps !!
Related
I attempted to retrieve user information from the MySQL database, but when I ran my program and searched for the user by name, nothing appeared in the HTML table. I can't figure out what's the issue. Below in my code,
Web Service Code
#WebMethod(operationName = "search")
public List<UserRegister> search(#WebParam(name = "name")String name ) {
Connection connection = DBUtils.getConnection();
List<UserRegister> user = new ArrayList<>();
UserRegister u=null;
try {
String searchQuery = "select * from register where name= ?";
PreparedStatement ps = connection.prepareStatement(searchQuery);
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
u = new UserRegister();
u.setName(rs.getString("name"));
u.setBranch(rs.getString("branch"));
u.setAge(rs.getString("age"));
u.setPhone(rs.getString("phone"));
user.add(u);
}
}catch(SQLException asd){
System.out.println(asd.getMessage());
}
return user;
}
Java Servlet
#WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Name = request.getParameter("name");
UserRegister userRegister = new UserRegister();
userRegister.setName(Name);
searchClass sclass = new searchClass();
request.setAttribute("name", sclass.search(Name));
RequestDispatcher view = request.getRequestDispatcher("display.jsp");
view.forward(request, response);
}
}
Java Class For Call the Web Service
public class searchClass {
public List<UserRegister> search( String username) {
SerachService_Service service=new SerachService_Service();
SerachService proxy =service.getSerachServicePort();
return (List<UserRegister>) proxy.search(username);
}
}
JSp For Search Bar
<form method="Get" action="SearchServlet">
<table border="0" width="300" align="center" bgcolor="#CDFFFF">
<tr><td colspan=2 align="center">
<h3>Search Employee</h3></td></tr>
<tr><td ><b>User Name</b></td>
<td>: <input type="text" name="name">
<tr><td colspan=2 align="center">
<input type="submit"></td></tr>
</table>
</form>
</body>
JSP Display Data
<table>
<c:forEach var="user" items="${name}">
<tr>
<td>
<c:out value="${user.name}" />
</td>
<td>
<c:out value="${user.branch}" />
</td>
<td>
<c:out value="${user.age}" />
</td>
<td>
<c:out value="${user.phone}" />
</td>
</tr>
</c:forEach>
</body>
I am populating a list in backend in java. Setting attribute in spring model and want to iterate and show that list in front end.
But the list turns out to be empty. I debugged and checked that list is getting populated at the backend.
Can we anyone help to debug and tell what I am missing.
In the model I am setting the values to model.addAttribute("videos", temp);
<table class="table table-bordered" style="width:100%">
<col width = 33%>
<col width = 33%>
<col width = 33%>
<thead>
<tr>
<th style="text-align:center">Title</th>
<th style="text-align:center">Source</th>
<th style="text-align:center">Link</th>
</tr>
</thead>
<tbody>
<c:forEach items="${videos}" var="temp">
<tr>
<td><c:out value="${temp.title}"/></td>
<td><c:out value="${temp.source}"/></td>
</tr>
</c:forEach>
</tbody>
</table>
Browser Console Image
Controller Code:
UserLoginJDBCTemplate uLoginJDBCTemplate =
(UserLoginJDBCTemplate)context.getBean("userLoginJDBCTemplate");
List<VideoList> videos = uLoginJDBCTemplate.listVideos(user.getName(),true);
// model.addAttribute("modules", modules);
model.addAttribute("videos", videos);
return "result";
JDBC Connection -
List <VideoList> videos = new ArrayList<VideoList>();// jdbcTemplateObject.query(SQL, new VideoListMapper());
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(SQL);
ps.setString(1, uname);
ResultSet rs = ps.executeQuery();
VideoList temp;
rs = ps.executeQuery();
if (rs.next()) {
temp = new VideoList(rs.getString("title"),rs.getString("source"),rs.getString("actual_url"));
videos.add(temp);
}
rs.close();
ps.close();
return videos;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
I need your help. I'm currently doing a project on purchase. After the user click on Add to cart, the item will be added to the cart but not yet persist into database. Then later on, I will have the user to click checkout. PurchaseCart.jsp will do action and bring them to PurchaseCheckOut servlet. So, how can I get the data from previous ?
PurchaseCart.jsp
<body>
<%!List<Double> stockArray = new ArrayList<Double>() ;%>
<%!List<Object> list1 = new ArrayList<Object>();%>
<% Object o = request.getAttribute("purchased");
list1.add(o);
int size = list1.size();
double stockPrice = (Double)request.getAttribute("stockPriceReal");
if(stockArray.size() == 0)
{
stockArray.add(stockArray.size(),stockPrice);
}
else {
stockArray.add(stockArray.size(), stockPrice); } %>
<form action = "../PurchaseCheckOut">
<table border="1">
<thead>
<tr>
<th>No.</th>
<th>Purchase Details ID</th>
<th>Stock ID</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<% for (int g = 0; g < size; g ++) { %>
<tr>
<% String toString = list1.get(g).toString();
String subString1 = toString.substring(0,7);
String subString2 = toString.substring(7,9);
String subString3 = toString.substring(9,14);
%>
<td><%= g +1 %></td>
<td><%= subString1 %></td>
<td><%= subString2 %></td>
<td><%= subString3 %></td>
<td><%= stockArray.get(g).toString() %></td>
</tr>
<% } %>
</tbody>
</table>
<input type = submit name="checkout" value="Check Out">
</form>
</body>
PurchaseCheckOut.java (I've done the persist part and redirect part but I have no idea how to get the value. ? is the value i'm passing in.)
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
PurchaseService ps = new PurchaseService(em);
utx.begin();
boolean success = ps.addPurchaedetails(?);
utx.commit();
HttpSession session = request.getSession();
session.setAttribute("success", success);
response.sendRedirect("MemberAccess/AddConfirm.jsp");
}
catch (Exception ex) {
Logger.getLogger(PurchaseCheckOut.class.getName()).log(Level.SEVERE, null, ex);
}
PurchaseService for addPurchasedetails
public boolean addPurchasedetails(Purchasedetails purcD) {
mgr.persist(purcD);
return true; }
Structure of the purchase works like this : PurchaseM.jsp(let user to choose) -> PurchaseCreate.java(pass all the value to cart) -> PurchaseCart.jsp (display the value(not yet persist))-> PurchaseCheckOut.java(persist) -> AddConfirm.jsp(display "You've done")
You can store the add to cart value in a Session object and refer anywhere you need to.
I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")
From index.jsp code,
statement.executeQuery("select * from fus where tester_num like 'hf60' ") ;
Example I want "hf60" to be a variable(userinput), wherein USER must input/write data from input text then submit and get the data so that the result will be
("select * from fus where tester_num like 'userinput' ")
Where should I insert that code, Is it in InsertServlet .java or in Index.jsp.? or make another filename.java code? Please help. Thanks;)
Index.jsp
<%# page import="java.sql.*" %>
<% Class.forName("oracle.jdbc.driver.OracleDriver"); %>
<HTML>
<HEAD>
<TITLE>SHIFT REPORT </TITLE>
</HEAD>
<BODY BGCOLOR=##342D7E>
<CENTER>
<H2><FONT COLOR="#ECD672" FACE="Verdana" >SHIFT REPORT</FONT></H2></CENTER>
<hr>
<%
Connection connection=DriverManager.getConnection ("jdbc:oracle:thin:#oradev2.*****.com:1521:RPADB","shift_admin", //
"shift_admin"
);
Statement statement = connection.createStatement() ;
//**Should I input the codes here?**
ResultSet resultset =
statement.executeQuery("select * from fus where tester_num like 'hf60") ;
%>
<TABLE BORDER="1" BGCOLOR="CCFFFF" width='200%' cellspacing='1' cellpadding='0' bordercolor="black" border='1'>
<TR>
<TH bgcolor='#DAA520'> <font size='2'>RECORD NUMBER</TH>
<TH bgcolor='#DAA520'><font size='2'>TESTER NUMBER</TH>
<TH bgcolor='#DAA520'><font size='2'>DATE</TH>
<TH bgcolor='#DAA520'><font size='2'>TIME</TH>
<TH bgcolor='#DAA520'><font size='2'>SYSTEM TYPE</TH>
<TH bgcolor='#DAA520'><font size='2'>PACKAGE</TH>
<TH bgcolor='#DAA520'><font size='2'>SOCKETS</TH>
<TH bgcolor='#DAA520'><font size='2'>VALIDATED BY</TH>
</TR>
<% while(resultset.next()){ %>
<TR>
<TD> <font size='2'><center><%= resultset.getLong(1) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(2) %></center></TD>
<TD> <font size='2'><center><%= resultset.getDate(3) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(4) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(5) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(6) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(7) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(8) %></center></TD>
</TR>
<% } %>
</TABLE>
</BODY>
</HTML>
InsertServlet.java
package fusion.shift.servlets.db;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InsertServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void destroy() {
}
public boolean processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String rec_num = request.getParameter("rec_num");
String tester_num = request.getParameter("tester_num");
String t_date = request.getParameter("t_date");
String t_time = request.getParameter("t_time");
String sys_type = request.getParameter("sys_type");
String packages = request.getParameter("package");
String sockets = request.getParameter("sockets");
String sockets = request.getParameter("val");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#oradev2.*****.com:1521:RPADB","shift_admin", //
"shift_admin"
);
String sql;
sql = "INSERT INTO fusion_shiftrpt(RECORD_NUM, TESTER_NUM, T_DATE, T_TIME, SYSTEM_TYPE, PACKAGE, SOCKETS,VAL) VALUES (?,?,?,?,?,?,?,?)";
ps = con.prepareStatement(sql);
stmt = con.createStatement();
ps.setString(1, rec_num);
.0+ ps.setString(2, tester_num);
ps.setString(3, t_date);
ps.setString(4, t_time);
ps.setString(5, sys_type);
ps.setString(6, packages);
ps.setString(7, sockets);
ps.setString(8, val);
ps.executeUpdate();
} catch (SQLException e) {
throw new ServletException(e);
} catch (ClassNotFoundException e) {
throw new ServletException(e);
} finally {
try {
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
if(ps != null)
ps.close();
if(con != null)
con.close();
} catch (SQLException e) {}
}
return(true);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
//String url = request.getRequestURI();
//System.out.println(url);
}
}
If you insist on staying with this design, I would suggest that you use JSTL. This provides a set of tags for accessing data, controlling logic, and performing SQL access.
See the Sun Tutorial on the Standard Tag Library and the SQL tags. This is a much better approach than embedding scriptlets into your JSP. That said, I would recommend this approach (or scriplets) only be used for prototypes or as a very-temporary fix.
With JSTL, you could replace all of the scriptlets with something similar to:
<sql:query var="rows" >
select * from fus where tester_num like ?
<sql:param value="${param.user_input}" />
</sql:query>
<table>
<c:forEach var="row" items="${rows}">
<tr>
<td>${row.column1name}</td>
<td>${row.column2name}</td>
<td>${row.column3name}</td>
</tr>
</c:forEach>
</table>
You have access to the request in a JSP. So if your JSP were to be accessed like this:
test.jsp?q=userinput
You could get to it like this in the JSP:
request.getParameter('userinput');
You should convert your JSP code to at least use a preparedStatement when you do this:
PreparedStatement ps = connection.prepareStatement("select * from fus where tester_num like ?");
ps.setString(1, "%" + request.getParameter('userinput') + "%");
ResultSet resultSet = ps.executeQuery();
As tvanfosson said, you should remove all database access code from your view logic (JSP). You should just show the info in your JSP, let the Servlet do all the processing. I also strongly recommend you to use an OMR framework like Hibernate.