JSP JSTL does not write HTML - java

I have an assignment for a one web page to show a table based on a selected date range (week, month or quarter) and a selected date. The data is from a read-only JSON file. A <select> control is filled with start dates using jQuery (not my preference but it works). Selecting a start date should cause a set of records to be chosen to be displayed in the <table> using JSTL <c:out>. I observe the correct data being requested by <c:forEach> from EventInfo#getDate() but no HTML code is written. I also failed to get JSTL to write <option> for the <select> control or even a <label>.
I am not sure what else to check to get this to work, such as pom.xml, file locations.
The java servlet and class files are in src/edjusterJsp/.
HomePage.jsp and actions.js are in WebContent/.
The data files is in WebContent/WEB-INF/.
Development is done in Eclipse/Luna on Windows Vista using Chrome to view.
HomePage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Joe Brown's Assignment for e|djuster</title>
<style>
.picklab
{
width: 10em;
}
.pickcontrol
{
width: 8em;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="actions.js"></script>
</head>
<body>
<h1>Joe Brown's Data Viewer</h1>
<c:set var="greeting" value="Hello World" />
<c:out value="${greeting}" />
<form action="JoeabServlet" method="post">
<label class="picklab">Period</label>
<select id="periodtype" class="pickcontrol pickler" required>
<option>select</option>
<option value="ptweek">Week</option>
<option value="ptmonth">Month</option>
<option value="ptquarter">Quarter</option>
</select><br>
<label class="picklab">Start Date</label>
<select id="periodrange" class="pickcontrol pickled">
<option>Please select parent</option>
</select><br>
<input type="submit" value="Update Summary" />
<table id="summaryz">
<thead>
<tr>
<th>Date</th>
<th>Type</th>
<th>Summary</th>
<th>Metric</th>
</tr>
</thead>
<tbody>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
</tr>
<c:forEach items="${eventinfos}" var="evinfo">
<tr>
<td><c:out value="${evinfo.getEventDate()}" /></td>
<td><c:out value="${evinfo.getEventType()}" /></td>
<td><c:out value="${evinfo.getEventSummary()}" /></td>
<td><c:out value="${evinfo.getEventSize()}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
</body>
</html>
JoeabServlet.java (portion)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String fillid = request.getParameter("fillid"); // ID of child DD to fill options for.
String periodsize = request.getParameter("periodsize");
String val = request.getParameter("val"); // Value of parent DD to find associated child DD options for.
System.out.println("doGet() fillid: " + fillid + " periodsize: " + periodsize + " val: " + val);
String jsonText = "invalid";
if (0 == fillid.compareTo("periodrange"))
{
// Generate date options for a period type
List<String> dates = getPeriodRanges(val);
StringWriter sw = new StringWriter();
JSONValue.writeJSONString(dates, sw);
jsonText = sw.toString();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonText);
}
else if (0 == fillid.compareTo("summaryz"))
{
// Generate summary data for the table
System.out.println("doGet() matched summaryz");
List<EventInfo> evInfos = getEventInfos(periodsize, val);
request.setAttribute("eventinfos", evInfos);
request.getRequestDispatcher("/HomePage.jsp").forward(request, response);
}
}
actions.js (portion)
function fillSummaries(tableToFillID, ddTypeId, callingElement)
{
var tableau = $("#" + tableToFillID);
var dd = $('#' + ddTypeId);
console.debug("selected: " + $(callingElement).children(':selected'));
console.debug("selected text: " + $(callingElement).children(':selected').text());
sdate = $(callingElement).children(':selected').text();
console.debug("sdate : " + sdate);
$.getJSON('http://localhost:8080/edjusterJsp/JoeabServlet?fillid=' + tableToFillID + '&periodsize=' + dd.val() + '&val=' + sdate);
}
EventInfo.java (portion)
public class EventInfo
{
protected String event_date;
protected String event_type;
protected String event_summary;
protected String event_size;
public String getEventDate()
{
System.out.println("get event_date" + event_date);
return event_date;
}
}

Related

How to save records and update the same page with recorded values in java

