Populate dropdown based on another dropdown selection - java

I have two dropdown fields in a JSP page and I have type4 connection with oracle 10g. I want that based on one dropdown selection I want that second dropdown should get filled by fetching data from database based on data in first dropdown automatically just like refreshing that JSP page or showing an alert something like "please wait". How can I do it in JSP-Servlet?
<select name="dropdown1">
<option value="<%out.println(name);%>"><%out.println(name);%></option>
</select>
My objective is: This below dropdown should get filled base don above selection:
<select name="dropdown2">
<option value="<%out.println(rollno);%>"><%out.println(rollno);%></option>
</select>
I have found one solution :
<body onload="setModels()">
<% // You would get your map some other way.
Map<String,List<String>> map = new TreeMap<String,List<String>>();
Connection con=null;
String vehtypeout="";
String vehtypeout1="";
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("");
PreparedStatement ps=null;
ResultSet rs=null;
ps=con.prepareStatement("select c1.name, c2.roll from combo1 c1 left join combo2 c2 on c1.name=c2.name order by name");
rs=ps.executeQuery();
while(rs.next()){
vehtypeout=rs.getString(1);
vehtypeout1=rs.getString(2);
map.put(vehtypeout, Arrays.asList((vehtypeout1)));// here i want to show multiple value of vehtypeout1 from database but only one value is coming from databse, how can i fetch multiple value?
map.put("mercedes", Arrays.asList(new String[]{"foo", "bar"}));
}
rs.close();
ps.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
<%! // You may wish to put this in a class
public String modelsToJavascriptList(Collection<String> items) {
StringBuilder builder = new StringBuilder();
builder.append('[');
boolean first = true;
for (String item : items) {
if (!first) {
builder.append(',');
} else {
first = false;
}
builder.append('\'').append(item).append('\'');
}
builder.append(']');
return builder.toString();
}
public String mfMapToString(Map<String,List<String>> mfmap) {
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean first = true;
for (String mf : mfmap.keySet()) {
if (!first) {
builder.append(',');
} else {
first = false;
}
builder.append('\'').append(mf).append('\'');
builder.append(" : ");
builder.append( modelsToJavascriptList(mfmap.get(mf)) );
}
builder.append("};");
return builder.toString();
}
%>
<script>
var modelsPerManufacturer =<%= mfMapToString(map) %>
function setSelectOptionsForModels(modelArray) {
var selectBox = document.myForm.models;
for (i = selectBox.length - 1; i>= 0; i--) {
// Bottom-up for less flicker
selectBox.remove(i);
}
for (i = 0; i< modelArray.length; i++) {
var text = modelArray[i];
var opt = new Option(text,text, false, false);
selectBox.add(opt);
}
}
function setModels() {
var index = document.myForm.manufacturer.selectedIndex;
if (index == -1) {
return;
}
var manufacturerOption = document.myForm.manufacturer.options[index];
if (!manufacturerOption) {
// Strange, the form does not have an option with given index.
return;
}
manufacturer = manufacturerOption.value;
var modelsForManufacturer = modelsPerManufacturer[manufacturer];
if (!modelsForManufacturer) {
// This modelsForManufacturer is not in the modelsPerManufacturer map
return; // or alert
}
setSelectOptionsForModels(modelsForManufacturer);
}
function modelSelected() {
var index = document.myForm.models.selectedIndex;
if (index == -1) {
return;
}
// alert("You selected " + document.myForm.models.options[index].value);
}
</script>
<form name="myForm">
<select onchange="setModels()" id="manufacturer">
<% boolean first = true;
for (String mf : map.keySet()) { %>
<option value="<%= mf %>" <%= first ? "SELECTED" : "" %>><%= mf %></option>
<% first = false;
} %>
</select>
<select onChange="modelSelected()" id="models">
<!-- Filled dynamically by setModels -->
</select>
But i am getting only one value in vehtypeout1 where databse contains multiple values. How can i do it?

