Struts2 : Action's property setter is not invoked - java

I try to post a simple form :
<s:form action="register">
<s:textfield name="lastname"></s:textfield>
<s:submit></s:submit>
</s:form>
The action :
public class RegisterAction extends ActionSupport {
private String lastname;
public String execute() {
System.out.println("register");
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
The action outputs the register string but the setter is never called.
Why the setter is never called ?
Even when I type directly the action in the browser http://localhost:8686/register.action?lastname=sdjh the setter is not invoked but the execute method outputs "register".

I don't see any missing parts in your code. I tried to replicate the same and I found it's working perfectly. Following is my code.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<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>
</web-app>
struts.xml
<?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" />
<package name="default" namespace="/" extends="struts-default">
<action name="register" class="com.tmp.RegisterAction">
<result>one.jsp</result>
</action>
</package>
</struts>
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" 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">
</head>
<body>
<s:form action="register">
<s:textfield name="lastname"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
RegisterAction
package com.tmp;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport {
private static final long serialVersionUID = 1L;
String lastname;
public String getLastname() {
return lastname;
}
public void setLastname( String lastname ) {
this.lastname = lastname;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return Action.SUCCESS;
}
}
one.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
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">
</head>
<body>
<s:property value="lastname"/>
</body>
</html>

Related

Cannot redirect a JSP file and display values using Struts 2

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.

Error of Null Pointer Exception in java using struts [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to retrieve data from database but i am getting Null Pointer Exception in struts.I am using ecllipse mars.
Thanks in advance
My files are:-
web.xml
enter code here
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Report2</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.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="myapp" />
<package name="default" extends="struts-default" namespace="/">
<action name="database" class="genius.database.ReportAction"
method="execute">
<result name="Success">/ReportView.jsp</result>
</action>
</package>
</struts>
ReportAction.java
package genius.database;
import java.sql.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import genius.database.Student;
public class ReportAction{
HttpServletRequest request=null;
public String execute() throws SQLException,ClassNotFoundException {
Connection con;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/registertable?
zeroDateTimeBehavior=convertToNull","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
List<Student> li=null;
li=new ArrayList<Student>();
while(rs.next()){
Student st=new Student();
st.setRno(rs.getInt(1));
st.setName(rs.getString(2));
st.setEng(rs.getInt(3));
st.setMaths(rs.getInt(4));
li.add(st);
}
request.setAttribute("disp", li);
return "Success";
}
}
Student.java
package genius.database;
public class Student {
private int rno;
private String name;
private int eng;
private int mat;
public int getRno() {
return rno;
}
public void setRno(int rno) {
this.rno = rno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public int getMaths() {
return mat;
}
public void setMaths(int mat) {
this.mat = mat;
}
}
ReportView.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<%#page language="java" import="java.util.*" %>
<%#page language="java" import="genius.database.Student" %>
<%#page language="java" import="genius.database.ReportAction" %>
<!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>Insert title here</title>
</head>
<body>
<h2>Report</h2>
<s:actionerror key="error.Insert"/>
<s:form name="form" method="post">
<table border="1">
<thead>
<tr>
<td>Roll No</td>
<td>Name</td>
<td>Eng</td>
<td>Maths</td>
</tr>
</thead>
<tbody>
<tr>
<%
List<Student> li=(List<Student>)request.getAttribute("disp");
out.println(li);
if(li==null){
Iterator<Student> it=li.iterator();
while(it.hasNext()){
Student st=(Student)it.next();
int rno=st.getRno();
String name=st.getName();
int eng=st.getEng();
int mat=st.getMaths();
%>
<td><%out.println(rno);%></td>
<td><%out.println(name);%></td>
<td><%out.println(eng);%></td>
<td><%out.println(mat);%></td>
<% }
}
%>
</tr>
</tbody>
</table>
</s:form>
</body>
</html>
index.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>Report</title>
</head>
<body>
<s:form action="database.action">
<s:submit value="Submit"></s:submit>
</s:form>
</body>
</html>
You probably mean:
if (li!=null)
From
if(li==null){
Iterator<Student> it=li.iterator();
while(it.hasNext()){
Student st=(Student)it.next();
int rno=st.getRno();
String name=st.getName();
int eng=st.getEng();
int mat=st.getMaths();
Not sure if that's it, but that will definitely cause a NullPointerException.
Better to use JSTL rather than scriplets in you JSP
e.g.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
....
<c:forEach items="${disp}" var="student" >
${student.rno}
${student.name}
</c:forEach>
see https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm

Struts2 upload over max size but it can not throw any exception

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.

Content-Type not allowed: fileUpload in Struts 2

I am new to Struts 2 and trying to do use fileUpload interceptor. I am attaching all my code layers
Action Class (FileUploadAction):
package com.caveofprogramming.actions;
import java.io.File;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
public String getFileUploadContentType() {
return fileUploadContentType;
}
public void setFileUploadContentType(String fileUploadContentType) {
this.fileUploadContentType = fileUploadContentType;
}
public String getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
#Action( value = "/fileUpload",
results={#Result(name="success",location="/success.jsp"),
#Result(name="error",location="/error.jsp"),
#Result(name="input",location="/error.jsp")
},
interceptorRefs={
#InterceptorRef(
params={"allowedTypes","image/jpeg,image/jpg,application/zip",
"maximumSize","1024000"},
value="fileUpload"
),
#InterceptorRef("defaultStack"),
#InterceptorRef("validation")
}
)
public String execute(){
try{
return SUCCESS;
} catch(Exception e){
return ERROR;
}
}
public String display() {
return NONE;
}
}
error.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<s:fielderror/>
</body>
</html>
Success.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">
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Success
</body>
</html>
fileUpload.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
<body>
<h1>Struts 2 <s:file> file upload example</h1>
<s:form method="post" enctype="multipart/form-data" action="fileUpload">
<s:file label="File One" name="fileUpload" />
<s:submit />
</s:form>
</body>
</html>
I am not understanding why I am getting this error
"Content-Type not allowed: fileUpload "photography-104a.jpg" "upload_37fbf440_169b_4687_af65_93c8c967256c_00000000.tmp" image/pjpeg"
Although my uploading file format is .jpg.
You are getting this error probably because you don't allow files with content type image/pjpeg. Use parameter of fileUpload interceptor to define allowed MIME types
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/pjpeg</param>
</interceptor-ref>

Action redirect is not working with list attribute after login in Struts 2

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.

Categories

Resources