Struts2 jQuery Plugin issue with Double Select - struts2

I have a little (I hope) issue trying to use Doubleselect element from Struts2 jQuery plugin and after searching the internet I found nothing about it so I come here to get your help.
I have a jsp with two struts2 jQuery Plugin selects to get the second select (Modelo) loaded based of the item selected from the first one (Fabricante). When the jsp is loaded, the first select is loaded; but when I select an item from this first select, the value of this selected item does not arrive (is value is null) to the action so there is no way to query the values for the second select from database; consequently, second select is never loaded.
I have followed the sample from the struts2-jquery-showcase.
Some info about my app:
struts2 2.3
tiles
Spring 3.1 (I have struts2-spring integration)
Following the code snippets from some files
JSP code for the tiles layout
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<tiles:importAttribute/>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var GB_ROOT_DIR = "res/greybox/";
</script>
<script type="text/javascript" src="res/greybox/AJS.js"></script>
<script type="text/javascript" src="res/greybox/AJS_fx.js"></script>
<script type="text/javascript" src="res/greybox/gb_scripts.js"></script>
<...>
<sj:head jqueryui="true" />
</head>
<body leftmargin="0" topmargin="0" marginheight="0" marginwidth="0">
<tiles:insertAttribute name="header" />
<tiles:insertAttribute name="menu" />
<...>
<tiles:insertAttribute name="content" />
</body>
</html>
JSP code
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="display" uri="http://displaytag.sf.net"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<...>
<s:form action="nuevaReparacion2" validate="true" onsubmit="return checkSubmit();" name="formulario" method="post">
<...>
<table cellpadding="0" cellspacing="0" width="900">
<tr>
<td height="2"> Fabricante:
<s:url id="remoteurl" action="nuevaReparacionCargaModelo"/>
<sj:select
href="%{remoteurl}"
id="selectFab"
onChangeTopics="reloadModelos"
name="idFabricante"
list="listFabricantes"
listKey="id"
listValue="nombre"
emptyOption="false"
headerKey="-1"
headerValue="Seleccione un fabricante"
indicator="indicator"
/>
<img id="indicator"
src="res/images/ajax-loader.gif"
alt="cargando..."
style="display:none"
/>
</td>
<td height="2">Modelo:
<sj:select
href="%{remoteurl}"
id="selectMod"
formIds="formulario"
reloadTopics="reloadModelos"
name="idModelo"
list="listModelos"
listKey="id"
listValue="nombre"
emptyOption="false"
headerKey="-1"
headerValue="Seleccione un modelo"
indicator="indicator2"
/>
<img id="indicator2"
src="res/images/ajax-loader.gif"
alt="cargando..."
style="display:none"
/>
</td>
</tr>
</table>
<...>
web.xml
<...>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring-context.xml</param-value>
</context-param>
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/classes/tiles.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/struts/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
<...>
struts.xml
<...>
<interceptor-stack name="authenticationMinimalStack">
<interceptor-ref name="exception" />
<interceptor-ref name="servletConfig" />
<interceptor-ref name="securityInterceptor" />
<interceptor-ref name="prepare" />
<interceptor-ref name="checkbox" />
<interceptor-ref name="multiselect" />
<interceptor-ref name="chain" />
<interceptor-ref name="fileUpload">
<!-- <param name="maximumSize">50000000</param> -->
<param name="maximumSize">80000000</param>
</interceptor-ref>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="staticParams" />
<interceptor-ref name="params"/>
<interceptor-ref name="workflow" />
</interceptor-stack>
<...>
<...>
<action name="nuevaReparacionCargaModelo" method="cargaModeloFabricante" class="nuevaReparacionAction">
<interceptor-ref name="authenticationMinimalStack" />
<result name="pajax" type="json"></result>
</action>
<...>
Action class code
public class NuevaReparacionAction extends AbstractAction<NuevaReparacionForm> {
<...>
public String init() throws Exception {
if (model.getListFabricantes() == null) {
List<Fabricante> listFabricantes = referenceDataService.getAllFabricantes();
model.setListFabricantes(listFabricantes);
}
<...>
}
<...>
public String cargaModeloFabricante() throws Exception {
if(StringUtils.isNotEmpty(idFabricante)){
List<Modelo> listModelos = referenceDataService.getAllModelosPorFab(idFabricante);
model.setListModelos(listModelos);
}
String res = "pajax";
return res;
}
<...>
}
Form class code
public class NuevaReparacionForm extends AbstractActionForm {
<...>
private List<Fabricante> listFabricantes;
private String idFabricante;
private List<Modelo> listModelos;
private String idModelo;
<...>
public List<Fabricante> getListFabricantes() {
return listFabricantes;
}
public void setListFabricantes(List<Fabricante> listFabricantes) {
this.listFabricantes = listFabricantes;
}
public String getIdFabricante() {
return idFabricante;
}
public void setIdFabricante(String idFabricante) {
this.idFabricante = idFabricante;
}
public List<Modelo> getListModelos() {
return listModelos;
}
public void setListModelos(List<Modelo> listModelos) {
this.listModelos = listModelos;
}
public String getIdModelo() {
return idModelo;
}
public void setIdModelo(String idModelo) {
this.idModelo = idModelo;
}
<...>
The Fabricante bean
public class Fabricante extends AbstractObject<Long> {
private static final long serialVersionUID = -3767216824782509270L;
private boolean indRepara;
public boolean isIndRepara() {
return indRepara;
}
public void setIndRepara(boolean indRepara) {
this.indRepara = indRepara;
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null) {
return false;
}
if (!obj.getClass().equals(getClass())) {
return false;
}
Fabricante castedObj = (Fabricante) obj;
return ObjectUtils.equals(getId(), castedObj.getId());
}
#Override
public String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.append("nombre", getNombre())
.toString();
}
}
The Modelo bean
public class Modelo extends AbstractObject<Long> {
private static final long serialVersionUID = -5167217040308921281L;
private Fabricante fabricante;
public Fabricante getFabricante() {
return fabricante;
}
public void setFabricante(Fabricante fabricante) {
this.fabricante = fabricante;
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null) {
return false;
}
if (!obj.getClass().equals(getClass())) {
return false;
}
Modelo castedObj = (Modelo) obj;
return ObjectUtils.equals(getId(), castedObj.getId());
}
#Override
public String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.append("nombre", getNombre())
.toString();
}
}
The superclass for the beans
public class AbstractObject<T> {
/**
*
*/
private static final long serialVersionUID = 7717102673045778131L;
/**
* The object id
*/
private T id;
private String nombre;
/**
* Setter for attribute "id"
* #param id the object id
*
public void setId(T id) {
this.id = id;
}
/**
* Getter for attribute "id"
* #return the object id
*
public T getId() {
return id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
Thanks in advance.

Related

Set method is not called in struts2 for file input but called for other perameters

I am new to struts2. What I am trying is to get data from the client and insert into the db.But while doing this setImageFile(File fie) isnt called and thus imageFile object is null. While other set methods are called and is thus respective members contains values.
action.class
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.Map;
import javax.servlet.http.Part;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.dispatcher.SessionMap;
public class register extends ActionSupport implements SessionAware{
SessionMap<String, String> sessionMap;
private String name;
private String email;
private String dob;
private String address;
private File imageFile;
private String imageFileFileName;
private String imageFileContentType;
#Override
public void setSession(Map map)
{
sessionMap = (SessionMap)map;
sessionMap.put("", name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public File getImageFile() {
return imageFile;
}
public void setFile(File imageFile) {
this.imageFile = imageFile;
}
public void setSessionMap(SessionMap<String, String> sessionMap) {
this.sessionMap = sessionMap;
}
public String execute()
{
try
{
Class.forName("org.postgresql.Driver");
Connection conn=DriverManager.getConnection("jdbc:postgresql://localhost:5432/DemoDB", "postgres", "postgres");
InputStream imageInputStream = new FileInputStream(imageFile);
String query = "insert into userProfile('Name','Address','email','dob','img') values(?,?,?,?,?)";
Date date = Date.valueOf(dob);
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(0, name);
preparedStatement.setString(1, address);
preparedStatement.setString(2, email);
preparedStatement.setDate(3, date);
preparedStatement.setBinaryStream(4, imageInputStream, imageFile.length());
preparedStatement.execute();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return "success";
}
}
In the above code imageFile is null. And othe members contains value
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="register" namespace="/" extends="tiles-default">
<action name="register" class="com.passportseva.register">
<result name="success" type="tiles">login</result>
<result name="input" type="tiles">register</result>
<result name="error">layoutmanager.jsp</result>
</action>
</package>
</struts>
This is jsp where the action is called
registration.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="register" method="POST">
<div>
<div><h1>Name</h1></div>
<input type="text" name="name" hint="name"/>
</div>
<div>
<div><h1>Email</h1>></div>
<input type="text" name="email" hint="email"/>
</div>
<div>
<div><h1>DOB</h1></div>
<input type="date" name="dob"/>
</div>
<div>
<div><h1>Address</h1></div>
<input type="area" name="address" hint="address"/>
</div>
<div>
<s:file name="imageFile" label="image"/>
</div>
<input type="submit" value="register"/>
</form>
</body>
</html>
I used tiles here
tiles.xml
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="login" template="/layoutmanager.jsp">
<put-attribute name="title" value="Login Page"/>
<put-attribute name="body" value="/login.jsp"/>
</definition>
<definition name="register" template="/layoutmanager.jsp">
<put-attribute name="title" value="Passport seva registration"/>
<put-attribute name="body" value="/registration.jsp"/>
</definition>
</tiles-definitions>
The output says that invalid field value for imageFile.
Use Struts Form tag with enctype attribute.
<s:form action="register" method="POST" enctype="multipart/form-data">
</s:form>

how to validate HashSet size greather than zero in Struts2 if tag?

I am using Struts2 and want to check the HashSet property size is greater than zero using Struts2 if tag.
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="bundle" extends="struts-default" namespace="/">
<action name="process"
class="sample.action.Process"
method="execute">
<interceptor-ref name="defaultStack" />
<result name="success">/jsp/result.jsp</result>
</action>
</package>
</struts>
POJO
package sample.pojo;
public class Customer{
private Integer id;
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
Action Class
package sample.action;
import java.util.HashSet;
import java.util.Set;
import sample.pojo.Customer;
import com.opensymphony.xwork2.ActionSupport;
public class Process extends ActionSupport
{
private Set<Customer> result = new HashSet<Customer>();
public String execute()
{
Customer cust1 = new Customer();
cust1.setId(1);
cust1.setAge(59);
cust1.setName("Subramanian");
result.add(cust1);
return SUCCESS;
}
public Set<Customer> getResult() {
return result;
}
public void setResult(Set<Customer> result) {
this.result = result;
}
}
VIEW
<!DOCTYPE html>
<html>
<head>
<%# taglib prefix="s" uri="/struts-tags"%>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=8;" />
<title>Welcome Page</title>
</head>
<body>
<s:if test="*<syntax>*">
java.util.HashSet size is <s:property value="result.size"/>
</s:if>
<s:else>
java.util.HashSet size is empty!
</s:else>
</body>
</html>
Please help with the Struts2 if tag syntax to be used in the View. Thank you!
Below code snippet worked for me
<s:if test="%{mySet.size()>0}">

Struts2 validation is not even working

I also configured all the setting for Struts2 basic validation, but nothing is working for me.
My login.jsp file
<%#taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
<s:head />
</head>
<body>
<s:actionerror/>
<s:form action="Login" method="post">
<s:textfield name="userName" label="User Name" />
<s:password name="password" label="Password" />
<s:submit value="Login" />
<s:fielderror></s:fielderror>
</s:form>
</body>
</html>
My loginAction class is,
package com.test;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String userName;
private String password;
public LoginAction() {
}
public String execute() {
return "SUCCESS";
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
my struts2.xml file is,
<package name="default" namespace="/" extends="struts-default">
<action name="Login" class="com.test.LoginAction" method="execute">
<result name="SUCCESS">login.jsp</result>
<result name="input">login.jsp</result>
</action>
</package>
</struts>
And I place my LoginAction-validation.xml file in the same package where the Action class is placed.
Please lookout my code and help me to resolve the validation issue.
You are returning same login.jsp page in your execute method in action class.
So this results in displaying login page with empty field every time you hit enter.
Try creating an additional jsp to which you are redirected to based on String returned from action class.
other than that i dont see any problem.

How to use RequestContext in primefaces?

I'm new to primefaces. I trying some examples in primeface showcase
But;
After saveUser, on ajax method handleComplete(xhr, status, args) args don't have arguments that added in saveUser method.
EDIT : I just added #ManagedBean annotations because i'm using jsf 2.0
EDIT-2
in my pom;
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>2.2</version>
</dependency>
in my web.xml
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
in my .xhtml page
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<script type="text/javascript">
function handleComplete(xhr, status, args) {
if(args.validationFailed) {
alert("Validation Failed");
} else {
alert("Save:" + args.saved);
alert("FirstName: " + args.user.firstname + ", Lastname: " + args.user.lastname);
}
}
</script>
</h:head>
<h:body>
<h:form>
<p:panel id="panel" header="New User">
<h:panelGrid columns="2">
<h:outputLabel for="firstname" value="Firstname: *" />
<p:inputText id="firstname" value="#{user.firstName}" required="true"/>
<h:outputLabel for="surname" value="Lastname: *" />
<p:inputText id="surname" value="#{user.surName}" required="true"/>
</h:panelGrid>
</p:panel>
<p:commandButton value="Save" actionListener="#{user.saveUser}" oncomplete="handleComplete(xhr, status, args)" />
</h:form>
</h:body>
</html>
in my bean;
#ManagedBean(name = "user")
public class User {
private String firstName = "";
private String surName = "";
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurName() {
return surName;
}
public void saveUser(ActionEvent actionEvent) {
// save user
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("saved", true);
context.addCallbackParam("user", this);
}
}
EDIT -3
I can catch properties that carried with data in ajax response with this.PrimeFaces.ajax.RequestManager.requests[0].data it carries that data ;
"j_id2059540600_7ac21836=j_id2059540600_7ac21836&j_id2059540600_7ac21836%3Afirstname=qweq&j_id2059540600_7ac21836%3Asurname=asda&javax.faces.ViewState=8900392402396831372%3A-8139730777939772917&javax.faces.partial.ajax=true&javax.faces.source=j_id2059540600_7ac21836:j_id2059540600_7ac218a5&javax.faces.partial.execute=#all&j_id2059540600_7ac21836:j_id2059540600_7ac218a5=j_id2059540600_7ac21836:j_id2059540600_7ac218a5"
But i'm pretty sure there is another option. Just can't seet it.
Thanks for any help.
Solved! It was about scope problem of a form that contains a commandButton. Command buttons (i think..didnt read a formal document about it.) that in a form has a scope of its own form. Cant reach/update/modify elements in an form.

Struts 2 Drop Down Example Problem

i am trying to work on a drop down list using struts2 tag. But till now i am unsuccessful: below is the .jsp page, the action class, the struts.xml file and all relevant codes. Any help will be greatly appreciated. Thank you.
Note: I am getting this error :-> tag 'select', field 'list': The requested list key 'country' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
...........
Index.jsp :
.............
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s" %>
<h3>Struts 2: UI Tag Example - Registration Page Demo </h3><hr>
<s:form action="register">
<s:select label="Country" list="country" listKey="countryAbbr" listValue="countryName" />
<s:submit/>
</s:form>
......................
struts.xml:
......................
<package name="com.uitagdemo" extends="struts-default">
<action name="register" class="com.uitagdemo.RegisterAction" >
<result name="success">/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
...........................
RegisterAction.java
...........................
public class RegisterAction extends ActionSupport {
private List<Country> country;
public String execute() {
return SUCCESS;
}
public List<Country> getCountry(){
country = new ArrayList<Country>();
country.add(new Country("IN", "INDIA"));
country.add(new Country("US", "USA"));
country.add(new Country("FR", "FRANCE"));
return country;
}
}
.......................
success.jsp
.......................
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s" %>
Struts 2: UI Tag Example
Struts 2: UI Tag Example - Registration Page Demo
Country: <s:property value="country" /><br>
</body>
......................
Country.java
......................
public class Country {
private String countryAbbr;
private String countryName;
public Country() {
}
public Country(String countryAbbr, String countryName) {
this.countryAbbr = countryAbbr;
this.countryName = countryName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCountryAbbr() {
return countryAbbr;
}
public void setCountryAbbr(String countryAbbr) {
this.countryAbbr = countryAbbr;
}
}
In this case you are using the Country class as a Map. Simplest solution would be to make a Hashmap property called country with appropriate getter/setters and populate it with what you need.
Then in your JSP you could say something like:
<s:select label="Country" list="country.keys">
or maybe you'd rather
<s:select label="Country" list="country.values">
The workflow should be reverse than above. It should be
action that fills select tag(calls getcountry) -> page with form -> action(to which form will be submitted)
but above we have
page with form -> submitted to action that fills the select, but form has already been displayed.

Resources