having a issues with getting the result of a query based on the drop down select, for some reason its not returning anything when trying to post it on to the jsp.
here is my what code looks like
here is my index.jsp
<form method="post" action="Test">
<h3>Get today's feed event</h3>
<p>
<select name="colour" size="1" class="selectpicker" data-style="btn-inverse">
<option value="light">Runningball</option>
<option value="amber">Enetpulse</option>
<option value="DonBest">DonBest</option>
<option value="BetRadar">Betradar</option>
</select>
</p>
<input type="submit" value="Submit" class="btn">
</form>
and here is my logic
public List<String> getColours(String colour) {
List<String> colours = new ArrayList<String>();
if(colour.equals("DonBest")){
try {
connectToCoral3();
CachedRowSet res1 = con.selectQuery(
"select id,name,event_time from nodes where syst_id=16 and event_time>=now() order by event_time");
//some debugging code
while (res1.next()) {
System.out.println("id= " + res1.getString("id") + " name= "
+ res1.getString("name"));
}
while (res1.next()) {
colours.add(res1.getString("id"));
colours.add(res1.getString("name"));
colours.add(res1.getString("event_time"));
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
e.getStackTrace();
}
}else if(colour.equals("light")){
colours.add("orange");
colours.add("pink");
}
return (colours);
}
servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
String c = request.getParameter("colour");
ColourExpert ce = new ColourExpert();
List<String> styles = ce.getColours(c);
request.setAttribute("styles",styles);
System.out.println(styles);
} catch (Exception e) {
request.setAttribute("error", "Retrieving rows failed.");
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("WEB-INF/Home/simplePage.jsp");
view.forward(request, response);
and here is my jsp,
<c:forEach items="${styles}" var="styles">
<c:out value="${styles.id}" />
<c:out value="${styles.name}" />
<c:out value="${styles.event_time}" />
</c:forEach>
<c:if test="${not empty error}">Error: ${error}</c:if>
any help would be great
Remove the first while loop in your code. Then it will work.
//Remove This
while (res1.next()) {
System.out.println("id= " + res1.getString("id") + " name= " + res1.getString("name"));
}
First to access a request variable in JSTL you need to change your code to:
<c:forEach items="${requestScope.styles}" var="styles">
<c:out value="${styles.id}" />
<c:out value="${styles.name}" />
<c:out value="${styles.event_time}" />
</c:forEach>
<c:if test="${not empty error}">Error: ${error}</c:if>
Related
I'm trying to send a variable from my JSP to my Servlet using the post method. However, the value is continually returning null. I've put in prints and another type of hidden input to check for other errors, but it's just that the inputs are null in the servlet. Why is this?
JSP: (this code is within a table)
<c:set var="counter" value="0"/>
<tbody>
<form id="myForm" action="feedingSchedules" method="post">
<c:forEach var="schedule" items="${feeding_schedules}">
<tr>
<td><c:out value="${schedule.schedule_ID}" /></td>
<td><c:out value="${schedule.feeding_time}" /></td>
<td><c:out value="${schedule.recurrence}" /></td>
<td><c:out value="${schedule.notes}" /></td>
<td><c:out value="${schedule.food}" /></td>
<td><c:out value="${schedule.animalID}" /></td>
<td><button id="myButton" class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button></td>
<c:set var="counter" value="${counter + 1}"/>
<c:out value="${counter }"/>
</tr>
</c:forEach>
<c:out value="${counter }"/>
<input type="hidden" name="hi" id="hi" value="hi"/>
<input type="hidden" name="numSchedules" id="numSchedules" value="${counter}"/>
</form>
</tbody>
</table>
<script type="text/javascript">
var form = document.getElementById("myForm");
document.getElementById("myButton").addEventListener("click", function () {
form.submit();
});
</script>
Servlet: ('test' variable is null; code crashes at 'count' declaration because parseInt can't parse a null value)
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FeedingScheduleDAO dao = DAOUtilities.getFeedingScheduleDao();
List<FeedingSchedule> schedules = dao.getAllSchedules();
//Get Parameters
System.out.println("got here");
String test = request.getParameter("hi");
System.out.println(test);
int count = Integer.parseInt(request.getParameter("numSchedules"));
for(int i = 0; i < count; i++) {
String btn = null;
btn = request.getParameter("btn" + i);
if(btn == ("val" + i)) {
System.out.println("got here");
// call delete method from DAO
try {
dao.deleteSchedule(schedules.get(i));
request.getSession().setAttribute("message", "Schedule successfully deleted");
request.getSession().setAttribute("messageClass", "alert-success");
response.sendRedirect("feedingSchedules");
} catch (Exception e) {
e.printStackTrace();
request.getSession().setAttribute("message", "There was a problem deleting the schedule at this time");
request.getSession().setAttribute("messageClass", "alert-danger");
request.getRequestDispatcher("feedingScheduleHome.jsp").forward(request, response);
}
}
}
}
You can try debugging the code by making the form method=GET. This will help you to know the values that are going to Servlet. Then you can just check the URL to see if the data is there or not. Try this if you cannot see the data in the url that means that the form submit is not working properly.
I have a drop down list in a JSP which I am reading the values from and pass it into my servlet to perform actions based on the value received.
Below is my JSP:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="getdata.do" method="post">
<div align='left' >
<div align='left' >
<label class="text-white mb-3 lead">Which report do you want to generate?</label>
<select id="reportSelection" data-style="bg-white rounded-pill px-5 py-3 shadow-sm " class="selectpicker w-100" name="reportselection">
<option>Outage</option>
<option>DataQuality</option>
<option>Latency</option>
</select>
</head>
<p id = "demo"> </p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</div>
</div>
<hr class="colorgraph">
<div class="row">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="Submit" class="btn btn-primary btn-block btn-lg register" tabindex="7"></div>
</div>
</div>
</form>
</body>
</html>
I gave the drop down list an ID: reportSelection
In my servlet class, I tried to read it as below:
#WebServlet("/getdata.do")
public class DataServlet extends HttpServlet {
String message;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("In POST Method");
getTableColumn gt = new getTableColumn();
String issue = request.getParameter("reportSelection");
System.out.println("Drop Down Message: " + issue);
try {
System.out.println("In Try");
if (issue.equals("Latency")) {
message = gt.cruise("latency");
} else if (issue.equals("DataQuality")) {
message = gt.cruise("DataQuality");
System.out.println("Data quality");
} else if (issue.equals("Outage")) {
message = gt.cruise("Outage");
}
} catch (SQLException s) {
s.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I also printed the values of it just to see I am receiving any values from it.
But once I click on submit button, I see null pointer exception as
String issue = request.getParameter("reportSelection");
is receiving NULL from JSP
Could anyone let me know what is the mistake I am doing here & how do I correct it ?
I have already coded the servlet and the dao part of the delete method.
Once i want to use the method in jsp page, it returned ERROR 500 / ERROR 404.
I am using tomcat 7,Java 7 and windows 10. Running oracle. I tried to use ajax to link the servlet delete method but it still didn't work.
// deleteStaffServelt
public class DeleteStaffServlet extends HttpServlet {
enter code here
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ids = request.getParameter("userId");
int deleteId = Integer.parseInt(ids);
StaffDao staffDao = new StaffDao();
staffDao.delete(deleteId);
response.sendRedirect("deleteStaffServlet?id=" + deleteId);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// delete method in Dao
public void delete(int id) {
try {
String sql = "delete from ZZZ_EMPLOYEES where ZE_ID = " + id;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// jsp
<body>
<form action="listServletTwo">
<table border="0" cellspacing="0">
<tr>
<td>社員No. <input name="noStart" type="text" size="8" />
~ <input name="noEnd" type="text" size="8" /> <input
type="submit" value="検索" />
</td>
<td>社員名. <input name="name" type="text" size="20" /> <input
type="submit" value="検索" />
</td>
</tr>
</table>
</br>
<%
List<Staff> list1 = (List<Staff>) session.getAttribute("list");
if (list1 != null) {
%>
<table border="1" cellspacing="0">
<tr bgcolor="pink">
<td>社員No.</td>
<td>ユーザーID</td>
<td>社員名</td>
<td>削除機能</td>
<td>更新機能</td>
</tr>
<%
for (Staff s : list1) {
%>
<tr>
<td id="<%=s.getId()%>"><%=s.getId()%></td>
<td><%=s.getNo()%></td>
<td><%=s.getName()%></td>
<td>Delete</td>
<td>名前:<input name="name" type="text" size="10" /> ユーザーID:<input
name="name" type="text" size="10" />
<input type="submit" value="Edit" name="edit" onclick="editRecord(<%=s.getId()%>);">
</td>
</tr>
<%
}
}
session.removeAttribute("list");
%>
</table>
</form>
result is HTTP Status 500 – Internal Server Error
java.lang.NumberFormatException: null
Here ,Delete,you have used id=<%=s.getId()%> i.e : you are getting value <%=s.getId()%> in parameter id but in your servlet ,you are getting parameter using request.getParameter("userId"); just change this to request.getParameter("id");.
Also, your delete query is wrong it should like below :
// delete method in Dao
public void delete(int id) {
try {
//you have to give placeholder(?) in query not the value
String sql = "delete from ZZZ_EMPLOYEES where ZE_ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I am not sure what you are doing here :
response.sendRedirect("deleteStaffServlet?id=" + deleteId);
But, I think you have already deleted required row from table ,so there is no need to do that again. So, just change that to below :
response.sendRedirect("yourjsppage");
In my jsp I have many input type number tags. When I submit them I go to my servlet who needs to read them to save the values in a database. I have tried request get attribute , get parameter, but they always return null values. I have also tried using Servlet File Upload but it returns a class cast exception saying that it can not cast MonitorRequestWrapper to RequestContext.
my jsp code:
<form method="GET" action="HomeServlet">
<c:forEach var="kat" items="${requestScope.Category}">
<h2 style="background-color:blue; color: white; width:150px;">${kat.getName()}</h2>
<c:if test='${kat.getName() == "Bike"}'>
<table>
<c:forEach var="pro" items="${requestScope.Bikes}">
<tr>
<td><label>${pro.getName()}</label></td>
<td><label>${pro.getPrice()}</label> <span>kn</span></td>
<td><label>Amount:</label></td>>
<c:set var="pr" value="proz"></c:set>
<c:set var="prp" value="${pro.getStringID()}"></c:set>
<c:set var="id" value="${pr.concat(prp)}"></c:set>
<td><input type="number" name="${id}"></td>
</tr>
</c:forEach>
</table>
</c:if>
<c:if test='${kat.getName() == "Ball"}'>
<table>
<c:forEach var="pro" items="${requestScope.Balls}">
<tr>
<td><label>${pro.getName()}</label></td>
<td><label>${pro.getPrice()}</label> <span>kn</span></td>
<td><label>Amount:</label></td>>
<c:set var="pr" value="proz"></c:set>
<c:set var="prp" value="${pro.getStringID()}"></c:set>
<c:set var="id" value="${pr.concat(prp)}"></c:set>
<td><input type="number" name="${id}"></td>
</tr>
</c:forEach>
</table>
</c:if>
</c:forEach>
<br>
<input type="submit" value="Choose">
</form>
my servlet code:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession sesija =request.getSession();
try {
r = new Repository();
bouth = r.getBouthProducts();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File rep= (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(rep);
List<FileItem> items = new ServletFileUpload(factory).parseRequest((RequestContext) request);
for (FileItem item : items) {
for (Product pro : r.GetProducts()) {
String s = "proz";
String concat = s.concat(pro.getStringID());
String name = item.getFieldName();
if(name.equals(concat)){
int i = Integer.parseInt(item.getString());
if(i > 0)
{
- doesn't matter
}
}
}
}
} catch (SQLException ex) {
response.sendError(ex.getErrorCode());
} catch (FileUploadException ex) {
Logger.getLogger(HomeServlet.class.getName()).log(Level.SEVERE, null, ex);
}
-- doesn't matter
}
I am trying to populate a page with check box selections.I am using struts in my project.So in the action class i have created the list loaded with experiment nos in it.So in My Jsp page i got back the experiment list and set it to the checkbox .But the checkboxes with unique experiment nos are not shown on the page
Generating the list from the action class
public List expList() throws FISException
{
Utilities utilities = new Utilities();
PreparedStatement sqlQueryStmt = null;
ResultSet resultSet = null;
int index = 1;
List expList = new ArrayList();
Connection conn = null;
Logger logger = Logger.getInstance();
try
{
String resource = null;
String sql = "SELECT factory_node_id,exp_id FROM s_exp where dept = ?";
sqlQueryStmt = conn.prepareStatement(sql);
sqlQueryStmt.setString(index++,dept);
resultSet = sqlQueryStmt.executeQuery();
while(resultSet.next())
{
expNo= resultSet.getString(2);
expList.add(expNo);
}
}
catch(Exception e)
{
logger.error(Logger.FLOW,"Error in getting expNo",e);
}
finally
{
DBUtils.cleanUp(sqlQueryStmt,resultSet);
DBUtils.cleanUp(conn);
}
return expList;
}
<%
List expList = new ArrayList();
expList =factory.getList("resource_list_data");
request.setAttribute("expNos ", expList );
%>
<c:forEach var="item" items="${expNos}">
<input type="checkbox" value="${item}"/>
</c:forEach>
Kindly help on how to display checkbox dynamically..
<c:set var="count" value="0" scope="page" />
<c:forEach var="item" items="${expNos}">
<input type="checkbox" name="${count + 1}" value="${item}"/>
</c:forEach>
update:
<c:set var="count" value="0" scope="page" />
<c:forEach var="item" items="${expNos}">
${item} <input type="checkbox" name="${count + 1}" value="${item}"/>
</c:forEach>