How to link my form with the action? - java

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" >

Related

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"/>

Submitting form's data to a java Set

Is it possible to submit a form's data to a java Set in an action of Struts2?
Action code:
class TestAction extends ActionSupport{
private Set<Integer> mySet = new LinkedHashSet<Integer>();
public TestAction(){
}
public String test(){
someMethod(mySet);
}
... Getters/Setters ...
}
Form code:
<form action="test.action" >
<input name="mySet[0]" />
<input name="mySet[1]" />
<input name="mySet[2]" />
<submit />
</form>
The Set is just a collection, and Struts2 has support for any type of collections internally. But for this type of collection you can't use indexes in your OGNL expressions. Try
<form action="test.action" >
<input name="mySet" />
<input name="mySet" />
<input name="mySet" />
<s:submit />
</form>

struts 2 action error : retrieves values of form properties

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

Struts 2 validation not working properly as application grows

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.

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