2013-05-08 3 views
0

У меня есть переключатель в форме в приложении Struts2. Я могу проверять поля текстовых полей, но я не могу сделать это для переключателя (нужно проверить) и для checkboxlist (по крайней мере один должен быть проверен).Как проверить радиокнопки в Struts2

Я следил за некоторыми страницами, рассказывающими о теме, но ни одно из решений не работает.

Наконец у меня есть это в файле XML:

<field name="sexo"> 
    <field-validator type="requiredstring"> 
     <param name="trim">true</param> 
     <message>*</message> 
    </field-validator> 
</field>  

Любая помощь будет принята с благодарностью.

Добавлено:

Это класс действия: (это важно, если нет кода, связанные проверки не существует?)

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package agenda; 

import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpSession; 
import org.apache.struts2.ServletActionContext; 

/** 
* 
* @author Jaime 
*/ 
public class ProfileAction { 

    private String username; 
    private String password; 
    private String nombres; 
    private String apellidopaterno; 
    private String apellidomaterno; 
    private String fechanacimiento; 
    private String direccion; 
    private String comuna; 
    private String telefonofijo; 
    private String telefonomovil; 
    private String email; 
    private String sexo; 
    private String[] subscripcion; 

    public ProfileAction() { 
    } 

    /** 
    * 
    * @return @throws Exception 
    */ 
    public String execute() throws Exception { 
     HttpServletRequest request = ServletActionContext.getRequest(); 
     HttpSession session = request.getSession(); 
     String usuario = (String) session.getAttribute("id"); 
     if (usuario != null && !usuario.equals("") && !usuario.equals("0")) { 
      return "success"; 
     } else { 
      return "error"; 
     } 
    } 

    /** 
    * Muestra el formulario de registro de cliente 
    * 
    * @return 
    * @throws Exception 
    */ 
    public String register() throws Exception { 
     return "success"; 
    } 

    /** 
    * @return the username 
    */ 
    public String getUsername() { 
     return username; 
    } 

    /** 
    * @param username the username to set 
    */ 
    public void setUsername(String username) { 
     this.username = username; 
    } 

    /** 
    * @return the password 
    */ 
    public String getPassword() { 
     return password; 
    } 

    /** 
    * @param password the password to set 
    */ 
    public void setPassword(String password) { 
     this.password = password; 
    } 

    /** 
    * @return the nombres 
    */ 
    public String getNombres() { 
     return nombres; 
    } 

    /** 
    * @param nombres the nombres to set 
    */ 
    public void setNombres(String nombres) { 
     this.nombres = nombres; 
    } 

    /** 
    * @return the apellidopaterno 
    */ 
    public String getApellidopaterno() { 
     return apellidopaterno; 
    } 

    /** 
    * @param apellidopaterno the apellidopaterno to set 
    */ 
    public void setApellidopaterno(String apellidopaterno) { 
     this.apellidopaterno = apellidopaterno; 
    } 

    /** 
    * @return the apellidomaterno 
    */ 
    public String getApellidomaterno() { 
     return apellidomaterno; 
    } 

    /** 
    * @param apellidomaterno the apellidomaterno to set 
    */ 
    public void setApellidomaterno(String apellidomaterno) { 
     this.apellidomaterno = apellidomaterno; 
    } 

    /** 
    * @return the fechanacimiento 
    */ 
    public String getFechanacimiento() { 
     return fechanacimiento; 
    } 

    /** 
    * @param fechanacimiento the fechanacimiento to set 
    */ 
    public void setFechanacimiento(String fechanacimiento) { 
     this.fechanacimiento = fechanacimiento; 
    } 

    /** 
    * @return the direccion 
    */ 
    public String getDireccion() { 
     return direccion; 
    } 

    /** 
    * @param direccion the direccion to set 
    */ 
    public void setDireccion(String direccion) { 
     this.direccion = direccion; 
    } 

    /** 
    * @return the comuna 
    */ 
    public String getComuna() { 
     return comuna; 
    } 

    /** 
    * @param comuna the comuna to set 
    */ 
    public void setComuna(String comuna) { 
     this.comuna = comuna; 
    } 

    /** 
    * @return the telefonofijo 
    */ 
    public String getTelefonofijo() { 
     return telefonofijo; 
    } 

    /** 
    * @param telefonofijo the telefonofijo to set 
    */ 
    public void setTelefonofijo(String telefonofijo) { 
     this.telefonofijo = telefonofijo; 
    } 