I'm trying to create a page that register new products and show the results list in same page.
This is my product.jsp page.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
<div>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td><c:out value="${product.name}" /></td>
<td><c:out value="${product.description}" /></td>
<td><c:out value="${product.price}" /></td>
</tr>
</c:forEach>
</div>
</table>
<br/><br/>
<form id="form1" action="${pageContext.request.contextPath}/" method="post">
<table>
<tr> <td>Product Name : <input type="text" name="pname" id="pname" /></td></tr>
<tr> <td>Product Description : <input type="text" name="pdesc" id="pdesc"/></td></tr>
<tr><td>Product Price : <input type="text" name="price" id="price"/></td></tr>
<tr><td> <input type="submit" value="save"/></td></tr>
</table>
<h4 style="color: red" id="result"><c:out value="${msg}"/></h4>
</form>
<script>
$(document).ready(function () {
$('#form1').submit(function () { .
$form = $(this);
$.post($form.attr('action'),
$form.serialize(),
function (responseText) {
$('#result').text(responseText);
$('#pname').val('');
$('#pdesc').val('');
$('#price').val('');
});
return false;
});
});
</script>
</body>
</html>
And here is my products.java servlet.
doGet() method usually calls when the page is loaded and it returns the registered item list.
doPost() method on the other hand save the records and returns the results back to the product.jsp page.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Product> products = productDAO.list();
request.setAttribute("products", products);
request.getRequestDispatcher("/products.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain products from DB", e);
}
}
#Override
protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
try {
Product p = new Product();
p.setName(requset.getParameter("pname"));
p.setDescription(requset.getParameter("pdesc"));
p.setPrice(new BigDecimal(requset.getParameter("price")));
if (productDAO.Save(p) > 0) {
response.getWriter().write(String.valueOf("sucess"));
} else {
response.getWriter().write(String.valueOf("saved fail"));
}
} catch (Exception e) {
e.printStackTrace();
response.getWriter().write(String.valueOf(e));
}
Also this is my web.xml file that indicate products.java servlet file load in the startup of the application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>products</servlet-name>
<servlet-class>com.shop.controller.products</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>products</servlet-name>
<url-pattern/>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MyDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
This web page is working finely, but the problem that I have is I want to update the given list after registration of the item.
Currently I only send a successful or error message only. I got an suggestion saying that I should use json. But to my knowledge it won't update the same given table.
Please help. Thank you.
Check out BalusC's answer here, it's a godsend. As you can see from it there are many different ways to handle your response data. Below i'll give you an example using your code.
For example, you could do something like this:
product.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
<div>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td><c:out value="${product.name}" /></td>
<td><c:out value="${product.description}" /></td>
<td><c:out value="${product.price}" /></td>
</tr>
</c:forEach>
</div>
</table>
<br/><br/>
<form id="form1" action="YourProductsServlet" method="post">
<table>
<tr> <td>Product Name : <input type="text" name="pname" id="pname" /></td></tr>
<tr> <td>Product Description : <input type="text" name="pdesc" id="pdesc"/></td></tr>
<tr><td>Product Price : <input type="text" name="price" id="price"/></td></tr>
<tr><td> <input type="submit" value="save"/></td></tr>
</table>
<div style="color: red" id="result"></div>
</form>
<script>
//ajaxifying an existing form
$(document).on("submit", "#form1", function(event) {
var $form = $(this);
$.post($form.attr("action"), $form.serialize(), function(responseJson) {
// handle response data
var $table = $("<table>").appendTo($("#result")); // Create HTML <table> element and append it to HTML DOM element with ID "result".
$.each(responseJson, function(index, product) { // Iterate over the JSON array.
$("<tr>").appendTo($table) // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
.append($("<td>").text(product.id)) // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
.append($("<td>").text(product.name)) // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
.append($("<td>").text(product.price)); // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
});
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
</body>
</html>
products.java
Note: Servlets by convention start with a capital letter. Also in your
web.xml there is no url mapping set.. So as shown in the form above
i'm going to assume it's set as "YourProductsServlet"
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//in this case we are going to use this doGet method to handle your ajax response and when you initially load your data so we need to check if it's ajax or not, we can do that with this:
boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
try {
List<Product> products = productDAO.list();
request.setAttribute("products", products);
if (ajax) {
//where the magic happens
//Returning List<Entity> as JSON
String json = new Gson().toJson(products);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}else{
//not an ajax request so process normally
request.getRequestDispatcher("/products.jsp").forward(request, response);
}
} catch (SQLException e) {
throw new ServletException("Cannot obtain products from DB", e);
}
}
#Override
protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
//your form submits your new product to here, where you will save in your database
try {
Product p = new Product();
p.setName(requset.getParameter("pname"));
p.setDescription(requset.getParameter("pdesc"));
p.setPrice(new BigDecimal(requset.getParameter("price")));
productDAO.Save(p);
//if (productDAO.Save(p) > 0) {
//response.getWriter().write(String.valueOf("sucess"));
//} else {
//response.getWriter().write(String.valueOf("saved fail"));
//}
} catch (Exception e) {
e.printStackTrace();
//response.getWriter().write(String.valueOf(e));
}
doGet(request,response); //forward request and response to doGet method
}
Let me know if that works/helps or if you have questions.
Your code is indeed working correctly and as intended.
What you need to do, is to either trigger a reload of the page on the success callback (not very user-friendly) or update your table using JavaScript to modify the DOM of the page (how most modern systems work).
Such tasks are easier to accomplish using a JavaScript framework to dynamically render and keep the page updated based on changes in the server. There are very simple and easy-to-use libraries like Backbone.js, and more advanced ones like AngularJS and React.

Re-ordering form results with Java/JSP

I'm inexperienced with Java and JSP. I created a form and it works the way it is supposed to, but I want to have some fun with it and have it reorder the results after the form is submitted. I'll include some images to show what I mean. I'm having a hard time searching for what I want and don't really know where to start. Any help will be appreciated.
Here is the form page:
Here is the results:
Here is what I want the results to look like (notice 'last' goes from 2 to 3, 'middle' from 3 to 5, 'item' from 4 to 2, and 'address' from 5 to 4):
Java File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowParameters extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
String title = "Reading All Request Parameters";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues =
request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("STOP1\n");
doGet(request, response);
}
}
JSP file
<%# 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>Lab 3</title>
<style type="text/css">
.address {
height: 50px;
}
</style>
</head>
<body>
<body BGCOLOR="#FF0000">
<h1 align="center">Basic FORM</h1>
<form action="ShowParameters" method="post">
First Name: <input type="text" name="first"> <br>
Last Name: <input type="text" name="last" value="$"> <hr/>
Middle Name: <input type="text" name="middle"> <br>
Item: <input type="text" name="item"> <br>
Address: <input type="text" name="address" class="address"> <br>
Credit Card: <br>
<input type="radio" name="cardType" value="Visa">Visa <br>
<input type="radio" name="cardType" value="MasterCard">MasterCard <br>
Credit Card Number: <input type="text" name="cardNum"> <br><br>
<center><input type="submit" value="Submit Order"></center>
</form>
</body>
</html>
instead of creating html in servlet create a class to hold form input information like:
public class Person {
private String firstName;
private String midlleName;
private String lastName;
private String item;
private String address;
private String cardType;
private String cardNumber;
//getters and setters
}
in servlet create instance of Person class and set values then simply add person instance to request and forward to jsp.
Person person = new Person();
person.setFirstName(request.getParameter("first"));
//set other person values here
request.setAttribute("person", person);
request.getRequestDispatcher("filename.jsp").forward(request, response);
in jsp display like:
<table border="2">
<tr bgcolor="#FFAD00">
<th>Parameter Name</th>
<th>Parameter Value(s)</th>
</tr>
<tr>
<td>first</td><td>${person.firstName}</td>
</tr>
<tr>
<td>item</td><td>${person.item}</td>
</tr>
<tr>
<td>last</td><td>${person.midlleName}</td>
</tr>
<tr>
<td>address</td><td>${person.address}</td>
</tr>
<tr>
<td>middle</td><td>${person.lastName}</td>
</tr>
<tr>
<td>cardType</td><td>${person.cardType}</td>
</tr>
<tr>
<td>cardNum</td><td>${person.cardNumber}</td>
</tr>
</table>
Benefits:
easy to change the order as you like in html.(simply move the <tr/> elements)
No need of loop.
Follows Object-oriented programming (OOP) style of programming.
Rather than getting an enumeration of the parameters by request.getParameterNames you could have a string array of all the parameter names you expect with them in the order you want, and you could loop through that array like so:
String[] paramNames = { "item", "last", "first" };
for(int i=0; i<paramNames.length; i++)
{
out.print("<tr>");
out.print("<td>" + paramNames[i] + "</td>");
out.print("<td>");
String[] paramValues = request.getParameterValues(paramNames[i]);
...
...
out.print("</td>");
out.print("</tr>");
}
Please take note that one of the things you are not doing in your code is properly closing the cells with </td> and the rows with </tr>. You should really also close the LIs with </li>.

