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
Related
I'm quite new to JSPs and JavaBeans and trying out how to pass values of parameters from a form in one JSP (theForm.jsp) to another JSP (theResult.jsp) as follows:
In my theResult.jsp:
<body>
<jsp:useBean id="user" class="people.User" scope="application"/>
Your username is: <jsp:getProperty name="user" property="username"/><br>
Your password is: <jsp:getProperty name="user" property="password"/><br>
</body>
And in my theForm.jsp file:
<body>
<jsp:useBean id="user" class="people.User" scope="application">
<jsp:setProperty name="user" property="username" value='<%=request.getParameter("username")%>'/>
<jsp:setProperty name="user" property="password" param="password"/> // another way to use setProperty, I read
</jsp:useBean>
<form action="theResult.jsp" method="post">
<input type="text" name="username" placeholder="Type your username"><br>
<input type="password" name="password" placeholder="Type your password"><br>
<input type="submit" value="submit">
</form>
</body>
But all my result is showing is:
Your username is: null
Your password is: null
My people.user javabean:
package people;
public class User implements java.io.Serializable {
private String username;
private String password;
public User(){}
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
//... and same thing for 'password'
}
<body>
<jsp:useBean id="user" class="people.User"/>
<jsp:setProperty name="user" property="*"/>
<%-- the (*) symbol indicates the value should come
from request parameter whose name matches property
name . Thus simple automatic conversion should be
performed --%/>
Your username is: <jsp:getProperty name="user" property="username"/><br>
Your password is: <jsp:getProperty name="password"/><br>
I try to send url parameter to Action class as described here: How to access url parameters in Action classes Struts 2
If I do like next, it works and I can get pageLevel in Action class
<s:form action="index?pageLevel=99">
<s:checkboxlist label="Select" list="colors" name="yourColor" value="defaultColor" />
<s:submit value="Submit" />
</s:form>
But next does not work
<s:form action="index?pageLevel=<%=level%>">
And this does not work too
<c:set var="pageLevel" scope="page" value="<%=level%>" />
<s:form action="index?pageLevel=${pageLevel}">
I get error
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /start.jsp (line: 86, column: 0)
According to TLD or attribute directive in tag file, attribute action
does not accept any expressions
Jsp page contains
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
How can I do it?
Have a 'level' property in your index action with its getter an setter
Something like:
public class Index extends ActionSupport {
private String level;
public String getLevel() {
return this.getLevel();
}
public void setLevel(String level) {
this.level = level;
}
}
Set 'level' as a hidden parameter in the form.
Assuming your action name is "index" and the request parameter is "pageLevel":
<s:form action="index">
<s:checkboxlist label="Select" list="colors" name="yourColor" value="defaultColor" />
<s:hidden name="level" value="%{#parameters.pageLevel}" />
<s:submit value="Submit" />
</s:form>
Try this
<s:form action="index">
<s:checkboxlist label="Select" list="colors" name="yourColor" value="defaultColor" />
<s:hidden name="pageLevel" value="%{pageLevel}"/>
<s:submit value="Submit" />
</s:form>
I have following situation in code:
Action class:
#NameSpace("/")
public class MyAction extends ActionSupport implements ModelDriven<Car> {
private Car car = new Cart();
#Override
public Car getModel() {
return car;
}
#Action(value = "pageAction", results = {name = SUCCESS, location = "myPage", type="tiles"})
public String showPage() {
return SUCCESS;
}
#Action(value = "formSubmitAction", results = {name = SUCCESS, location = "results.jsp"})
public String formSubmitAction() {
System.out.println(car);
// everything has default values (nulls)
return SUCCESS;
}
}
View for myPage location:
<s:form
namespace="/"
action="pageAction"
method="post" >
<s:push value="model">
<s:textfield name="color" />
<s:textfield name="manufacturer" />
<sj:submit
href="formSubmitAction"
targets="output" />
</s:push>
</s:form>
<div id="output"></div>
results.jsp:
renders empty content into div#output
<s:property value="%{model}" />
<s:property value="%{model.color}" />
<s:property value="%{model.manufacturer}" />
I wonder why is that happening? Model data is not updated after submit.
I'm using struts2-jquery submit tag.
When I'm using simple form submit without Ajax the model is being updated,
but I want to load data asynchronously with Ajax.
How can I achieve that?
The solution is to add ID to form and to sj:submit tag. But I don't know why submit tag inside form wasn't working properly. The correct code is below:
<s:form
id="formId"
namespace="/"
action="pageAction"
method="post" >
<s:push value="model">
<s:textfield name="color" />
<s:textfield name="manufacturer" />
<sj:submit
formIds="formId"
href="formSubmitAction"
targets="output" />
</s:push>
</s:form>
EDIT
As it turns out you only have to add ID to form, and everything works :)
look at link in the comment below
The modelDriven interceptor pushes a model on top of the valueStack. So you can access model properties directly.
<s:property value="%{color}" />
<s:property value="%{manufacturer}" />
Problem
I am using jsp to submit a form and struts 2 action class takes care of it. If there is some problem, then i am sending the result to same page with an error message.
Along with the error message, i want to display property values that he had provided while submitting the request.
Source code
Form contains few text fields and few file type inputs.
My CreateRequest.jsp file:
<input type="file" name="attachment" id="myFile1" />
<input type="file" name="attachment" id="myFile2" />
<input type="file" name="attachment" id="myFile3" />
<input type="text" name="operationName" id="operation1" />
<input type="text" name="operationName" id="operation2" />
<input type="text" name="operationName" id="operation3" />
My Action class :
public class CreateRequest extends ActionSupport {
private List<File> attachment;
private List<String> attachmentContentType;
private List<String> attachmentFileName;
private List<String> operationName
// contains getter and setter for each property
public string execute(){
// some logic
//returns error if it fails otherwise success
}
}
struts.xml (Action Servlet) file:
<action name="createRequest"
class="action.CreateRequest">
<result name="success">RequestStatus.jsp
</result>
<result name="input" >CreateRequest.jsp</result>
<result name="error" >CreateRequest.jsp</result>
</action>
HELP
How do i get all those values displayed in CreateRequest.jsp page, when the action class returns error.
use ognl value=" %{operationName[0]}" for text box
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.