These are the files that I have created along with the AccessDenied.jsp and HelloWorld.jsp, but the code doesn't run.
package com.Struts;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldActionSupport extends ActionSupport {
private String name;
public HelloWorldActionSupport() {
}
#Override
public String execute() throws Exception
{
if("SECRET".equals(name))
{
return SUCCESS;
}
else
{
return ERROR;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Struts.xml File:
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- Configuration for the default package.
<constant name="struts.devMode" value="true"/>
<package name="hello" extends="struts-default">
<action name="helloWorldActionSupport" class= "com.Struts.HelloWorldActionSupport">
<result name="success">/HelloWorld.jsp</result>
<result name="error">/AccessDenied.jsp</result>
</action>
</package>
</struts>
index.jsp File:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<h1>Hello World from Struts-2</h1>
<s:action name="helloWorldActionSupport" executeResult="true">
<label for="name">Please Enter Your Name: </label><br/>
<input type="text" name="name"/>
<input type="submit" value="Say Hello"/>
</s:action>
</body>
</html>
After I click on the submit button it doesn't proceed to the next page.
Use this code
<s:form action="helloWorldActionSupport" method="POST">
<label for="name">Please Enter Your Name: </label><br/>
<input type="text" name="name"/>
<input type="submit" value="Say Hello"/>
</s:form>
Related
I have the struts2 checkbox which behavior strangely when there are previous and next paging situation.
I have the three pages jsp named step1.jsp, step2.jsp and step3.jsp
I have the checkbox control on step1.jsp.
<s:checkbox value="%{loanForm.directmarketingCheckboxboolean}" name="loanForm.directmarketingCheckboxboolean"
style="vertical-align:middle;" id="directmarketingCheckbox" />
private boolean directmarketingCheckboxboolean;
public boolean isDirectmarketingCheckboxboolean() {
return directmarketingCheckboxboolean;
}
public void setDirectmarketingCheckboxboolean(boolean directmarketingCheckboxboolean) {
this.directmarketingCheckboxboolean = directmarketingCheckboxboolean;
}
Load step1.jsp and checked the checkbox in step1 and clicked next button. It goes to step2.jsp.
In step2.jsp, click previous button. It goes to step1.jsp.
The checkbox in step 1 is checked. Then I unchecked it and click
next button. It goes to step2.jsp.
In step2.jsp, click previous button. It goes to step1.jsp.
The checkbox in step1 is still checked. (It should show unchecked.
Right?).
first step
second time after next and previous
third time
According to the your request, I post my page (display_loan_step2) here:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# page contentType="text/html; charset=UTF-8"%>
<%# page import="java.util.*"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache, no-store");
response.setDateHeader("Expires", 0);
%>
<html>
<head>
<title>Loan Application Step 2</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<s:head />
<link rel="stylesheet" href="./js/bootstrap.min.css">
<script src="./js/jquery.min.js"></script>
<script src="./js/bootstrap.min.js"></script>
</head>
<body>
<s:form action="LoanFormResult3" namespace="/" theme="simple" cssClass="well form-search">
<p>
<s:checkbox value="%{loanForm.directmarketingCheckboxboolean}" name="loanForm.directmarketingCheckboxboolean"
style="vertical-align:middle;" id="directmarketingCheckbox" />
<s:text name="label.directmarketing.remark2" />
</p>
<s:url action="LoanFormResult.action" var="urlPrev" >
<s:param name="name">previous</s:param>
</s:url>
<s:a href="%{urlPrev}" cssClass="btn btn-primary" id="btnPrevious">Previous</s:a>
<s:submit key="submit" cssClass="btn btn-primary" id="btnNext" value="Next">
<s:hidden name="name" value="next"/>
</s:submit>
</s:form>
</body>
</html>
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>
<package name="cardAppPublic" extends="struts-default">
<action
name="LoanFormResult" method="displayPrevious" class="loanActionForm">
<result name="display_loan_step1">/WEB-INF/jsp/display_loan_step1.jsp</result>
</action>
<action
name="LoanFormResult2" method="display" class="loanActionForm">
<result name="display_loan_step2">/WEB-INF/jsp/display_loan_step2.jsp</result>
</action>
<action
name="LoanFormResult3" method="displayNext" class="loanActionForm">
<result name="display_loan_step3">/WEB-INF/jsp/display_loan_step3.jsp</result>
</action>
</package>
</struts>
Whole backend code:
public class LoanAction extends ActionSupport{
private LoanForm loanForm;
public LoanForm getLoanForm() {
return (LoanForm) ActionContext.getContext().getSession().get("loanForm");
}
public void setLoanForm(LoanForm loanForm) {
ActionContext.getContext().getSession().put("loanForm", loanForm);
}
public String display(){
return "display_loan_step2";
}
public String displayNext(){
return "display_loan_step3";
}
public String displayPrevious(){
return "display_loan_step1";
}
}
public class LoanForm extends ActionSupport{
private boolean directmarketingCheckboxboolean;
public boolean isDirectmarketingCheckboxboolean() {
return directmarketingCheckboxboolean;
}
public void setDirectmarketingCheckboxboolean(boolean directmarketingCheckboxboolean) {
this.directmarketingCheckboxboolean = directmarketingCheckboxboolean;
}
}
ApplicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="loanActionForm" class="com.struts.action.LoanAction" />
</beans>
I have created a simple program that gets the firstname and lastname of a user using a textfield. But the problem is that when I click the submit button I cannot redirect it to another jsp file which shows the firstname and lastname of the user.
Here's my HelloAction class:
package com.novamsc.training.struts.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport {
private String firstName;
private String lastName;
public String user(){
return "hello";
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String display(){
return "hi";
}
}
Here's my userInput.jsp file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Form</title>
</head>
<body>
<s:form name="inputData">
<s:textfield key="firstName"/>
<s:textfield key="lastName"/>
<s:submit/>
</s:form>
</body>
</html>
Here's my resultInput.jsp file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Get Result</title>
</head>
<body>
<p>
<s:property value="firstName" />
</p>
<p>
<s:property value="lastName" />
</p>
</body>
</html>
Here's my struts-traning.xml 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="hello" namespace="/exercise" extends="training-default">
<action name="userInput" class="com.novamsc.training.struts.action.HelloAction"
method="user">
<result name="hello">/jsp/userInput.jsp</result>
</action>
<action name="inputData" class="com.novamsc.training.struts.action.HelloAction"
method="display">
<result name="hi">/jsp/resultInput.jsp</result>
</action>
</package>
</struts>
You should use form tag with additional attributes that map the form to another action.
<s:form name="inputData" namespace="/exercise" action="submitData">
<s:textfield key="firstName"/>
<s:textfield key="lastName"/>
<s:submit/>
</s:form>
then for additional action you need to write action config
<action name="submitData" class="com.novamsc.training.struts.action.HelloAction"
method="save">
<result type="redirectAction">inputData</result>
</action>
add additional method to map the new action
public String save(){
return ActionSupport.SUCCESS;
}
This additional action is required to follow PRG (Post-Redirect-Get) pattern.
I am learning Upload interceptor now.
The document says, all upload files size exceeds the value of constant "struts.multipart.maxSize" will throw a exception in the background, and the view will go to INPUT view.
But, in my case,it can not throw any exception, and the view did not go to INPUT view(Upload progress has been 0% always,see the picture).
this is my upload html
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>HELLO!${session.user }</h1>
<div align="center">
<s:form method="post" enctype="multipart/form-data" action="upload">
<s:fielderror></s:fielderror>
<s:file label="上传文件" name="upload" />
<s:file label="上传文件" name="upload" />
<s:file label="上传文件" name="upload" />
<s:submit />
</s:form>
</div>
</body>
</html>
this is the code of my Action
package com.aks.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = -6671906825564499267L;
private static final int BUFFER_SIZE = 4096;
private List<File> upload;
private List<String> uploadFileName;
private List<String> uploadContentType;
private String savePath;
public String getSavePath() {
return ServletActionContext.getRequest().getServletContext().getRealPath(this.savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public List<File> getUpload() {
return upload;
}
public void setUpload(List<File> upload) {
this.upload = upload;
}
public List<String> getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
}
public List<String> getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(List<String> uploadContentType) {
this.uploadContentType = uploadContentType;
}
#Override
public String execute() throws Exception {
String newFileName = (UUID.randomUUID() + uploadFileName.get(0).substring(uploadFileName.get(0).lastIndexOf(".")));
System.out.println(newFileName);
System.out.println(getSavePath());
FileInputStream fis = new FileInputStream(upload.get(0));
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + newFileName);
System.out.println(getSavePath());
FileChannel fcIn = fis.getChannel();
FileChannel fcOut = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
while(true){
buffer.clear();
int r = fcIn.read(buffer);
if(r == -1){
break;
}
buffer.flip();
fcOut.write(buffer);
}
getUploadFileName().set(0, newFileName);
fcIn.close();
fcOut.close();
fis.close();
fos.close();
return SUCCESS;
}
}
this is the result html
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>显示上传图片</title>
</head>
<body>
<img src="upload/${uploadFileName['0']} " />
<s:debug></s:debug>
</body>
</html>
At last, this is the struts.xml of this action
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.multipart.maxSize" value="100000000" /> <!-- 20MB -->
<constant name="struts.multipart.saveDir" value="/temp" />
<package name="default" namespace="/" extends="struts-default">
<action name="index">
<result name="success">index.jsp</result>
</action>
<action name="login" class="com.aks.action.LoginAction">
<result name="input">index.jsp</result>
<result name="success">/WEB-INF/jsp/welcome.jsp</result>
<result name="error">/WEB-INF/jsp/error.jsp</result>
</action>
<action name="upload" class="com.aks.action.UploadAction">
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedTypes">image/png,image/jpeg,application/x-zip-compressed,application/octet-stream</param>
<param name="fileUpload.maximumSize">90000000</param>
</interceptor-ref>
<param name="savePath">/upload</param>
<result name="input">index.jsp</result>
<result name="success">/WEB-INF/jsp/showImage.jsp</result>
<result name="error">/WEB-INF/jsp/error.jsp</result>
</action>
</package>
<!-- Add packages here -->
</struts>
My development environment:
eclipse4.5.1+tomcat8+jdk1.8+struts2.3.24
Why can not throw exception,why not go to Input view?
This is a known problem, analyzed in this answer, and (as you can read in the update), it's been "patched" in Struts2 2.3.18.
Just upgrade to 2.3.24.1 and use jakarta-stream as Multipart parser.
I have created Struts 2 database application. In this one using Query I made Ajax call to the Struts 2 action. The problem is whenever I hit the submit button, it will trigger the Ajax call, but Ajax call is not properly hit the server action class URL. Every time I got 404 exception in browser. How to resolve this problem?
this is my js file :
$(document).ready(function(e){
$("#loginPage_emailid").blur(function () {
console.log("OnBlur() EmailId");
var emailId=$("#loginPage_emailid").val();
console.log("emailId ------- "+emailId);
if(emailId != null && emailId.length != 0 && typeof emailId != 'undefined' && emailId != "InvalidEmailId"){
FormValidator.prototype.validateEmailId(emailId);
}
else{
$("#loginPage_emailid").val("InvalidEmailId");
return false;
}
});
$("#loginPage_emailid").click(function () {
var emailId=$("#loginPage_emailid").val();
if( emailId == "InvalidEmailId"){
$("#loginPage_emailid").val("EmailID");
}
});
$("#loginPage_password").blur(function () {
var password=$("#loginPage_password").val();
if( password != "InvalidPassword"){
$("#loginPage_password").val("Password");
}
});
$("#loginPage_password").blur(function () {
var password=$("#loginPage_password").val();
console.log("password ------- "+password);
if(password != null && password.length != 0 && typeof password != 'undefined' && password != "InvalidPassword"){
FormValidator.prototype.validatePassword(password);
}
else{
$("#loginPage_password").val("InvalidPassword");
return false;
}
});
$("#loginPage_form").submit(function () {
console.log("Submit !!!!");
if(!FormValidator.prototype.isValidEmailId || !FormValidator.prototype.isValidPassword){
console.log("##$%^&#$%^&##%*##$%&*#^&*#$%&*($%&*(");
if(!FormValidator.prototype.isValidEmailId){
$("#loginPage_emailid").val("InvalidEmailId");
}
if(!FormValidator.prototype.isValidPassword){
$("#loginPage_password").val("InvalidPassword");
}
return false;
}
else{
console.log("Success full submit");
var jsonData={};
jsonData.emailId=FormValidator.prototype.emailId;
jsonData.password=FormValidator.prototype.password;
$.ajax({
type: "POST",
url: "login.action",
data: jsonData,
success: function(data){
console.log(""+data);
}
});
return false;
}
});
});
function FormValidator(){
var isValidEmailId=false;
var isValidPassword=false;
var emailId=null;
var password=null;
}
FormValidator.prototype.validateEmailId=function(emailId){
console.log("Email Id ===== "+emailId);
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (reg.test(emailId)){
FormValidator.prototype.isValidEmailId=true;
FormValidator.prototype.emailId=emailId;
}
};
FormValidator.prototype.validatePassword=function(password){
console.log("Password ===== "+password);
FormValidator.prototype.isValidPassword=true;
FormValidator.prototype.password=password;
};
loginpage.jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--[if lt IE 7 ]> <html lang="en" class="ie6 ielt8"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="ie7 ielt8"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html lang="en"><!--<![endif]--><head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/formvalidator.js"></script>
</head>
<body>
<div class="container">
<section id="content">
<!-- <s:form id="loginPage_form">
<div>
<s:textfield name ="emailid" label="EmailID" placeholder="EmailID" required="" id="loginPage_emailid" />
</div>
<div>
<s:password type="password" name ="password" label="Password" placeholder="Password" required="" id="loginPage_password" />
</div>
<div>
<s:submit value="Log in" />
</div>
</s:form> -->
<form id="loginPage_form" >
<h1>Login Form</h1>
<div>
<input type="text" placeholder="EmailID" required="" id="loginPage_emailid">
</div>
<div>
<input type="password" placeholder="Password" required="" id="loginPage_password">
</div>
<div>
<input type="submit" value="Log in"> Lost your password? Register
</div>
</form>
<div id="loginPage_errormessage" style="display: none;margin: 0px 0px;position: absolute;left: 47%;top: 79%;color: orangered;">emailid or password is invalid</div>
<!-- form -->
<div class="button" style="display: none;">
Download source file
</div>
<!-- button --> </section>
<!-- content -->
</div>
<!-- container -->
</body></html>
and this is my struts.xml 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>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.convention.default.parent.package" value="default"/>
<package name="default" extends="struts-default" namespace="/">
<action name="login" class="com.jamcracker.view.LoginAction" method="execute">
<result name="success">/jsp/dummy.jsp</result>
</action>
<!-- <action name="index">
<result>loginpage.jsp</result>
</action> -->
<!-- <action name="add"
class="com.jamcracker.view.ContactAction" method="add">
<result name="success" type="chain">index</result>
<result name="input" type="chain">index</result>
</action>
<action name="delete"
class="com.jamcracker.view.ContactAction" method="delete">
<result name="success" type="chain">index</result>
</action>
<action name="index"
class="com.jamcracker.view.ContactAction">
<result name="success">index.jsp</result>
</action> -->
</package>
</struts>
LoginAction.java class:
package com.jamcracker.view;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String emailId;
private String password;
public String getEmailId() {
return emailId;
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} }
There is no execute method in your LoginAction class, so AJAX call does not return any result. Try to add simple execute method:
public String execute() {
return SUCCESS;
}
404 is not an exception. It's an error code the Struts set to the response when no action found in the runtime configuration corresponding to the URL requested.
Because you didn't post a web.xml consider looking at Error 404 issues using Struts application.
Also check your library folder WEB-INF/lib for plugins you didn't use and remove them. Look at the issue at Struts2 - HTTP Status 404 - No result defined for action. You should post the stacktrace with exact error message however.
When calling an action from javascript code use s:url tag to build the action URL from the action mapping. See Jquery Error - While calling struts action.
The code you should change
$.ajax({
type: "POST",
url: '<s:url namespace="/" action="login"/>',
data: jsonData,
success: function(data){
console.log(""+data);
}
});
By the way if you are using struts2-jquery plugin there's a possibility to make ajax submit with <sj:submit> tag.
I have the following usecase that on Login a CustomerForm should be shown and a ListofCustomers which is retrieved from Database should be shown.
I have written the following code in Struts 2 but my getCustomerList() in CustomerAction is not getting called which is redirected during the Login action in struts.xml
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Struts 2 Entry Point is Filter -->
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
</web-app>
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.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="struts-default" namespace="/">
<interceptors>
<interceptor name="mylogging"
class="com.rahul.interceptor.MyLoggingInterceptor">
</interceptor>
<interceptor-stack name="loggingStack">
<interceptor-ref name="mylogging" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<action name="login" class="com.rahul.action.LoginAction">
<interceptor-ref name="loggingStack" />
<result type="redirect">/customer?method=getCustomersList</result>
<result name="success">Welcome.jsp</result>
<result name="error">Login.jsp</result>
</action>
<action name="customer" class="com.rahul.action.CustomerAction">
<interceptor-ref name="loggingStack" />
<result name="success">SuccessCustomer.jsp</result>
<result name="input">Customer.jsp</result>
</action>
</package>
</struts>
login.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts 2 - Login Application</title>
</head>
<body>
<h2>Struts 2 Login Application</h2>
<s:actionerror />
<s:form action="login" method="post">
<s:textfield name="username" key="label.username" size="20" />
<s:password name="password" key="label.password" size="20" />
<s:submit method="execute" key="label.login" align="center" />
</s:form>
</body>
</html>
loginAction.java:
package com.rahul.action;
public class LoginAction {
private String userName;
private String password;
public String execute() {
if (this.userName.equals("admin") && this.password.equals("admin123")) {
return "success";
} else {
return "error";
}
}
public String getUsername() {
return userName;
}
public void setUsername(String username) {
this.userName = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
CustomerAction.java:
package com.rahul.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class CustomerAction extends ActionSupport {
private String name;
private Integer age;
private String email;
private String telephone;
private List<String> customerList;
private String countryName;
public String getCountryName() {
System.out.println("getCountryName method");
countryName="India";
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String addCustomer() {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public List<String> getCustomerList() {
return customerList;
}
public void setCustomerList(List<String> customerList) {
this.customerList = customerList;
}
public String getCustomersList() {
System.out.println("Inside Customer List");
customerList = new ArrayList<String>();
customerList.add("Rahul");
customerList.add("Saurabh");
return SUCCESS;
}
}
welcome.jsp:
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>
Howdy,
<s:property value="username" />
...!
</h2>
<%#include file="Customer.jsp"%>
</body>
</html>
Customer.jsp:
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer Page</title>
</head>
<body>
<s:form action="customer.action" method="post" validate="true">
<s:textfield name="name" key="name" size="20" />
<s:textfield name="age" key="age" size="20" />
<s:textfield name="email" key="email" size="20" />
<s:textfield name="telephone" key="telephone" size="20" />
<s:submit method="addCustomer" key="label.add.customer" align="center" />
</s:form>
<s:property value="customerList" />
</body>
</html>
You can't pass a method as parameter name. This name is reserved for special parameter used by DMI and have a special syntax. First, if you want to use this parameter and DMI you should enable it.
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
then
<result type="redirect">/customer?method:getCustomersList</result>
Note, use a colon to specify a method name in parameter.
or use equivalent syntax
<result type="redirect">/customer!getCustomersList</result>
You might also wonder: Is a colon safe for friendly-URL use?
Also, don't use .action extension in the struts tags
<s:form namespace="/" action="customer" method="post" validate="true">
<s:textfield name="name" key="name" size="20" />
<s:textfield name="age" key="age" size="20" />
<s:textfield name="email" key="email" size="20" />
<s:textfield name="telephone" key="telephone" size="20" />
<s:submit method="addCustomer" key="label.add.customer" align="center" />
</s:form>
Note, the method attribute used by the struts tag to add a special parameter to the form url: method:addCustomer. This parameter only works with DMI. If you used namespace to the action configuration you should use it in the form tag as well.