Using jquery, bind a function to the onchange event of "combobox1" select box.
In that function, send an ajax request (you can use jquery get function) to a jsp page in your server.
In that jsp page, retrieve the relevant data from database and send the response back to the client with those data (may be you need to use JSON format).
In the jquery get function, you can add a callback function to execute after server send you back the response.
Inside that call back function, write the code to fill "combobox2" using response data sent by the server.

You'll want an ajax call like below. Have your function that is called return a html-string of
"<option value='myVal'>myText</option>".
The jQuery/Ajax would be:
$("#ddl1").change(function() {
$.ajax({
url: "URLyouwanttoaddress",
data: "myselection=" + $("#ddl1").val();
type:"get",
success: function(data) {
$("#ddl2").html(data);
}
});
});

Related

How not to include special characters & numeric in Jquery TagIt

How can i show the special characters(~!##...etc) and numeric number(0-9) not in tag when user key in the value from the input tag? Is it possible to restrict special characters and numeric display in normal text? Any help would be appreciated.
Current output :
<%
ArrayList alTag = new ArrayList();
Vector vTag = new Vector();
String SQL = "SELECT CODE, DESCP FROM TB_FRUIT WITH UR";
TEST.makeConnection();
TEST.executeQuery(SQL);
while(TEST.getNextQuery())
{
Vector vRow = new Vector();
ArrayList alInner = new ArrayList();
String field =TEST.getColumnString("CODE");
String descp =TEST.getColumnString("DESCP");
alInner.add(field);
alInner.add(descp);
alTag.add(alInner);
vTag.addElement(field);
}
TEST.takeDown();
%>
<script>
var dbArray = [<%
String dbCode = "";
String dbList = "";
for(int i=0;i<vTag.size();i++)
{
dbCode = (String) vTag.elementAt(i);
dbList += "\"" + dbCode + "\",";
}
out.print(dbList); %>
];
$(document).ready(function() {
$("#myTags").tagit({
availableTags: dbArray
});
});
</script>
<html>
<body>
<input type="text" id="myTags" name="TYPE">
</body>
</html>
This restricts the input only to alphabets
$('#myTags').keypress(function (event) {
var regex = new RegExp("^[a-zA-Z]+$");
var str = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(str)) {
e.preventDefault();
return false;
}
});
If you are open to introducing a jquery plugin, the easiset way is to include the [alphanum jquery plugin] and then do
$('#myTags').alpha();
[alphanum jquery plugin] : https://github.com/KevinSheedy/jquery.alphanum
UPDATED :
You could extent the jquery tagit plugin and override the cleaned input method as shown below so as to replace non alphabets .
$.widget( "ui.tagit", $.ui.tagit, {
_cleanedInput: function() {
var cleanedInput = this.tagInput.val().replace(/[^a-zA-Z0-9\s]+/,"");
return $.trim(cleanedInput.replace(/^"(.*)"$/, '$1'));
}
});

Selectable Table in JSP, JavaScript