Arabic value does not work in jsp servlet

I have one demo code where I have three jsp named arabic1.jsp, arabic2.jsp, arabic3.jsp and one servlet named ArabicServlet.
Inside arabic1.jsp I have one textbox where I entered arabic value and submitted the page by calling ArabicServlet servlet, which forward same content to arabic2.jsp, where I have displayed the same content inside textbox which is correctly displayed.
Now I have one link on arabic2.jsp to forward request on arabic3.jsp using same servlet and content, here on arabic3.jsp I have displayed same arabic content inside textbox but I got wrong characters.
I am entering value on first jsp as محمد , It is shown on third jsp as ÙØ­Ùد
arabic1.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
<input type="hidden" id="page" name="page" value="1"/>
</td>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic">
</td>
<td>
<input type="submit" id="arabic" name="arabic">
</td>
</tr>
</table>
</form>
</body>
</html>
arabic2.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<%
Map map = (Hashtable)request.getAttribute("arabic");
String arabicvalue = (String)map.get("arabicmap");
System.out.println("Arabic Value on jsp = "+arabicvalue);
String url = "/test/ArabicServlet?page=2&arabicvalue="+arabicvalue;
%>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic" value="<%=arabicvalue%>">
</td>
<td>
Test
</td>
</tr>
</table>
</form>
</body>
</html>
arabic3.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<%
Map map = (Hashtable)request.getAttribute("arabic");
String arabicvalue = (String)map.get("arabicmap");
System.out.println("Arabic Value on jsp = "+arabicvalue);
String url = "/test/ArabicServlet?page=2&arabicvalue="+arabicvalue;
%>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic" value="<%=arabicvalue%>">
</td>
</tr>
</table>
</form>
</body>
</html>
ArabicServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
request.setCharacterEncoding("UTF-8");
String page = request.getParameter("page");
System.out.println("Page Number = "+page);
if(page.equals("1")){
String arabic = (String)request.getParameter("arabic");
System.out.println("Arabic Value from first page = "+arabic);
Map map = new java.util.Hashtable();
map.put("arabicmap",arabic);
request.setAttribute("arabic",map);
request.getRequestDispatcher("arabic2.jsp").forward(request,response);
}else{
String arabic = (String)request.getParameter("arabicvalue");
Map map = new java.util.Hashtable();
map.put("arabicmap",arabic);
request.setAttribute("arabic",map);
System.out.println("Arabic Value from first page = "+arabic);
request.getRequestDispatcher("arabic3.jsp").forward(request,response);
}
}
I resolve similar problem by putting these lines in my code:
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