    /** 
    * @return the telefonomovil 
    */ 
    public String getTelefonomovil() { 
     return telefonomovil; 
    } 

    /** 
    * @param telefonomovil the telefonomovil to set 
    */ 
    public void setTelefonomovil(String telefonomovil) { 
     this.telefonomovil = telefonomovil; 
    } 

    /** 
    * @return the email 
    */ 
    public String getEmail() { 
     return email; 
    } 

    /** 
    * @param email the email to set 
    */ 
    public void setEmail(String email) { 
     this.email = email; 
    } 

    /** 
    * @return the sexo 
    */ 
    public String getSexo() { 
     return sexo; 
    } 

    /** 
    * @param sexo the sexo to set 
    */ 
    public void setSexo(String sexo) { 
     this.sexo = sexo; 
    } 

    /** 
    * @return the subscripcion 
    */ 
    public String[] getSubscripcion() { 
     return subscripcion; 
    } 

    /** 
    * @param subscripcion the subscripcion to set 
    */ 
    public void setSubscripcion(String[] subscripcion) { 
     this.subscripcion = subscripcion; 
    } 
} 

Это файл JSP:

<%@ taglib prefix="s" uri="/struts-tags" %> 
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %> 

<script src="js/jquery/jquery.maskedinput.js" type="text/javascript"></script> 
<script src="js/jquery/jquery.selectbox-0.2.js" type="text/javascript"></script> 

<div id="register"> 
    <ul><li><a href="#frm_registro"><span><s:text name="profile.register" /></span></a></li></ul> 
    <div id="frm_registro"> 
     <s:div id="avisoError"><s:text name="profile.requiredtext" /></s:div> 
     <s:form id="registro" 
       action="proceso_registro" theme="css_xhtml" validate="true"> 
      <s:textfield name="username" key="profile.rut" labelposition="left" maxlength="50" /> 
      <s:password name="password" key="profile.password" labelposition="left" maxlength="50" /> 
      <s:textfield name="nombres" key="profile.nombres" labelposition="left" maxlength="80" size="40" /> 
      <s:textfield name="apellidopaterno" key="profile.apellidopaterno" labelposition="left" maxlength="80" size="40" /> 
      <s:textfield name="apellidomaterno" key="profile.apellidomaterno" labelposition="left" maxlength="80" size="40" /> 
      <s:textfield name="fechanacimiento" key="profile.fechanacimiento" labelposition="left" /> 
      <s:textfield name="direccion" key="profile.direccion" labelposition="left" maxlength="80" size="40" /> 
      <s:select name="comuna" key="profile.comuna" labelposition="left" list="#{'1':'Santiago', '2':'Huechuraba'}" headerValue="-= Seleccione Comuna =- " headerKey="" /> 
      <s:textfield name="telefonofijo" key="profile.telefonofijo" labelposition="left" maxlength="30" size="30" /> 
      <s:textfield name="telefonomovil" key="profile.telefonomovil" labelposition="left" maxlength="30" size="30" /> 
      <s:textfield name="email" key="profile.email" labelposition="left" maxlength="30" size="30" /> 
      <s:radio name="sexo" key="profile.sexo" labelposition="left" list="#{'M':'Masculino', 'F':'Femenino'}" /> 
      <s:checkboxlist name="subscripcion" key="profile.subscripcion" labelposition="left" list="#{'T':'Teléfono', 'E':'E-mail', 'M':'Mensaje de Texto'}" value="T" /> 

      <s:submit id="boton_registro" align="left" cssClass="send" value="Registrarse" /> 
     </s:form> 
    </div> 
</div> 

<script> 
    $("#register").tabs(); 
    $("#boton_registro").button(); 
    $("#registro_fechanacimiento").datepicker({ 
     dateFormat: "dd/mm/yy", 
     showOn: "both", 
     changeYear: true, 
     changeMonth: true, 
     buttonImage: "images/datepicker_icon.png", 
     buttonImageOnly: true, 
     buttonText: "<s:text name="AgendaPlus.choosedate" />"}); 
    $("#registro_fechanacimiento").mask("99/99/9999");            
    $.mask.definitions['~']='[0-9kK]'; 
    $("#registro_username").mask("99.999.999-~"); 
    $("#registro_comuna").selectbox({ 
     effect: "fade" 
    });  
    $("#registro_telefonofijo").mask("(99) 9999 9999");            
    $("#registro_telefonomovil").mask("(09) 9999 9999");            