I'm creating a betting site using JSP and Servlets.
I need to create a selectable table of betting coefficients.
It looks like:
The scenario is:
User presses on the coefficients and makes a bet that can consist of different matches. I need to make the cells with coefficients selectable and allow only one selection in a row. Then i should get all the coefficients that were selected and put them into the request and do some stuff with them in my servlet.
Can I do this using JSP, Servlets and HTML ? Or I need some javascript code?
I know almost nothing about javascript, so some links or small code listings would help me a lot.
Thanks in advance
There are two things you must do: 1. Set your table id as table 2.
On each row declare onclick = 'choose(n);', where n the order of
rows beginning from 1; If you know JSP hope you know how make n
increment by each row;
And pay Attention I am setting trLength by subtracting 1 from rows.length, only when there is header on table. So there must be header anyway, otherwise code won't work
<!DOCTYPE html>
<html>
<body onkeydown="chooseNext(event);">
<table id="table">
<th>name</th>
<th>lastname</th>
<th>score</th>
<tr onclick="choose(1);">
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr onclick="choose(2);">
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr onclick="choose(3);">
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<script>
/**
*
*
*
* #author Abdullaev Omonullo, 2015
*/
var IC = 1;
function setRow(value) {
IC = value;
}
function getRow() {
return IC;
}
/**** Initialization ****/
var rows = document.getElementById('table').getElementsByTagName('tr');
var trLength = rows.length - 1;
try {
highlightAll();
} catch (error) {
alert('error on getting table: ' + error);
}
choose(getRow());
function highlightAll() {
var i = 1;
for (; i <= trLength; i++) {
highlightByIndex(i);
}
}
/****END Initilization END****/
function chooseNext(event) {
if (event.keyCode == 38) {
goUp();
} else if (event.keyCode == 40) {
goDown();
}
}
function goUp() {
if (IC != 1) {
choose(IC - 1);
}
}
function goDown() {
if (IC != trLength) {
choose(IC + 1);
}
}
function highlight(rowIndex) {
var row = rows[rowIndex];
var oldRow = rows[rowIndex];
highlightByIndex(parseInt(IC));
row.style.backgroundColor = "aqua";
IC = rowIndex;
}
function highlightByIndex(i) {
var row = rows[i];
var colors = [ '#C9EAFF', '#E8F6FF' ];
row.style.backgroundColor = colors[i % 2];
}
function choose(rowIndex) {
highlight(rowIndex);
}
</script>
you need to use javascript, try datatables it has the ability to do what you need.
http://www.datatables.net/examples/server_side/select_rows.html

Storing MySQL query results in an ArrayList using Java