Why no files found using file uploading in Struts 2

I am using org.apache.commons.*, org.apache.commons.disk.*, org.apache.commons.fileupload.servlet.* packages for file uploading in JSP program and there was no need of Struts and it was working great, data easily worked with this, but when I added Struts 2 core libraries into my web project using MyEclipse 8.5 it is not working and have no fields found. May be the program is with upload.parseRequest.
Frankly, I am unable to understand the problem, so I share my program too
AddCategory.jsp:
<html>
<head>
<meta http-equiv="refresh" content="30">
</head>
<script type="text/javascript">
function blank() {
if (document.cate.cat.value == "Enter New Category") {
alert(" Category must not be blanked !!!");
document.cate.cat.focus();
return false;
}
else if (!document.getElementById("file1").value) {
alert("No file selected");
return false;
}
else {
return true;
}
}
</script>
<form name="cate" action="CategoryAdded.jsp" method="post" enctype="multipart/form-data" onsubmit="return blank()">
<table width="100%" border="0">
<tr>
<th colspan="2" scope="col">
<div align="center">Create New Category</div>
</th>
</tr>
<tr>
<td width="50%">
<div align="right">Enter New Category:</div>
</td>
<td width="50%">
<input name="cat" type="text" id="cat" value="Enter New Category"
onFocus="if(this.value== 'Enter New Category'){ this.value='' ; this.style.background='white';}"
onBlur="if(this.value==''){this.value='Enter New Category'; this.style.background='lightyellow'}">
</td>
</tr>
<tr>
<td width="50%">
<div align="right">Upload photo:</div>
</td>
<td width="50%"><input name="file1" type="file" id="file1"></td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Add Category">
</div>
</td>
</tr>
</table>
</form>
</html>
CategoryAdded.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%#page import="java.io.*" %>
<%# page language="java" errorPage="" %>
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.io.*" %>
<%#page import="java.util.Iterator,java.util.List" %>
<%#page import="org.apache.commons.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.*" %>
<%# page import="java.util.*" %>
<%#page import="org.apache.commons.fileupload.FileItemFactory" %>
<%#page import="org.apache.commons.fileupload.FileItem" %>
<%#page import="org.apache.commons.fileupload.FileUploadException" %>
<%#page import="p1.DBInfo" %>
<%#page import="p1.Identy" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<%
String pname = "";
Identy id = new Identy();
String cod = id.code();
boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
if (!isMultipartContent) {
System.out.println("No multipart found");
return;
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
System.out.println("No fields found");
return;
}
DBInfo obj = new DBInfo();
Connection cn = obj.getConn();
PreparedStatement ps = cn.prepareStatement("insert into category values(?,?,?)");
while (it.hasNext()) {
FileItem fileItem = it.next();
if (fileItem.getFieldName().equals("cat")) {
pname = fileItem.getString();
System.out.println("category name is " + pname);
}
boolean isFormField = fileItem.isFormField();
if (!isFormField) {
String s = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
fileItem.write(new File("D:\\Practice\\ShoppingCart\\WebRoot\\images\\" + s));
System.out.println(s);
fileItem.getOutputStream().close();
ps.setString(3, "D:\\Practice\\ShoppingCart\\WebRoot\\images\\" + s);
}
}
ps.setString(1, pname);
ps.setString(2, pname + cod);
int i = ps.executeUpdate();
if (i == 1) {
%>
<head>
<script type="text/javascript">
function myFunction() {
var r = confirm("New Category Added Successfully!!!\nIf you Want to Add more New Category then Press Ok!!!");
if (r == true) {
window.location = "AddCategory.jsp";
}
else {
window.location = "Tryy.jsp";
}
}
</script>
</head>
<body onload="myFunction()">
</body>
<%
}
cn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</html>
The best thing is to rewrite the JSPs to remove scriptlets and move business logic to the action classes.
You could also use Struts2 <s:if> and <s:else> tags to render content conditionally.
The commons-fileUpload is the default implementation for uploading files in Struts2, to use it correctly you could run an example Struts2 project like struts-2-upload-multiple-files-example.

