I have got a little problem with Struts2, and I don't know why it doesn't work ...
I want to pass 2 variables between two JSP, via an Action class :
view1.jsp :
<s:form action="myAction">
<input id="var1" name="var1" type="text" />
<input id="var2" name="var2" type="text" />
<button type="submit"> Ok </button>
</s:form>
-> var1 and var2 are the variables that I want to pass to the Action class
struts.xml:
<action name="myAction" class="MyAction" method="execute">
<result name="success">view2.jsp</result>
</action>
Action.java :
public class MyAction extends DefaultActionSupport
{
private String var1;
private String var2;
public String execute() throws Exception
{
// ... Some actions ...
return SUCCESS;
}
// Getters & Setters for var1 and var2 (generated by Eclipse)
public String getVar1()
{
return var1;
}
public void setVar1(String var1)
{
this.var1 = var1;
}
public String getVar2()
{
return var2;
}
public void setVar2(String var2)
{
this.var2 = var2;
}
-> This works correctly ; if I put "System.out.print" with the getters, it shows me the good values of var1 (content1) and var2 (content2)
view2.jsp :
Values of var1 = <s:property value="var1" />
Values of var2 = <s:property value="var2" />
Textfield with var1 in default-value : <s:textfield value="%{var1}" />
Textfield with var2 in default-value : <s:textfield value="%{var2}" />
-> There is a problem here :
I can't get the content of var1 and var2 !
-> <s:property value="var1" /> and <s:textfield value="%{var1} are returning "null"
Where is my error ? I don't understand ... I followed what the others said on the internet ...
Thank you !
I finally found the answer to my problem !
To get the value of var1and var2I had to use those following lines :
view1.jsp :
<s:form action="myAction">
<input id="var1" name="var1" type="text" />
<input id="var2" name="var2" type="text" />
<button type="submit"> Ok </button>
</s:form>
struts.xml:
<action name="myAction" class="MyAction" method="execute">
<result name="success">view2.jsp</result>
</action>
Action.java :
public class MyAction extends DefaultActionSupport{
private String var1;
private String var2;
public String execute() throws Exception{
// ... Some actions ...
ActionContext.getContext().getSession().put("var1", getVar1());
ActionContext.getContext().getSession().put("var2", getVar2());
return SUCCESS;
}
// Getters & Setters for var1 and var2 (generated by Eclipse)
public String getVar1(){
return var1;
}
public void setVar1(String var1){
this.var1 = var1;
}
public String getVar2(){
return var2;
}
public void setVar2(String var2){
this.var2 = var2;
}
}
view2.jsp :
Values of var1 = <s:property value="#session.var1" />
Values of var2 = <s:property value="#session.var2" />
//To transform var1 and var2 into JSP variables :
<s:set var="var1 " value="#session.var1 " />
<s:set var="var2 " value="#session.var2" />
<jsp:useBean id="var1 " type="java.lang.String" />
<jsp:useBean id="var2 " type="java.lang.String" />
<%
String myString1 = var1;
String myString2 = var2
%>
Related
creating a webserver in netbeans with I have 3 files index.jsp, response.jsp and client.java.
the idea is to create a temperature converter, but only takes the input and not doing the calculator job.
please any help!?
index.jsp
<form name="Input Form" id="ftemp" action="response.jsp">
<input type="text" name="temp" />
<select name="conv1">
<option>Celsius</option>
<option>Fahrenheit</option>
</select>
<select name="conv2">
<option>Fahrenheit</option>
<option>Celsius</option>
</select>
<input type="submit" value="Submit" />
</form>
response.jsp
<body>
<h1>your list is in order</h1>
<jsp:useBean id="sortbean" scope="session" class="sortclient.SortClient" />
<jsp:setProperty name="sortbean" property="input" />
<jsp:setProperty name="sortbean" property="cel" />
<jsp:setProperty name="sortbean" property="fahr" />
<jsp:getProperty name="sortbean" property="input" />
</body>
client.java
public class SortClient {
private String input;
double cel = 0;
double fahr = 0;
public SortClient (){
input = null;
}
public String getInput() {
try{
String key = getKey();
input = mergeSort (input,key);
double tempCelsius = input.nextDouble();
double tempFahrenheit = input.nextDouble();
return input;
}catch (Exception ex){
System.out.println(ex); //we would log this
return "That is not a valid list";
}
}
public void setInput(String input) {
this.input = input;
}
public double toCelsius( double tempFahrenheit )
{
return ((5.0 / 9.0) * ( tempFahrenheit - 32 ));
}
public double toFahrenheit( double tempCelsius )
{
return (tempCelsius * 9.0 / 5.0) + 32;
}
private static String mergeSort(java.lang.String input, java.lang.String userKey) {
org.tempuri.Service service = new org.tempuri.Service();
org.tempuri.IService port = service.getBasicHttpBindingIService();
return port.mergeSort(input, userKey);
}
private static String getKey() {
org.tempuri.Service service = new org.tempuri.Service();
org.tempuri.IService port = service.getBasicHttpBindingIService();
return port.getKey();
}
You have multiple problems in your code. Here are some suggestions:
Match the input names in index.html and SortClient.java to avoid confusion and simplify property assignments
Create setter and getter for all fields or else jsp:setProperty and jsp:getProperty won't work
Pay attention on your data types: String doesn't have nextDouble(). If you haven't please use IDE (Eclipse, Netbeans, Intellij .etc) assistance.
Remove unnecessary libraries and code eg. org.tempuri.*
Here are codes implementing suggestions above:
index.jsp
<form name="Input Form" id="ftemp" action="response.jsp">
<input type="text" name="temp" />
<select name="conv1">
<option>Celsius</option>
<option>Fahrenheit</option>
</select>
<select name="conv2">
<option>Fahrenheit</option>
<option>Celsius</option>
</select>
<input type="submit" value="Submit" />
</form>
response.jsp
<h1>your list is in order</h1>
<jsp:useBean id="sortbean" scope="session" class="sortclient.SortClient" />
<jsp:setProperty name="sortbean" property="*" />
Input: <jsp:getProperty name="sortbean" property="temp" /><br>
Conv1: <jsp:getProperty name="sortbean" property="conv1" /><br>
Conv2: <jsp:getProperty name="sortbean" property="conv2" /><br>
Result: <jsp:getProperty name="sortbean" property="result" />
SortClient.java
package sortclient;
public class SortClient {
private String temp;
private String conv1;
private String conv2;
private Double result;
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getConv1() {
return conv1;
}
public void setConv1(String conv1) {
this.conv1 = conv1;
}
public String getConv2() {
return conv2;
}
public void setConv2(String conv2) {
this.conv2 = conv2;
}
public Double getResult() {
result = Double.parseDouble(temp);
if (conv1.equalsIgnoreCase(conv2)) {
return result;
} else if (conv2.equalsIgnoreCase("Celsius")) {
return toCelsius(result);
} else if (conv2.equalsIgnoreCase("Fahrenheit")) {
return toFahrenheit(result);
}
return 0.0;
}
public double toCelsius(double tempFahrenheit )
{
return ((5.0 / 9.0) * ( tempFahrenheit - 32 ));
}
public double toFahrenheit( double tempCelsius )
{
return (tempCelsius * 9.0 / 5.0) + 32;
}
}
Refer to this tutorial for detailed guide.
As other have suggested, this approach is actually considered obsolete as it's tightly coupled and not maintainable on big scale. So I'd also suggest you to learn MVC pattern as from tutorial such as:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
http://www.thejavageek.com/2013/08/11/mvc-architecture-with-servlets-and-jsp/
I have an iterator which requires to use mapped properties or indexed properties but my getter-setter are not getting those values.
For Ex:
(This is just an example. Ultimately the idea is whether I can use mapped property in struts 2 or not. If yes, then how.)
index.jsp:
<s:form action="hello" namespace="foo">
<s:textfield name="arp(0)" /> <br/>
<s:textfield name="prp(0)" /> <br/>
<s:textfield name="arp(1)" /> <br/>
<s:textfield name="prp(1)" /> <br/>
<s:submit value="Say Hello" />
</s:form>
helloWorld.action:
class PRLists {
String arp;
String prp;
public String getArp() {
return Arp;
}
public void setArp(String aRP) {
arp = aRP;
}
public String getPrp() {
return prp;
}
public void setPrp(String pRP) {
prp = pRP;
}
}
public class HelloWorldAction {
ArrayList<PRLists> prlist = new ArrayList<PRLists>();
public String execute() throws Exception {
System.out.println("ruuning execute");
return "success";
}
public ArrayList<PRLists> getPrlist() {
return prlist;
}
public void setPrlist(ArrayList<PRLists> prlist) {
this.prlist = prlist;
}
public String getArp(String key) {
int index = Integer.parseInt(key);
return prlist[index].arp;
}
public void setArp(String key, Object value) {
System.out.println("set ARP: index:" + index + ", value" + value);
int index = Integer.parseInt(key);
prlist[index].arp = value.toString();
}
public String getPrp(String key) {
int index = Integer.parseInt(key);
return prlist[index].prp;
}
public void setPrp(String key, Object value) {
System.out.println("set PRP, Key:" + key + ", value:" + value);
int index = Integer.parseInt(key);
prlist[index].prp = value.toString();
}
}
Earlier I was having this kind of working functions in struts 1 but now I am trying to move it to struts 2. Now my setter functions in HelloWorldAction.java for arp and prp are not getting called upon form submit.
public void setArp(String key, Object value);
public void setPrp(String key, Object value);
<s:textfield name="prlist[0].arp" /> can work but we have some dependent code which requires to use fields with name such as <s:textfield name="arp(0)" />.
I do not know whether struts 2 supports mapped properties or not. If it supports, then how can I use it.
I also found a related issue: https://issues.liferay.com/browse/LPS-14128
Note: I have made some modifications in question description
Thanks in advance.
You're violating a lot of "rules" here, other than avoiding almost any mechanism provided by the framework. Never put logic in accessors / mutators (getters / setters), never use capitalized variable names, avoid using variables starting with an uppercase letter, read struts Type Conversion, use Struts tags (eg. <s:textfield/> instead of <input type="text" />) whenever possible, and reduce your code to:
public class HelloWorldAction{
private String name;
private List<PRLists> arnList = new ArrayList<PRLists>();
public String execute() throws Exception {
System.out.println("running execute");
return "success";
}
public List<PRLists> getArnList(){
return arnList;
}
public void setArnList(List<PRLists> arnList){
this.arnList = arnList;
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("set name: "+name);
this.name = name;
}
}
<s:form action="hello" namespace="foo">
<s:textfield name="name" label="name" />
<s:textfield name="arnList[0].arp" /> <br/>
<s:textfield name="arnList[0].prp" /> <br/>
<s:textfield name="arnList[1].arp" /> <br/>
<s:textfield name="arnList[1].prp" /> <br/>
<s:submit value="Say Hello" />
</s:form>
of in an iterator, as you said (without showing it), like
<s:form action="hello" namespace="foo">
<s:textfield name="name" label="name" />
<s:iterator value="arnList" status="rowStatus">
<s:textfield name="arnList[%{#rowStatus.index}].arp" /> <br/>
<s:textfield name="arnList[%{#rowStatus.index}].prp" /> <br/>
</s:iterator>
<s:submit value="Say Hello" />
</s:form>
When I want to save data into database it's throws exception.
My Jsp as follows:
list.jsp
<body>
<s:form action="userActionForm">
<s:submit value="Add"/>
</s:form>
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>First Name</th>
<th>Last Name</th>
<th>Contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<s:iterator value="userList" status="userStatus">
<tr
class="<s:if test="#userStatus.odd == true ">odd</s:if> <s:else>even</s:else>">
<td><s:property value="fName" /></td>
<td><s:property value="lName" /></td>
<td><s:property value="contact" /></td>
<td><s:url id="editURL" action="editUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</div>
<s:a href="logOut">LogOut</s:a>
</body>
register.jsp
<body>
<s:form action="saveOrUpdateUser" method="post">
<s:push value="userdata">
<s:hidden name="id" />
<s:textfield name="First name" label="Enter Name"/>
<s:textfield name="Lst Name" label="Enter Lst Name"/>
<s:textfield name="Contact" label="Enter Contact"/>
<s:submit />
</s:push>
</s:form>
</body>
UserAction.java
public class UserAction extends ActionSupport implements ModelDriven<UserData> {
private UserData userdata = new UserData();
private UserDAO userDAO = new UserDAOImpl();
setters & getters
#Override
public UserData getModel() {
System.out.println("userdata = ==" + userdata.getName());
return userdata;
}
public String saveOrUpdate() {
System.out.println("user data" + userdata);
userDAO.saveOrUpdateUser(userdata);
return SUCCESS;
}
}
UserDAO
public interface UserDAO
{
public void saveOrUpdateUser(UserData userData);
}
UserDAOImpl
public class UserDAOImpl implements UserDAO
{
#SessionTarget
private Session session;
#TransactionTarget
Transaction transaction;
public void saveOrUpdateUser(UserData userdata) {
try {
session.saveOrUpdate(userdata);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
Struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="hibernate-default">
<interceptors>
<interceptor name="mylogging" class="Demo.AuthenticationInterceptor"> </interceptor>
<interceptor-stack name="loggingStack">
<interceptor-ref name="mylogging" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="loggingStack"></default-interceptor-ref>
<action name="saveOrUpdateUser" method="saveOrUpdate" class="Demo.UserAction">
<result name="success" type="redirect" >list.jsp</result>
<result name="login">/login.jsp</result>
</action>
</package>
</struts>
When I run the application I got exception like NullPointer Exception
java.lang.NullPointerException
at Demo.UserDAOImpl.saveOrUpdateUser(UserDAOImpl.java:36)
at Demo.UserAction.saveOrUpdate(UserAction.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
AuthenticationInterceptor:
public class AuthenticationInterceptor implements Interceptor
{
public String intercept(ActionInvocation ai) throws Exception
{
System.out.println("inside the interceptor()......new");
Map session = ai.getInvocationContext().getSession();
String name = (String) session.get("name");
System.out.println("inside the session or loginaction=" + name);
if ((session.get("name") != null) || ((session.get("name") == null))) {
System.out.println("inside the session or loginaction ");
return ai.invoke();
} else {
return "login";
}
}
}
This exception I got how to overcome I don't know
You have a logic error. I have noticed that you have a nonsense if statement that seems that it will always return true.
if ((session.get("name") != null) || ((session.get("name") == null)))
Your are checking with an or statement here ( || = OR ) the statement will be true in both cases if it is null or not.
you probably want something more along the lines of:
if (session.get("name") != null)
{
do the is NOT null actions
}else if(session.get("name") == null)
{
do the IS null actions
(probably put a warning message here to help you better diagnose null problems with your session)
}
this could be the cause of your current nullPointerException, or it might not, but either way this will fix possible problems in the future involving that statement.
Is there any alternative validation framework while building complex web app? Or any guide for validation. Links to example is not required as it working on simple Form but not in complex Form with multiple links.
This is my action class
package com.tpc.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.tpc.domain.LeadFacultyModel;
import com.tpc.service.LeadFacultyServiceInterface;
public class LeadFacultyAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private LeadFacultyModel leadFacultyModel;
private String lead_faculty_formAction;
// Injecting leadFacultyServiceImpl bean
LeadFacultyServiceInterface leadFacultyServiceImpl;
//variable to store the action message to pass to other pages through get request
private String action_msg = null;
private List<LeadFacultyModel> leadFacultyModelList = new ArrayList<LeadFacultyModel>();
public String execute() throws Exception {
return SUCCESS;
}
public String formAction() throws Exception
{
if(lead_faculty_formAction.equals("Save"))
{
System.out.println("Inside Update");
return this.updateLeadFaculty();
}
else if(lead_faculty_formAction.equals("Submit"))
{
System.out.println("Inside Save");
return this.saveLeadFaculty();
}
else if(lead_faculty_formAction.equals("Delete"))
{
System.out.println("Inside Delete");
return this.deleteLeadFaculty();
}
else
{
return SUCCESS;
}
}
public String saveLeadFaculty() throws Exception {
boolean result =leadFacultyServiceImpl.createLeadFaculty(leadFacultyModel);
if(result == true)
{
addActionMessage(getText("message.save_success"));
return "SAVE_SUCCESS";
}
else {
addActionError(getText("message.save_error"));
return "SAVE_ERROR";
}
}
public String viewAllLeadFaculty(){
// TODO Auto-generated method stub
System.out.println("view all method is called");
try{
leadFacultyModelList = leadFacultyServiceImpl.getAllLeadFaculty();
System.out.println("Action page "+leadFacultyModelList.size());
return SUCCESS;
}catch(Exception ex){
ex.printStackTrace();
return ERROR;
}
}
//Section of getter/setter methods in this class
public void setLeadFacultyModel(LeadFacultyModel leadFacultyModel) {
this.leadFacultyModel = leadFacultyModel;
}
public LeadFacultyModel getLeadFacultyModel() {
return leadFacultyModel;
}
public String getLead_faculty_formAction() {
return lead_faculty_formAction;
}
public void setLead_faculty_formAction(String lead_faculty_formAction) {
this.lead_faculty_formAction = lead_faculty_formAction;
}
public void setLeadFacultyServiceImpl(
LeadFacultyServiceInterface leadFacultyServiceImpl) {
this.leadFacultyServiceImpl = leadFacultyServiceImpl;
}
public void setAction_msg(String action_msg) {
this.action_msg = action_msg;
}
public List<LeadFacultyModel> getLeadFacultyModelList() {
return leadFacultyModelList;
}
public void setLeadFacultyModelList(List<LeadFacultyModel> leadFacultyModelList) {
this.leadFacultyModelList = leadFacultyModelList;
}
public String getAction_msg() {
return action_msg;
}
}
This is LeadFacultyAction-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="leadFacultyModel.lead_string_FacultyName">
<field-validator type="requiredstring">
<message>Name is required.</message>
</field-validator>
</field>
</validators>
this is struts.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<package name="default" extends="struts-default">
<!-- /** defining result types for implementing tiles **/ -->
<result-types>
<result-type name="tiles"
class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<global-results>
<result name="error">/404_error.jsp</result>
</global-results>
<action name="">
<result></result>
</action>
<action name="baseTemplate" >
<result type="tiles">baseTemplate</result>
</action>
<action name="setup_lead_faculty">
<result type="tiles">setup_lead_faculty</result>
</action>
<action name="setup_LeadFacultyAction" class="com.tpc.action.LeadFacultyAction" method="formAction">
<result name="SAVE_SUCCESS" type="tiles">setup_lead_faculty</result>
<result name="UPDATE_SUCCESS" type="tiles">setup_lead_faculty</result>
<result name="DELETE_SUCCESS" type="tiles">setup_lead_faculty</result>
<result name="SAVE_ERROR" type="tiles">setup_lead_faculty</result>
<result name="UPDATE_ERROR" type="tiles">setup_lead_faculty</result>
<result name="DELETE_ERROR" type="tiles">setup_lead_faculty</result>
<result name="input" type="tiles">setup_lead_faculty</result>
</action>
<action name="setup_LeadFaculty_list_view_Action" class="com.tpc.action.LeadFacultyAction" method="viewAllLeadFaculty">
<result type="tiles" name="success">setup_lead_faculty_list_view</result>
</action>
<action name="setup_LeadFacultyAction_selected_from_list" class="com.tpc.action.LeadFacultyAction" method="getByIdLeadFaculty">
<result type="tiles" name="success">setup_lead_faculty</result>
</action>
</package>
This is my JSP file:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<c:set value="/lms/" var="baseUrl" />
<s:form method="post" action="setup_LeadFacultyAction">
<div class="buttontab">
<input type="submit" name="lead_faculty_formAction" value="Save"
class="form_button" /> <input type="submit"
name="lead_faculty_formAction" value="Submit" class="form_button" />
<input type="submit" name="lead_faculty_formAction"
value="Delete" class="form_button" /> <input
type="submit" name="lead_faculty_formAction" value="Reset" disabled="disabled"
class="form_button" /> <span class="span"
style="float: right;"> <i><a href="${baseUrl}lead/setup_LeadFaculty_list_view_Action"> <img
src="${baseUrl}icons/gridview.png" width="12px" height="12px" /></a> </i> </span>
<span class="span" style="float: right;"> <i><img
src="${baseUrl}icons/formview.png" width="12px" height="12px" /> </i> </span>
<span class="span" style="float: right;"> <i><img
src="${baseUrl}icons/tileview.png" width="12px" height="12px" /> </i> </span>
</div>
<div id="content_wrap">
<div class="unidiv1">
<s:if test="hasActionErrors()">
<div class="errors">
<s:actionerror/>
</div>
</s:if>
<s:if test="hasActionMessages()">
<div>
<p><s:actionmessage/></p>
</div>
</s:if>
<s:if test="hasFieldErrors()">
<div>
<p><s:fielderror/></p>
</div>
</s:if>
<div class="field_wrapper">
<div class="left_box">
<label>ID</label>
</div>
<div class="right_box">
<input type="text" name="leadFacultyModel.lead_string_FacultyId" value="${leadFacultyModel.lead_string_FacultyId}"
class="input_id" />
</div>
</div>
<div class="field_wrapper">
<div class="left_box">
<label>Faculy</label>
</div>
<div class="right_box">
<input type="text" name="leadFacultyModel.lead_string_FacultyName" value="${leadFacultyModel.lead_string_FacultyName }" />
</div>
</div>
<div class="field_wrapper">
<div class="left_box">
<label>Remarks</label>
</div>
<div class="right_box">
<textarea name="leadFacultyModel.lead_string_FacultyRemarks"
class="textarea_address">${leadFacultyModel.lead_string_FacultyRemarks}</textarea>
</div>
</div>
</div>
</div>
The difference is only if Struts discover validation annotations while intercepting the action it processes those annotations to perform validations by applying validation rules exposed by annotations. The same thing is when parsing -validation.xml. You can use both validation methods xml based and annotation based together, or with addition to custom validation (excluding custom validators).
For example, if I have a phone field and I want to validate it is not empty and contains a predefined format I will just put two annotations on it.
private String phone;
public String getPhone() {
return phone;
}
#RequiredStringValidator(type= ValidatorType.FIELD, message="Phone required.")
#RegexFieldValidator(type= ValidatorType.FIELD, message="Invalid Phone",
regexExpression="\\([0-9][0-9][0-9]\\)\\s[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]")
public void setPhone(String phone) {
this.phone = phone;
}
then I have an execute action I don't want to validate
#SkipValidation
public String execute() throws Exception {
then I have another action save that I want to validate questions but I don't want to validate a phone.
private String myQuestionq1;
private String myQuestionq2;
public String getMyQuestionq1() {
return myQuestionq1;
}
public void setMyQuestionq1(String myQuestionq1) {
this.myQuestionq1 = myQuestionq1;
}
public String getMyQuestionq2() {
return myQuestionq2;
}
public void setMyQuestionq2(String myQuestionq2) {
this.myQuestionq2 = myQuestionq2;
}
#Action(value="save", results = {
#Result(name="input", location = "/default.jsp"),
#Result(name="back", type="redirect", location = "/")
},interceptorRefs = #InterceptorRef(value="defaultStack", params = {"validation.validateAnnotatedMethodOnly", "true"}))
#Validations(requiredFields = {
#RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "myQuestionq1", message = "You must enter a value for field myQuestionq1."),
#RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "myQuestionq2", message = "You must enter a value for field myQuestionq2.")
})
public String save() throws SQLException {
this will execute only validators on this action.
More examples you could always find on Apache web site:
Validation using annotations examples.
I have a jsp page and struts 2 Action class . When I submit the form in the jsp , I am getting null values into the action.
The JSP code looks like :
<s:form id="user" name="user" action="initUserAdmin">
<s:textfield name="userName" cssClass="txtbox" size="30" />
<div class="btn"><a href='<s:url action="searchUserAdmin"/>'
title="Search" id="button" class="btn" ><span>Search</span></a></div>
</s:form>
The struts.xml has this part
<action name="*UserAdmin" method="{1}" class="com.mphasis.im.web.action.UserAction">
<result name="init" type="tiles">user</result>
<result name="search" type="tiles">user</result>
<result name="reset" type="tiles">user</result>
<result name="createNew" type="tiles">createNewUser</result>
</action>
And the Action class has this :
public class UserAction extends BaseAction
{
public String userName;
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String search()
{
searchProcessed = true;
System.out.println("******** inside search ******");
System.out.println("username = "+ userName);
return TilesConstants.SEARCH;
}
And the output comes as below when I type a string in the text box in jsp page.
******** inside search ******
username = null
What might be the problem ? Am I missing something ?
<a href='<s:url action="searchUserAdmin"/>'
title="Search" id="button" class="btn" >
It's just a href to the URL of action and with no parameter. Therefore, the 'userName' in the action is null.
<s:form id="user" name="user" action="initUserAdmin">
<s:textfield name="userName" cssClass="txtbox" size="30" />
<div class="btn"><a href='javascript:submitme()'
title="Search" id="button" class="btn" ><span>Search</span></a></div>
</s:form>
Javascript
function submitme(){
document.user.submit()
}
Also in the action mapping you provided the action name you are using there is UserAdmin whereas in the form action you are using initUserAdmin.They must be the same