The following java code takes in a POST request from a JSP file and passes back the out ArrayList as output. The problem I'm having is figuring out how to read the output into the Arraylist properly, so they I can grab each element from the Arraylist and display it in my JSP.
How can I read in the column names as the first array of strings, and then each row of data as the following arrays of strings, so that I have one giant array list that contains the entire results of the query in an organized manner, and will allow me to read the results onto my JSP page?
EDIT:
So the only problem I'm having now is that when executing a command like SELECT * FROM table; it only shows the column names. But when I execute a command like SELECT columnName FROM table; it displays the column perfectly. The code below has been updated to reflect where I am at now.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
#SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<String[]> out = new ArrayList<String[]>();
ArrayList<String> columns = new ArrayList<String>();
String query = request.getParameter("query");
if (query.toString().toLowerCase().contains("select")) {
//SELECT Queries
//try {
ResultSet resultSet = statement.executeQuery(query.toString());
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
columns.add(metaData.getColumnName(i));
}
while (resultSet.next()){
String[] row = new String[numberOfColumns];
for (int i = 0; i < numberOfColumns; i++){
row[i] = (String) resultSet.getObject(i+1);
}
out.add(row);
}
//}
//catch (Exception f) {
//f.printStackTrace();
//}
}
else if (query.toString().toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
//try {
conn.prepareStatement(query.toString()).executeUpdate(query.toString());
columns.add("\t\t Database has been updated!");
//}
//catch (Exception l){
//l.printStackTrace();
//}
}
else {
//Not a valid response
columns.add("\t\t Not a valid command or query!");
}
request.setAttribute("query", query);
request.setAttribute("resultSize", out.size());
request.setAttribute("queryResults", out);
request.setAttribute("queryColumns", columns);
RequestDispatcher dispatcher = request.getRequestDispatcher("/dbServlet.jsp");
dispatcher.forward(request, response);
}
}
Here is my .JSP file, and right now it is only printing [] with nothing in it when I execute a command. I know that commands are working because of previous tests, but the array is not displaying properly.
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<%# page import="java.util.ArrayList" %>
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>This is the MySQL Servlet</h1>
<form action = "/database/database" method = "post">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<textarea name = "query" cols="20" rows="5"></textarea>
<input type = "submit" value = "Run MySQL Servlet" />
<input type = "reset" value = "Clear Command" />
</label>
</p>
</form>
<hr>
<TABLE id="results">
<%
ArrayList<String> columns = (ArrayList<String>)request.getAttribute("queryColumns");
ArrayList<String[]> results = (ArrayList<String[]>)request.getAttribute("queryResults");
out.println("<TR>");
if(columns != null && !columns.isEmpty()){
for(String columnName: columns ){
out.println("<TD>"+columnName+"</TD>");
}
}
out.println("</TR>");
//print data
if(results != null && !results.isEmpty()){
for(String[] rowData: results){
out.println("<TR>");
for(String data: rowData){
out.println("<TD>"+data+"</TD>");
}
out.println("</TR>");
}
}
%>
</TABLE>
<%= request.getAttribute("query") %>
<%= request.getAttribute("resultSize") %>
</body>
</html>
Define one list for columns as well.
ArrayList<String[]> results= new ArrayList<String[]>();
ArrayList<String> columns= new ArrayList<String>();
Populate the list of columns as:
for(int i = 1; i<= numberOfColumns; i++){
columns.add(metaData.getColumnName(i));
}
Populate the list of with results row as:
while (resultSet.next()){
String[] row = new String[numberOfColumns];
for (int i = 1; i <= numberOfColumns; i++){
row[i] = (String) resultSet.getObject(i);
}
results.add(row);
}
in the end:
request.setAttribute("queryResults", results);
request.setAttribute("queryColumns", columns);
First of all, why are you adding a toString call on a String type variable?
Now, as for your issue, I would rather create a Class, for the tables in database, with the columns as attributes. And for each row, create an instance of that class from the columns, and add it to the ArrayList.
So, your ArrayList declaration might be like this: -
List<TargetTable> records = new ArrayList<TargetTable>();
And then: -
while (res.next()) {
records.add(new TargetTable(res.getString(1), res.getString(2), ...));
}
I hope you know the number of columns in your table.
ArrayList is not the best data structure for this purpose.
You can use
Table<Integer, String, Object>
which is available in google guava library. It is really easy to use as well
U can have two arraylists as,
ArrayList<String> columnNames = new ArrayList<String>();
ArrayList<String> out = new ArrayList<String>();
Iterate through ResultSetMetadata and add the columns to the columnNames ArrayList.
Then add the columnNames to out :
out.add(columNames);
Then Create a VO class with all the column names in the table you are accessing. create all the getters and setters for the class names.
Then iterate through the Resultset,
set all the values from the result set into that VO class.
add this VO class to the out arrayList.
ResultVO vo ;
while (resultSet.next()){
vo = new ResultVO();
vo.setColumnName1(resultSet.getString(1));
vo.setColumnName2(resultSet.getString(2));
out.add(vo);
}

cascading dropdown with Multiselect using Ajax and JSP

