Struts 2 validation not working properly as application grows - java

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.

Related

redirect after login with struts2

i want to make a redirect after a login action to my index page (index.jsp), actually my login works but the redirection is missing with ajax support.
Her is my login.jsp
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
function loginUser() {
var username = $("#username").val();
var userpass = $("#userpass").val();
$.ajax({
type : "POST",
url : "loginuser.action",
data : "username=" + username + "&userpass=" + userpass,
success : function(data) {
var ht = data.msg;
$("#resp").html(ht);
},
error : function(data) {
alert("Some error occured.");
}
});
}
</script>
</head>
<body style="text-align: center;">
<div class="container ">
<div class="col-lg-4">
<div class="form-group">
<input type="text" name="username" id="username"
class="form-control input-sm" placeholder="User Name">
</div>
<div class="form-group">
<input type="password" name="userpass" id="userpass"
class="form-control input-sm" placeholder="Password">
</div>
<button onclick="loginUser();" type="button" class="btn btn-success btn-block">Login</button>
<div class="text-center" id="resp" style="margin-top: 14px;"></div>
</div>
</div>
here is my LoginAction
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 5569022937143602032L;
private String username, userpass, msg;
Admin dao = null;
public String execute() throws SQLException, Exception {
dao = new Admin();
msg = dao.validate(username, userpass);
return msg;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpass() {
return userpass;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
my struts config file :
<?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>
<package name="default" extends="json-default">
<action name="loginuser"
class="org.websparrow.action.LoginAction">
<result name="LOGIN" type="json"></result>
<!-- <result name="Login Successful" type="redirectAction">index.jsp</result> -->
</action>
<action name="registeruser"
class="org.websparrow.action.RegisterAction">
<result name="REGISTER" type="json"></result>
</action>
<action name="report"
class="org.websparrow.action.ReportAction">
<result name="REPORT" type="json"></result>
</action>
<action name="updateuser"
class="org.websparrow.action.UpdateAction">
<result name="UPDATE" type="json"></result>
</action>
<action name="deleteuser"
class="org.websparrow.action.DeleteAction">
<result name="DELETE" type="json"></result>
</action>
</package>
for DAO part is :
public String validate(String username, String userpass) throws SQLException, Exception {
boolean status = false;
try {
String sql = "select * from USERS where UNAME=? and UPASS=?";
PreparedStatement ps = myconnection().prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, userpass);
ResultSet rs = ps.executeQuery();
status = rs.next();
if (status == true)
return "Login Successful";
else
return "Login Failed";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
} finally {
if (myconnection() != null) {
myconnection().close();
}
}
}
Thanks for your Help.
Do it in the success handler based on the result by changing the window.location value. Struts page redirect is not applicable in your scenario.

Accessing JSP form data with in the Struts 2 Action class

I don't understand how to access form data within the JSP page inside my Action class
login.jsp:
<div class="well">
<form id="loginForm" method="POST" action="hr/login/" novalidate="novalidate">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserEmail"><i class="fa fa-user" title="Enter Your username"></i></span>
<input type="text" class="form-control" id="username" name="username" value="" required title="Please enter you username" placeholder="Enter Username" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserPasswordMatch"><i class="fa fa-lock" title="Choose password"></i></span>
<input type="password" class="form-control" id="passwordmatch" name="passwordmatch" value="" required title="Enter your password" placeholder="Enter Password" />
</div>
</div>
<button type="submit" class="btn btn-success btn-block">Login</button>
</form>
</div>
BookingAction.java:
public class BookingAction {
private String name;
HotelReservationServceImpl service = new HotelReservationServceImpl();
public String execute() throws Exception {
return "success";
}
public String loginExecute()
{
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I also have a User class with private attributes which include username and password with getters and setters.
service.java:
public class HotelReservationServceImpl implements IHotelReservationService {
HotelReservationDAOImpl dbcon = new HotelReservationDAOImpl();
#Override
public int login(String username, String passwrd) {
if(username.isEmpty() || passwrd.isEmpty())
{
System.out.print(" Enter username and password ");
}
else
{
int i = dbcon.login(username, passwrd);
}
//dbcon.dbConnector();
return 0;
}
}
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="helloworld" extends="struts-default">
<action name="hello"
class="com.reservation.action.BookingAction"
method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
<action name="login"
class="com.reservation.action.BookingAction"
method="loginExecute">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
Use Struts tags to bind the form to the action and input fields to action properties.
<%# taglib prefix="s" uri="/struts-tags" %>
<s:form id="loginForm" method="POST" action="login" novalidate="novalidate">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserEmail"><i class="fa fa-user" title="Enter Your username"></i></span>
<s:textfield cssClass="form-control" id="username" name="user.username" value="" required title="Please enter you username" placeholder="Enter Username" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserPasswordMatch"><i class="fa fa-lock" title="Choose password"></i></span>
<s:password cssClass="form-control" id="passwordmatch" name="user.password" value="" required title="Enter your password" placeholder="Enter Password" />
</div>
</div>
<button type="submit" class="btn btn-success btn-block">Login</button>
</s:form>
To bind the form you should set the action name to the form tag. To bind input fields you should set property names to the struts input tags.
The properties are in the User bean that you should aggregate to the action class.
private User user;
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
If you don't want to generate extra HTML to the page use
<constant name="struts.ui.theme" value="simple"/>

How to link my form with the action?

I've a form with the following code:
<form action="doRegister" class="form-signup" >
<h2 class="form-signup-heading">Please sign up</h2>
<input type="email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" class="form-control" placeholder="Password" required>
<input type="password" class="form-control" placeholder="Password control" required>
<input type="text" class="form-control" placeholder="Name" required>
<input type="text" class="form-control" placeholder="Surname" required>
<input type="date" class="form-control" placeholder="Born date" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form
I've two classes: UserRegisterForm and UserRegistrationAction
UserRegisterForm
package com.github.jcpp.jathenaeum.action;
import org.apache.struts.action.ActionForm;
public class UserRegisterForm extends ActionForm{
private static final long serialVersionUID = 1;
/*ATTRIBUTES of the form fields*/
/*METHODS Get and Set*/
public UserRegisterForm() {
super();
}
}
UserRegistrationAction
package com.github.jcpp.jathenaeum.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.github.jcpp.jathenaeum.Utente;
import com.github.jcpp.jathenaeum.db.dao.UtenteDAO;
import com.github.jcpp.jathenaeum.exceptions.RegistrationException;
public class UserRegistrationAction extends Action{
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//boolean action_perform = false;
String action_target = null;
Random rnd = new Random();
UtenteDAO userDao = new UtenteDAO();
Utente user = new Utente();
//ActionMessages errors_mesg = new ActionMessages();
UserRegisterForm uf = (UserRegisterForm) form;
if(form != null){
user.setEmail(uf.getEmail());
user.setPassword(uf.getPassword());
user.setNome(uf.getName());
user.setCognome(uf.getSurname());
user.setDataNascita(uf.getBornDate());
user.setNumeroTessera(rnd.nextInt(999999)+1);
try{
if(userDao.register(user)){
action_target = "success";
}
}catch(Exception e){
action_target = "failed";
throw new RegistrationException();
}
}
return mapping.findForward(action_target);
}
in my struts-config.xml I've:
<form-beans>
<form-bean name="registerform" type="com.github.jcpp.jathenaeum.action.UserRegisterForm"/>
</form-beans>
<action-mappings>
<action path="/index" type="org.apache.struts.actions.ForwardAction" parameter="page.index" />
<action path="/signin" type="org.apache.struts.actions.ForwardAction" parameter="page.signin" />
<action path="/signup" type="org.apache.struts.actions.ForwardAction" parameter="page.signup" />
<action
path="/doRegister"
type="com.github.jcpp.jathenaeum.action.UserRegistrationAction"
name="registerform"
scope="request"
validate="true"
input="signup">
<forward name="input" path="/index.jsp"/>
<forward name="success" path="/welcome.jsp"/>
<forward name="failure" path="/index.jsp"/>
</action>
</action-mappings>
My errors report is:
type Status report
message /JAthenaeum/doRegister
description The requested resource is not available.
Why do I've this problem?
The problem was the action parameter in the form: it must be doRegister.do in my case, and in struts-config.xml the action path is equal to /doRegister. So, see the following code:
<form action="doRegister.do" >
[...]
</form>
and in the struts-config.xml
<action
path="/doRegister" <!-- LOOK HERE -->
type="com.github.jcpp.jathenaeum.action.UserRegistrationAction"
name="registerform"
scope="request"
validate="true"
input="/signup.jsp">
<!-- <forward name="input" path="/index.jsp"/>
<forward name="success" path="/signin.jsp"/>
<forward name="failed" path="/signup.jsp"/> -->
</action>
The action returns unknown forward named "failed". Change it to the one configured to the action "failure". The following code should replace
try {
if(!userDao.register(user)) {
return mapping.findForward("failure");
}
}catch(Exception e){
throw new RegistrationException(e);
}
return mapping.findForward("success");
The exception should be more informative, to tell you the cause of the exception.
Also the form should map to the action right
<html:form action="/doRegister" cssClass="form-signup" >

Struts 2 file upload : File object being null

I am trying to use Struts 2 file upload but it seems to me that its not working. Below is my code.
UploadAction.java:
public class UploadAction extends ActionSupport{
private File file;
private String orgFileName;
private String orgContentType;
public void setUpload(File file){
this.file=file;
}
public void setUploadContentType(String contentType){
this.orgContentType=contentType;
}
public void setUploadFileName(String fileName){
this.orgFileName=fileName;
}
#Override
public String execute(){
if(file==null)
{
System.out.println("No file....");
}
System.out.println(orgContentType);
System.out.println(orgFileName);
return SUCCESS;
}
}
struts.xml:
<constant name="struts.multipart.maxSize" value="20971520" />
<constant name="struts2.multipart.saveDir" value="C:/users/sabertooth/desktop/upload" />
<include file="example.xml"/>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="upload" class="UploadAction">
<result name="success">/example/HelloWorld.jsp</result>
</action>
</package>
I am also trying to set struts2.multipart.saveDir property as you can see above but when I read the server logs I see this line
unable to find `struts.multipart.saveDir` defaulting to `javax.servlet.dir`
Also the file object is null as no file... gets printed out on console.
I can't figure out what is wrong here.
EDIT:
fileupload.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>
<h1>upload file below</h1>
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
</body>
</html>
Apart from changing the saveDir (really not necessary, and dangerous), your are not following the conventions in the Action class: the name of an private variable must match the names of its Getters and Setters; and finally, in page you are mismatching the name by pointing to the private variable, not the setter. Change it to:
public class UploadAction extends ActionSupport{
private File upload;
private String uploadFileName;
private String uploadContentType;
public void setUpload(File upload){
this.upload=upload;
}
public void setUploadContentType(String uploadContentType){
this.uploadContentType=uploadContentType;
}
public void setUploadFileName(String uploadFileName){
this.uploadFileName=uploadFileName;
}
#Override
public String execute(){
if(upload==null)
{
System.out.println("No file....");
}
System.out.println(uploadContentType);
System.out.println(uploadFileName);
return SUCCESS;
}
}
JSP
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
Change this
<input type="file" name="file" id="uploadfile" />
to
<input type="file" name="upload" id="uploadfile" />
Your setter in your action class is setUpload so it is looking for a request parameter called upload, not file. For the sake of convention you should also change
private File file;
public void setUpload(File file){
this.file=file;
}
to
private File upload;
public void setUpload(File file){
this.upload=file;
}

Recieving 'null' values from a jsp page into Struts 2 Action

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

Categories