</script> 

Это часть конфигурационного файла XML:

<action name="registro" class="agenda.ProfileAction" method="register"> 
     <result name="success" type="tiles">/register.tiles</result> 
     <result name="input" type="tiles">/register.tiles</result> 
    </action>   

    <action name="proceso_registro" class="agenda.ProfileAction" method="register"> 
     <interceptor-ref name="profiling"> 
      <param name="profilingKey">profilingKey</param> 
     </interceptor-ref>    
     <interceptor-ref name="jsonValidationWorkflowStack"/>    
     <result name="success" type="tiles">/register.success.tiles</result> 
     <result name="input" type="tiles">/register.tiles</result> 
    </action>   

"Registro" действие является точкой входа (форма), так как этот URL показывает: http://domain.cl:8080/AgendaPlus/registro

И, наконец, это файл вся проверка (ProfileAction-validation.xml)

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" 
    "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> 
<validators> 
    <field name="username"> 
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>Requerido</message> 
     </field-validator> 
     <field-validator type="rutValidator"> 
      <param name="trim">true</param> 
      <message key="errors.short_invalid" /> 
     </field-validator> 
    </field> 
    <field name="password"> 
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
    </field>  
    <field name="nombres"> 
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
    </field> 
    <field name="apellidopaterno"> 
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
    </field> 
    <field name="fechanacimiento"> 
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
    </field>  
    <field name="comuna"> 
     <field-validator type="int"> 
      <param name="min">1</param> 
      <message>*</message> 
     </field-validator>   
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
    </field>  
    <field name="telefonofijo"> 
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
    </field>  
    <field name="telefonomovil"> 
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
    </field>  
    <field name="email"> 
     <field-validator type="requiredstring"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
     <field-validator type="email"> 
      <param name="trim">true</param> 
      <message key="errors.short_invalid" /> 
     </field-validator>   
    </field>  
    <field name="sexo"> 
     <field-validator type="required"> 
      <param name="trim">true</param> 
      <message>*</message> 
     </field-validator> 
    </field>  
    <field name="subscripcion"> 
     <field-validator type="fieldexpression"> 
      <param name="expression"><![CDATA[#subscripcion.size() > 0]]></param> 
      <message>al menos uno</message> 
     </field-validator> 
    </field>  
</validators> 

Как вы видите, этот файл validation.xml отличается от большинства xml, присутствующих в учебниках Struts2, даже когда я использую Struts2. Но этот XML-файл работает как минимум для всего поля, но для моего настраиваемого валидатора, переключателей и списка флажков. При использовании validation.xml из других учебных пособий ничего не работает.

С наилучшими пожеланиями,

Благодарности Jaime

+0

ВОЗМОЖНО дубликата http://stackoverflow.com/questions/6242590/validation-to-a-radio-list-in-struts-2 – sunleo

+0

Да ... она дублируется, однако я уже читал решение там, я последовал примеру, но это не сработало. Он ничего не подтверждает, а способ, которым я был реализован, проверяет все, кроме переключателей и флажков. Ссылка с учебником, указанная в опубликованной вами ссылке, использует очень четкий синтаксис XML для файла validator.xml. – jstuardo

+0

@jstuardo: Может ли ваше сообщение ваше действие и страница JSP. –

ответ

0

Вы должны использовать required валидатор вместо requiredstring. Валидатор required проверяет, не задано ли указанное поле.

<field name="sexo"> 
    <field-validator type="required"> 
     <param name="trim">true</param> 
     <message>*</message> 
    </field-validator> 
</field> 

И «по крайней мере один» условие можно использовать fieldexpression валидатор.

Update

Поскольку ваш subscripcion является массив необходимо использовать переменную length не size метод, и без # перед ним.

<field name="subscripcion"> 
    <field-validator type="fieldexpression"> 
     <param name="expression"><![CDATA[subscripcion.length > 0]]></param> 
     <message>al menos uno</message> 
    </field-validator> 
</field> 
+0

Здравствуйте, для радио, это тоже не работает .... У меня это определено: . Для checkboxlist у меня есть это выражение: 0]]> где #subscripcion определяется как , и это не сработает. – jstuardo

+0

@jstuardo: Обновлен мой ответ. И для вас case 'requiredstring' должен работать и для переключателя. –

Смежные вопросы