I am sending multiselect dropdown values to a JSP PAGE. Below is the AJAX code that send the multiselect values. The JSP PAge includes SQL query to read from database and show its values in another dropdown. Below code only display cascading dropdown values based on on select and not multiselect. It appears that only one value is sent to apps.jsp and not all values. I tried few changes and it didn't work. Below is the best working code available with me. Any help to get second dropdown display values based on multiselect from first dropdown? Single dropdown works fine with below code. Thank you.
<select multiple="multiple" name="RequirementFor" id="RequirementFor" onchange="showState(this.value);">
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
<div id="plat"><select name="Platform" id="Platform" multiple="multiple" onchange='showState2(this.value)'>
</select></div>
//AJAX Code
var xmlHttp ;
var xmlHttp;
function showState(str){
if (typeof XMLHttpRequest != "undefined"){
xmlHttp= new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp==null){
alert("Browser does not support XMLHTTP Request");
return;
}
var url="apps.jsp";
url +="?value=" +str;
xmlHttp.onreadystatechange = stateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function stateChange(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("plat").innerHTML=xmlHttp.responseText ;
}
}
below is code from JSP query(apps.jsp) page.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost", "username", "password");
Statement stmt;
ResultSet rs;
String[] funID= request.getParameterValues("value");
String conCat = "";
try{
if(funID.length>0)
{
for(int i=0;i<funID.length; i++)
{
conCat = funID[i] +" "+ "OR" + " "+ "FU_DEPARTMENT_ID= " + conCat;
}
conCat = conCat.substring(0, conCat.length() - 22);
}
}
catch(Exception e)
{out.println(e);}
String buffer="<select name='state' multiple='multiple'><option value='-1'>Select</option>";
try
{
String sqlSelect1="Select FU_ID, FU_NAME from UNIT where FU_DEPARTMENT_ID ="+conCat+" ORDER BY FU_NAME ASC";
stmt = con.createStatement();
rs = stmt.executeQuery(sqlSelect1);
while(rs.next()){
buffer=buffer+"<option value='"+rs.getString("FU_ID")+"'>"+rs.getString("FU_NAME")+"</option>";
}
buffer=buffer+"</select>";
response.getWriter().println(buffer);
stmt.close();
rs.close();
con.close();
}
catch(Exception e){
System.out.println(e);
}
I think you should change the way you get multi-values. Some thing likes this:
<select multiple="multiple" name="RequirementFor" id="RequirementFor" onchange='getMultiple(this);'>
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
<script>
var selected;
function getMultiple(ob) {
selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[ i ].selected) {
selected.push(ob.options[ i ].value);
}
}
var str = "";
for (var i = 0; i < selected.length; i++) {
str += "&value=" + selected[i];
}
console.log(str);
// --> your ajax code
}
</script>

json ajax problem

