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
}
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 try to send a parameter applicationNo wrapped inside my form tag.The data inside input generated via javascript snippet. I need to pass this data to my controller, but it always throw null pointer exception, I am not able to figure it out what is the problem.
So kindly suggest me the best way to achieve. I also attached required source code and snapshot.
I want to send the data highlighted in red area in below screenshot.
JSP CODE:
<form action="${baseURL}view_grp_conn_applications" id="grpCreationForm" method="post" commandName="command" >
<div class="col-sm-12">
<table id="addAppTable" class="table table-responsive table-bordered table-striped text-center" id="newField">
<thead>
<tr>
<th>#</th>
<th>Application No.</th>
<th>Name</th>
<th>Mobile No.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<c:set var="i" value="0"></c:set>
<tr>
<td valign="center"><input name="workOrderPostSps[${i}]" id="workOrderPostSps[${i}]" type="checkbox" value="${wo.woPostIdEnc}" onclick="highlightrow(this);" /></td>
<td align="center"><b><input onkeypress="show_list('${i}');" id="appNo1${i}" name="applicationNo" class="form-control start" autocomplete="off" data-validate="required" required="true" placeholder="press key on keyboard"/></b></td>
<td align="left"><span id="appName1${i}"></span></td>
<td align="left"><span id="appContact${i}"></span></td>
<td align="left"><span id="email1${i}"></span></td>
</tbody>
</table>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-turquoise pull-right no-margin " name="saveBtn" id="saveBtn" value="Next >>" onclick="myfunction()">
</div>
</form>
JAVA CODE:
This method open the JSP from where I wish to send the applicationNo
#RequestMapping(value = "/create_group_connection")
public ModelAndView createConnection(Model model) {
ModelAndView mav = new ModelAndView("user/create_group_connection");
Application application = new Application();
mav.addObject("command", application);
return mav;
}
This method will open the jsp where i need to extract that applicationNo
#RequestMapping(value = "/view_grp_conn_applications", method = RequestMethod.POST)
public ModelAndView viewApplications(#ModelAttribute("command")Application application,HttpServletRequest request, HttpSession session) {
ModelAndView mav = new ModelAndView("user/grp_conn_applications");
try {
System.out.println("inside view group applications");
String[] applicationNo = request.getParameterValues("applicationNo");
System.out.println("inside " + applicationNo[0]);
// for (int i = 0; application.length > 0; i++) {
// System.out.println("application number is" + application[i]);
// }
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
return mav;
}
<td><b><input onkeypress="show_list('${i}');" id="appNo1${i}" name="applicationNo" class="form-control start" autocomplete="off" data-validate="required" required="true" placeholder="press key on keyboard"/></b></td>
you just use the below instead of above
<input type='hidden' id="applicationNo" name="applicationNo" /></b></td>
you just set the application number using Javascript through id of hidden field on any event like onBlur, onKeyPress,Your Controller code is Correct
I have a HTML form
<form method="post" accept-charset="UTF-8"
action="<%=blobstoreService.createUploadUrl("/nonameyet")%>"
enctype="multipart/form-data">
<tr>
<td><input type="text" name=name /></td>
<td><input type="text" name=price /></td>
<td><input type="text" name=quantity /></td>
<td><input type="file" name="image" /></td>
<td><input type="submit" value="add" /></td>
</tr>
after sending the data I receive it here:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> blobKeys = blobs.get("image");
if (blobKeys.get(0) == null) {
resp.sendRedirect("/");
}
req.setCharacterEncoding("UTF-8");
BlobKey blobKey = blobKeys.get(0);
Product product = new Product();
String name = req.getParameter("name");
String priceAsString = req.getParameter("price");
int price = Integer.parseInt(priceAsString);
String quantityAsString = req.getParameter("quantity");
int quantity = Integer.parseInt(quantityAsString);
product.setName(name);
product.setPrice(price);
product.setQuantity(quantity);
String url = ImagesServiceFactory.getImagesService().getServingUrl(ServingUrlOptions.Builder.withBlobKey(blobKey));
product.setImage(url);
ofy().save().entities(product).now();
resp.sendRedirect("/index.jsp");
}
and now the JSP is:
<%
List<Product> list = ofy().load().type(Product.class).limit(20)
.list();
for (Product product : list) {
%>
<tr>
<td><%=product.getName()%></td>
<td><%=product.getPrice()%></td>
<td><%=product.getQuantity()%></td>
<td><img alt="<%=product.getName()%>"
src="<%=product.getImage()%>" width="100" height="100" /></td>
<td>delete
</tr>
<%
}
%>
But when I view the page in Chrome it looks like this:
After examining the data in http://localhost:8888/_ah/admin/datastore, I can see the word in Hebrew is correct:
So I get to the conclusion that somewhere on the way from the datastore to the jsp the text gets garbled. Can someone help?
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")
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>