JAVA String error in JSP

Im getting a curious error with an ArrayList, below is the code (note that this code was copied from an online servlet example, I am a JAVA novice).
the JSP:
<%#page import="p.SecondExample"%>
<%# page language="java" import="java.util.*;"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Servlet Application</TITLE>
<script language="javascript">
function editRecord(id){
window.location.href="editServlet/"+id;
}
function deleteRecord(id){
window.location.href="deleteUser/"+id;
}
</script>
</HEAD>
<BODY>
<br>
<table align="center">
</table>
<br>
<table width="600px" align="center" style="background-color:#EDF6EA;border:1px solid #000000;">
<tr><td colspan=9 align="center" height="10px"></td></tr>
<tr><td colspan=9 align="center"><!-- Add New User--></td></tr>
<tr><td colspan=9 align="center" height="10px"></td></tr>
<tr style="background-color:#7BA88B;font-weight:bold;">
<td>Sector Segment</td><td>Color</td>
</tr>
<%
String bgcolor="";
int count=0;
List viewList = new ArrayList();
Iterator viewItr;
SecondExample se = new SecondExample();
se.doPost(request, response);
if(request.getAttribute("userList")!=null && request.getAttribute("userList")!="")
{
List userList = (ArrayList)request.getAttribute("userList");
Iterator itr = userList.iterator();
System.out.println(userList);
while(itr.hasNext())
{
if(count%2==0)
{
bgcolor = "#C8E2D1";
}
else
{
bgcolor = "#EAF8EF";
}
viewList = (ArrayList)itr.next();
int id = Integer.parseInt(viewList.get(0).toString());
viewItr = viewList.iterator();
%>
<tr style="background-color:<%=bgcolor%>;">
<%
while(viewItr.hasNext())
{
%>
<td><%=viewItr.next()%></td>
<%
}
count++;
%>
<td><input type="button" name="edit" value="Edit" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRecord(<%=id%>);" ></td>
<td><input type="button" name="delete" style="background-color:#ff0000;font-weight:bold;;color:#ffffff;" value="Delete" onclick="deleteRecord(<%=id%>);"></td>
</tr>
<%
}
}
if(count==0)
{
%>
<tr><td colspan="9" align="center"> </td></tr>
<tr><td colspan="9" align="center">No Record Avaliable</td></tr>
<%
}
%>
<tr><td colspan=9 align="center" height="2px"></td></tr>
</table>
</BODY>
</HTML>
in debug, the error appears to occur with:
viewList = (ArrayList)itr.next();
int id = Integer.parseInt(viewList.get(0).toString());
viewItr = viewList.iterator();
where my error appears as:
org.apache.jasper.JasperException: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList
I'm not quite sure why or how to make next a string. Any help is greatly appreciated.
Yep, itr.next() returns a String, which cannot be cast into an ArrayList.
String value = (String) itr.next();
int id = Integer.parseInt(value);
The following few lines of code in which you're iterating over your viewArray can be removed now, too.

Categories

Resources