I am sorry to ask this but i've been working on this for hours and I can't figure it out on my own.
I have to use json for part of a project and I was able to get it to work but now it's not returning it back to the right jsp but instead just displaying the json jsp. I am pretty sure it is how I am receiving the json.
here are screen shots of what is happening:
this is the jsp that I need to use ajax on, I am wanting to populate the second dropdown using ajax:
this is what is happening instead, (it's the right data):
here is the code(sorry it's long):
-the jsp I am doing ajax on
<script type="text/javascript">
/**
* Utility function to create the Ajax request object in a cross-browser way.
* The cool thing about this function is you can send the parameters in a two-dimensional
* array. It also lets you send the name of the function to call when the response
* comes back.
*
* This is a generalized function you can copy directly into your code. *
*/
function doAjax(responseFunc, url, parameters) {
// create the AJAX object
var xmlHttp = undefined;
if (window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
} catch (othermicrosoft){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {}
}
}
if (xmlHttp == undefined && window.XMLHttpRequest) {
// If IE7+, Mozilla, Safari, etc: Use native object
xmlHttp = new XMLHttpRequest();
}
if (xmlHttp != undefined) {
// open the connections
xmlHttp.open("POST", url, true);
// callback handler
xmlHttp.onreadystatechange = function() {
// test if the response is finished coming down
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// create a JS object out of the response text
var obj = eval("(" + xmlHttp.responseText + ")");
// call the response function
responseFunc(obj);
}
}
// create the parameter string
// iterate the parameters array
var parameterString = "";
for (var i = 0; i < parameters.length; i++) {
parameterString += (i > 0 ? "&" : "") + parameters[i][0] + "=" + encodeURI(parameters[i][1]);
}
// set the necessary request headers
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameterString.length);
xmlHttp.setRequestHeader("Connection", "close");
// send the parameters
xmlHttp.send(parameterString);
}
}//doAjax
/**
* Submits the guess to the server. This is the event code, very much
* like an actionPerformed in Java.
*/
function getSeats() {
// this is how you get a reference to any part of the page
var packInput = document.getElementById("pack");
var pack = packInput.value;
// while (packInput.childNodes.length > 0) { // clear it out
// aSeats.removeChild(aSeats.childNodes[0]);
// }
// an example of how to do an alert (use these for debugging)
// I've just got this here so that we know the event was triggered
//alert("You guessed " + seat);
// send to the server (this is relative to our current page)
// THIS IS THE EXAMPLE OF HOW TO CALL AJAX
doAjax(receiveAnswer, "ttp.actions.Sale3PackAction.action",
[["pack", pack]]);
// change the history div color, just 'cause we can
// var randhex = (Math.round(0xFFFFFF * Math.random()).toString(16) + "000000").replace(/([a-f0-9]{6}).+/, "#$1").toUpperCase();
// document.getElementById("history").style.background = randhex;
}
/**
* Receives the response from the server. Our doAjax() function above
* turns the response text into a Javascript object, which it sends as the
* single parameter to this method.
*/
function receiveAnswer(response) {
// show the response pack. For this one, I'll use the innerHTML property,
// which simply replaces all HTML under a tag. This is the lazy way to do
// it, and I personally don't use it. But it's really popular and you are
// welcome to use it. Just know your shame if you do it...
var messageDiv = document.getElementById("aSeats");
messageDiv.innerHTML = response.aSeats;
// replace our history by modifying the dom -- this is the right way
// for simplicity, I'm just erasing the list and then repopulating it
var aSeats = document.getElementById("aSeats");
while (aSeats.childNodes.length > 0) { // clear it out
aSeats.removeChild(aSeats.childNodes[0]);
}
for (var i = 0; i < response.history.length; i++) { // add the items back in
var option = aSeats.appendChild(document.createElement("option"));
option.appendChild(document.createTextNode(response.history[i]));
}
// reset the input box
//document.getElementById("pack").value = "";
}
</script>
<% Venue v = (Venue)session.getAttribute("currentVenue"); %>
<% List<Conceptual_Package> cpList = Conceptual_PackageDAO.getInstance().getByVenue(v.getId()); %>
What Packages do you want to see?
<form method="post" action="ttp.actions.Sale3PackAction.action">
<select name="packid" id="pack">
<% for (Conceptual_Package cp: cpList) { %>
<option value="<%=cp.getId()%>"><%=cp.getName1()%></option>
<% } %>
</select>
<input type="submit" value=" next " onclick="getSeats();"/>
</form>
<!--new-->
Available Seats:
<select name="eventSeatid" id="aSeats">
<option value="aSeats"></option>
</select>
<input type="button" value=" Add "/>
Selected Seats:
<form method="post" action="ttp.actions.sale4Action.action">
<select name="eventSeat2id" size="10" id="seat2">
<option value="seat2"></option>
</select>
</form>
<jsp:include page="/footer.jsp"/>
-the json jsp
<%#page contentType="text/plain" pageEncoding="UTF-8"%>
<jsp:directive.page import="java.util.*"/>
{
"history": [
<% for (String newSeats: (List<String>)session.getAttribute("newSeats")) { %>
"<%=newSeats%>",
<% } %>
]
}
-the action class
public class Sale3PackAction implements Action{
public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String packid = request.getParameter("packid");
System.out.println("packid is: " + packid);
Conceptual_Package cp = Conceptual_PackageDAO.getInstance().read(packid);
request.setAttribute("cp", cp);
List<Physical_Package> ppList = Physical_PackageDAO.getInstance().getByConceptual_Package(cp.getId());
request.setAttribute("currentPack", ppList);
session.setAttribute("aSeats", null);
//return "sale3Pack_ajax.jsp";
//new
//HttpSession session = request.getSession();
// ensure we have a history
for (Physical_Package pPack: ppList){
try {
if (session.getAttribute("aSeats") == null) {
LinkedList aSeatsList = new LinkedList<String>();
session.setAttribute("aSeats", aSeatsList);
aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());
session.setAttribute("newSeats", aSeatsList);
} else {
LinkedList aSeatsList = (LinkedList) session.getAttribute("aSeats");
aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());
session.setAttribute("newSeats", aSeatsList);
}
} catch (DataException ex) {
Logger.getLogger(Sale3PackAction.class.getName()).log(Level.SEVERE, null, ex);
}
}
// next jsp page to go to
return "AjaxPack_json.jsp";
}
}
Hehe, I think we've all been in your place. Spending hours on something just to eventually realize that we overlooked some simple detail.
Read comments for more information...

Categories