Here I have created dynamic dropdown list using this link, but when I select some value from available list it should be called in action class.
The dropdown list which can be seen in the image ,here the values are loaded dynamically from the database and now what I want is when I select any value from that two dropdown list that values (I mean text value) should be sent to the action class and there I will execute one JDBC select query on the basis of this two values and will display in the table shown in the image but everything should be on load.Action should be on selecting values from dropdown list not on any button click .With static values I am able to call value from dropdown list into action class with name attribute.But in this case I cannot :(
I hope I am clear now .
I have tried calling select tag using listkey,name and id but none of them worked .
Below is my JSP code:
<div>
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:form action="ActionSelect">
<s:submit value=" Click Here"/>
</s:form>
<div>
Action class for loading dynamic dropdown list :
package com.ca.actions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.ca.database.Database;
import com.ca.pojo.Event;
import java.sql.PreparedStatement;
import com.opensymphony.xwork2.ActionSupport;
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
List<Event> dataForBillsJspList;
private List state = new ArrayList();
private List status = new ArrayList();
String eventName;
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public RetrieveEvNaCoNaAction() {
// TODO Auto-generated constructor stub
}
public List<Event> getDataForBillsJspList() {
return dataForBillsJspList;
}
public void setDataForBillsJspList(List<Event> dataForBillsJspList) {
this.dataForBillsJspList = dataForBillsJspList;
}
public List getStatus() {
return status;
}
public void setStatus(List status) {
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_NAME,COMPANY_NAME,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo FROM EVENT");
ResultSet rs = ps.executeQuery();
//dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
/*dataForBillsJspList.add(new Event(rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo")));
System.out.println(rs.getString("EVENT_NAME"));*/
status.add(rs.getString("COMPANY_NAME"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
}
public List getState() {
return state;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
setState(this.state);
setStatus(this.status);
return "success";
}
public String showEventDetails(){
System.out.println("Hi.."+eventName);
return SUCCESS;
}
public void setState(List state) {
//implement the application specific logic to
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_ID,EVENT_NAME,COMPANY_NAME,CONTACT_PERSON,CONTACT_NO,EMAIL_ID,EVENT_VENUE,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME FROM EVENT");
ResultSet rs = ps.executeQuery();
dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"),rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),rs.getString("EVENT_VENUE"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo"),rs.getString("EVENT_TIME")));
//System.out.println(rs.getString("EVENT_NAME"));
state.add(rs.getString("EVENT_NAME"));
System.out.println(rs.getString("EVENT_ID"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
//Here for displaying the data on UI, we are using few hardcoded values//
}
}
After loading dynamic dropdown list now i am trying to call selected value in action class by S.O.P but it gives null pointer exception. Below is my POJO class:
package com.ca.pojo;
public class Dropdown
{
private String eventState;
private String companyState;
public Dropdown() {
// TODO Auto-generated constructor stub
}
public String getEventState() {
return eventState;
}
public void setEventState(String eventState) {
this.eventState = eventState;
}
public String getCompanyState() {
return companyState;
}
public void setCompanyState(String companyState) {
this.companyState = companyState;
}
}
and below is action class where I am trying to call that selected value by using name attribute :
package com.ca.actions;
import com.ca.pojo.Dropdown;
import com.opensymphony.xwork2.ActionSupport;
public class DropdownAction extends ActionSupport
{
Dropdown dp;
public DropdownAction() {
// TODO Auto-generated constructor stub
}
public Dropdown getDp() {
return dp;
}
public void setDp(Dropdown dp) {
this.dp = dp;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println(dp.getEventState());
return "success";
}
}
struts.xml is properly configured. Now after selecting two values I want to display data in the below table accordingly without any button click but in jsp i have created button just to see whether i am getting the selected value in action class but in actual i want it without any button click.
Well, there is a huge mess here :D
First of all, the NullPointerException is thrown because the values are not sent, and the values are not sent because they're not in the form.
You should enclose them in the form like this for them to be sent to the ActionSelect action:
<s:form action="ActionSelect">
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:submit value=" Click Here"/>
</s:form>
Solved the mistery, this doesn't solve your problem, though.
You have two main ways to contact actions from a page:
Using a standard submit (as you're doing):
you either submit a form with its content, or call a link by eventually passing parameters in the querystring. This creates a Request, that will contact an action, that will return an entire JSP, that will be loaded in place of the page you're on now.
Using AJAX:
you POST or GET to an action without changing the current page, and the action can return anything, like a JSP snippet, a JSON result, a binary result (through the Struts2 Stream result), etc...
You then can choose what to do with the returned data, for example load it inside a <div> that before was empty, or had different content.
Now your problem is that you're contacting an action that is not the one you're coming from (is not able to re-render the entire JSP you're on) and you're calling it without using AJAX, then whatever the object mapped to the "success" result is (the whole JSP, or a JSP snippet), it will be loaded in place of the JSP you're on, and it will fail.
Since you seem to be quite new to this, I suggest you start with the easy solution (without AJAX), and after being expert with it, the next time try with AJAX.
That said,
avoid putting logic in getters and setters;
avoid calling methods that are not setter as setters (setState, setStatus...);
always make your attributes private;
try giving speaking names to variables: state and status for event states and company states are really confusing; and what about "state" instead of "name" (in jsp and on DB is "name");
consider loading informations like selectbox content in a prepare() method, so they will be available also in case of errors;
you're not closing the connections (and BTW it would be better to use something more evoluted, like Spring JDBC, or better Hibernate, or even better JPA, but for now keep going with the raw queries)
The following is a refactoring of your code to make it achieve the goal. I'll use #Getter and #Setter only for syntactic sugar (they're Lombok annotations, but you keep using your getters and setters, it's just for clarity):
<head>
<script>
$(function(){
$("#event, #company").on('change',function(){
$("#myForm").submit();
});
});
</script>
</head>
<body>
<form id="myForm">
<div>
...
<s:select id="event" name="event" list="events" />
...
<s:select id="company" name="company" list="companies" />
...
</div>
</form>
<div>
...
Table - iterate **dataForBillsJspList** here
...
</div>
</body>
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
#Getter private List<Event> dataForBillsJspList = new ArrayList<Event>();
#Getter private List<String> events = new ArrayList<String>();
#Getter private List<String> companies = new ArrayList<String>();
#Getter #Setter private String event = null;
#Getter #Setter private String company = null;
#Override
public void prepare() throws Exception {
Connection con;
try {
con = new Database().Get_Connection();
// load companies
PreparedStatement ps = con.prepareStatement("SELECT DISTINCT company_name FROM event");
ResultSet rs = ps.executeQuery();
while (rs.next()) { companies.add(rs.getString("company_name")); }
// load events
ps = con.prepareStatement("SELECT DISTINCT event_name FROM event");
rs = ps.executeQuery();
while (rs.next()) { events.add(rs.getString("event_name")); }
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
}
#Override
public String execute() {
Connection con;
try {
con = new Database().Get_Connection();
// load the table. The first time the table is loaded completely
String sql = "SELECT EVENT_ID, EVENT_NAME, COMPANY_NAME, CONTACT_PERSON, CONTACT_NO, EMAIL_ID, EVENT_VENUE, " +
"date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom, date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME " +
"FROM event";
String where = "";
// if instead this action has been called from the JSP page,
// the result is filtered on event and company:
if (event!=null && company!=null) {
where = " WHERE event_name = ? AND company_name = ?";
}
// load companies
PreparedStatement ps = con.prepareStatement(sql + where);
if (where.length()>0) {
ps.setString(1,event);
ps.setString(2,company);
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),rs.getString("COMPANY_NAME"),
rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),
rs.getString("EVENT_VENUE"), rs.getString("dateAsFrom"), rs.getString("dateAsTo"),
rs.getString("EVENT_TIME")));
}
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
return SUCCESS;
}
}
It is a kickoff example, but it should work.
The next steps are:
create a POJO with id and description, show the description in the select boxes, but send the id
use header values ("please choose an event"...) and handle in action conditional WHERE (only company, only event, both)
PAGINATION
Good luck
Using Javascript/jQuery you can do this, it depends on what you want to do after reached action class.
If you want to navigate to another page use the code below.
Add onchange event as an attribute to your dropdown,
onchange="customFunction(this.value)"
create customFunction in header part,
function customFunction(selectedValue){
window.location="Action_URL?myValue="+selectedValue;
}
Or if you want to return back the same page use jQuery ajax,
$("#eventName").change(function(e){
var selectedValue = $(this).val();
$.ajax({
type : 'post',
url : 'Action_URL',
data: { myValue: selectedValue},
success : function(data) {
alert(data);
console.log(data);
}
});
});
Hope this helps.
My question is: how to give dynamic param to an url using <s:itarator> in struts2?
I have some data stored in a MySQL database, I put the data (Id and Name) in two ArrayList
package Model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class Film {
private String id;
private String titolo;
private String trama;
private int i=0;
private ArrayList<String> puntate = new ArrayList<String>();
private ArrayList<Integer> idPuntate = new ArrayList<Integer>();
protected String DRIVER = "com.mysql.jdbc.Driver";
protected String url = "jdbc:mysql://localhost/SitoWeb";
protected String user = "root";
protected String psw = "";
private Connection con;
public String execute(){
Connessione();
Query();
return "success";
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public String getTitolo(){return titolo;}
public void setTitolo(String titolo) {this.titolo=titolo;}
public String getTrama(){return trama;}
public void Connessione(){
try{
con=null;
Class.forName(DRIVER);
con = DriverManager.getConnection(url,user,psw);
}catch(Exception e){}
}
public void Query(){
try {
PreparedStatement cmd = con.prepareStatement("SELECT Film.Titolo, Film.Trama, Episodi.Nome, Episodi.idEpisodio FROM Film INNER JOIN Episodi ON Film.Id = Episodi.id_Film WHERE id = ?");
cmd.setString(1, id);
ResultSet rs = cmd.executeQuery();
while(rs.next()){
titolo = rs.getString("titolo");
trama = rs.getString("trama");
idPuntate.add(i, rs.getInt("idEpisodio"));
puntate.add(i,rs.getString("Nome"));
i++;
}
rs.close();
cmd.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<Integer> getIdPuntate() {
return idPuntate;
}
public void setIdPuntate(ArrayList<Integer> idPuntate) {
this.idPuntate = idPuntate;
}
public ArrayList<String> getPuntate() {
return puntate;
}
public void setPuntate(ArrayList<String> puntate) {
this.puntate = puntate;
}
}
Now I want to show these data in my JSP page. I tried something like this:
<s:url action="episodi" var="episodi">
<s:param name="id"></s:param> // I don't know what to put here...
</s:url>
<ol>
<s:iterator value="puntate">
<li><s:property/></li>
</s:iterator>
</ol>
I don't know what to put in <s:param name="id"></s:param> because the param is an ArrayList. I tried to put <s:iterator value="idPuntate"> but it returns 0..
There are two problems:
If you are generating an url for each element of a Collection, then you need to put the url generation inside the iteration of that Collection, otherwise you will have always the same url:
<ol>
<s:iterator value="puntate">
<s:url action="episodi" var="episodio">
<s:param name="id">something here</s:param>
</s:url>
<li><s:property/></li>
</s:iterator>
</ol>
You have not used OOP, that would suggest to create a bean named Movie (or Film), with a List<Episode>, and Episode should be another bean with for example Long id, Integer season, Integer number, and String description.
Since you've used two different lists, one for the episode description and another one for the episode id, and assuming they're aligned (it is not guaranteed, so I strongly suggest you to refactor your code the OOP way), you can access the IDs by their index basing on the episode description index, during the iteration:
<ol>
<s:iterator value="puntate" status="ctr">
<s:url action="episodi" var="episodio">
<s:param name="id">
<s:property value="idPuntate[%{#ctr.index}]"/>
</s:param>
</s:url>
<li><s:property/></li>
</s:iterator>
</ol>
P.S: Film should be a bean declared in your action, not the action itself... otherwise it is not portable... what if you need the Film class in other actions ?
I faced with such problem. I write such jstl code:
<c:forEach var="package" items="${hotel.packages}">
<c:forEach var="product_item" items="${package.items}">
//some inputs and so on
</c:forEach>
</c:forEach>
my model class look like this:
Hotel class
private java.util.Set<com.acmecorp.acmeproject.model.catalog.hotel.HotelPackage> packages;
public java.util.Set<com.acmecorp.acmeproject.model.catalog.hotel.HotelPackage> getPackages() { /* compiled code */ }
public void setPackages(java.util.Set<com.acmecorp.acmeproject.model.catalog.hotel.HotelPackage> packages) { /* compiled code */ }
HotelPackage
public java.util.Set<com.acmecorp.acmeproject.model.catalog.hotel.HotelPackageItem> getItems() { /* compiled code */ }
public void setItems(java.util.Set<com.acmecorp.acmeproject.model.catalog.hotel.HotelPackageItem> items) { /* compiled code */ }
private java.util.Set<com.acmecorp.acmeproject.model.catalog.hotel.HotelPackageItem> items;
I'm geting this message
org.apache.jasper.JasperException: /WEB-INF/view/controls/hotelPackages/hotelPackagesView.jsp (line: 165, column: 24) "${package.items}" contains invalid expression(s): javax.el.ELException: Failed to parse the expression [${package.items}]
while trying to open my jsp.
line 164 it is this line <c:forEach var="product_item" items="${package.items}">
So, may be someone know what is the problem?
I believe it is because 'package' is a reserved Java keyword. Try renaming it to basically anything else.
Here is your answer!
your class Hotel
public class Hotel {
public java.util.HashSet<HotelPackage> packages;
public java.util.HashSet<HotelPackage> getPackages() {
return packages;
}
public void setPackages(java.util.HashSet<HotelPackage> packages) {
this.packages = packages;
}
}
your class
public class HotelPackage {
public java.util.HashSet<String> items;
public java.util.HashSet<String> getItems() {
return items;
}
public void setItems(java.util.HashSet<String> items) {
this.items = items;
}
}
your jstl code
<%
HashSet items = new HashSet();
Hotel hotel = new Hotel();
HashSet hotelPackSet = new HashSet();
HotelPackage hp1 = new HotelPackage();
HashSet items1 = new HashSet();
items1.add("Buffet");
items1.add("Luxury Rooms");
hotelPackSet.add(hp1);
HotelPackage hp2 = new HotelPackage();
HashSet items2 = new HashSet();
hp2.setItems(items2);
items2.add("Swimming Pool");
items2.add("Common Rooms");
hotelPackSet.add(hp1);
hotelPackSet.add(hp2);
hotel.setPackages(hotelPackSet);
%>
<c:set property="hotel" scope="page" value="<%= hotel%>" var="hotel"/>
<c:forEach var="pack" items="${hotel.packages}">
<c:set property="packItem" scope="page" value="${pack.items}" var="pack"/>
<c:forEach var="product_item" items="${pack}">
${product_item}
</c:forEach>
</c:forEach>
So you are doing a big mistake by not setting up var in set variable.Cheers :)
I want to make a page which displays which Users of my website have the current "Role". Each users have a set of Roles, and a Role is affected to 0 ~ n users.
I'm displaying a basic list with Users's name, and a checkbox for each User. And then a submit button.
When the form is submitted, it will delete the Role from the selected Users.
Most of the time, it's working fine. But there is a problem if the DB' data changed between the page loading and the form submit.
If we are into this situation, it deletes the role from the wrong user!
I've tried different ways, and right now I'm using something like this :
import java.util.LinkedList;
import java.util.List;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.list.AbstractItem;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
public class Test extends WebPage {
private static final long serialVersionUID = 1L;
/**
* An item used to link the checkbox to the Database Object
*/
public static class Item {
private boolean selected = false;
private int num;
public Item(final int num) { this.num = num; }
public final boolean isSelected() { return selected; }
public final int getNum() { return num; }
public final void setSelected(boolean selected) { this.selected = selected; }
public final void setNum(int num) { this.num = num; }
}
public Test(final PageParameters params) {
// This list will hold items we display
final List<Item> values = new LinkedList<Item>();
// Our stateless form
final StatelessForm<Void> form = new StatelessForm<Void>("form") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit() {
// On submit, we check our items to see which ones are selected
String toDelete = "";
for (final Item it : values) {
if (it.selected) {
toDelete += it.getNum() + ", ";
}
}
System.out.println(toDelete);
}
};
add(form);
form.add(new Button("submit"));
// We retrieve our data from the Database
final List<Integer> things = getFromDatabase();
// We print them
final RepeatingView rp = new RepeatingView("li");
form.add(rp);
for (int num : things) {
final AbstractItem item = new AbstractItem(rp.newChildId());
rp.add(item);
// We create our holder
final Item it = new Item(num);
values.add(it);
item.add(new Label("name", num));
// We use the property of our holder as model
item.add(new CheckBox("checkbox", new PropertyModel<Boolean>(it, "selected")));
}
}
/**
* Simulate a fetch from the database by swapping our data at each requests
*/
public static int num = 0;
private static List<Integer> getFromDatabase() {
final List<Integer> list = new LinkedList<Integer>();
if (num++ %2 == 0) {
list.add(1);
list.add(2);
}
else {
list.add(2);
list.add(1);
}
return list;
}
}
and :
<body>
<form wicket:id="form">
<ul>
<li wicket:id="li">
<span wicket:id="name"></span>
<input type="checkbox" wicket:id="checkbox" />
</li>
</ul>
<input type="submit" valud="submit" wicket:id="submit" />
</form>
</body>
I'm simulating a changing DB by swapping values each time the page is requested.
And what happens is that if I select "1" and press submit, it says that it'll delete "2"!
I understand why, but I've no idea how to fix it.
The best way to fix it would be to have something like this:
<input type="checkbox" name="toDelete[]" value="<the_id>" />
<input type="checkbox" name="toDelete[]" value="<the_id>" />
etc.
But I've no idea how to do it with Wicket, and I can't find anything on the Internet =/
So yeah.. any examples / ideas?
i want that, when user select item in a inputText field populates with data from database.
I have a select menu list:
<h:selectOneMenu id="blah" value="#{controller.selected.id}" title="#{bundle.CreateTitle_id}" >
<f:selectItems value="#{controller.listOfId()}" />
</h:selectOneMenu>
and let's say have input text like this:
<h:inputText value="In here we place value from backing bean"></h:inputText>
How can i make after selecting an item from a list(which holds the id) populate text field with other data from my backing bean(let's say a name).
Here is my backingBean:
#ManagedBean(name = "controller")
#SessionScoped
public class Bean implements Serializable {
private Catalog current;// here i'm holding int id, String name and other stuff...
private DataModel items = null;
#EJB
private probaSession.CatalogFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public KatalogController() {
}
public Katalog getSelected() {
if (current == null) {
current = new Catalog();
selectedItemIndex = -1;
}
return current;
}
private KatalogFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
//......
public ArrayList<Catalog> listOfId() {
ArrayList<Catalog> list=new ArrayList<Catalog>();
try{
String upit="select id from Catalog";
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery(upit);
while(rs.next()) {
Katalog k=new Katalog();
k.setId(rs.getInt(1));
k.setName(rs.getString(2));
list.add(k);
}
disconnect();
}
catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
and that's pretty much it.
I'm here if anything needs to explaining. It think it is easy(using ajax let's say) but i don't even know how to start doing it...
You must add an f:ajax (that is standard, many component library offer extended versions) to catch a change event in the inputText
<h:selectOneMenu id="blah" value="#{controller.selected.id}" title="#{bundle.CreateTitle_id}" >
<f:selectItems value="#{controller.listOfId()}" />
<f:ajax
event="change" <-- The event to capture. I believe that if not specified
there is a default event to capture from
each component (for inputText it would be "change")
render="myForm:foo" <-- Only repaint "blah"
listener="#{controller.myBlahListener}"
</h:selectOneMenu>
<h:inputText id="foo" value="#{controller.fooText}"/>
Your listener will read the new value in this.getSelected().getId(), and change the model so that controller.getFooText() returns the new value (the easiest way probably is this.setFooTest(this.getSelected().getId(), but that depends of your model.