Variable cannot be resolved error in struts2 - struts2

My requirement is am trying to populate pid(projectid) from project table and name from userdetails table as an drop down for a form.Am new to struts framework. Could someone please throw us some light on this issue please.
Here is the code:
sprintform.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<?xml version="1.0" encoding="UTF-8" ?>
<!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>
<link href="css/jquery.ui.datepicker.css" rel="stylesheet"
type="text/css" />
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.17.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){$('.dateTxt').datepicker({
dateFormat : 'yy-mm-dd'
}); });
</script>
</head>
<body>
<h1 style="color: green">Sprint</h1>
<s:form action="sprintInsert" namespace="/" method="post"
name="sprintForm" theme="xhtml">
<s:textfield name="title:" size="40" maxlength="40" required="true"
label="Title" />
<p>
Begin Date: <input id="one" class="dateTxt" type="text"
name="begindate" />
</p>
<p>
End Date: <input id="two" class="dateTxt" type="text" name="enddate" />
</p>
<s:select label="ProjectId" headerKey="-1"
headerValue="Select Project Id" list="projectidList" name="pid" />
<%-- <s:select label="Owner" headerKey="-1"
headerValue="Select Sprint Owner" list="sprintownerList"
name="sprintowner" /> --%>
<tr>
<td>State:</td>
<td><select name="state">
<option value="">Choose a state..</option>
<option value="A">Active</option>
<option value="F">Future</option>
<option value="C">Close</option>
</select></td>
</tr>
<s:textfield name="targetestimatedpoints" size="40" maxlength="40"
required="true" label="Target Estimate pts:" />
<s:textfield name="totalestimatedpoints" size="40" maxlength="40"
required="true" label="Total Estimate pts:" />
<s:textfield name="totaldefaultestimatedhours" size="40"
maxlength="40" required="true" label="Total Detail Estimate Hrs: " />
<s:textfield name="todohours:" size="40" maxlength="40"
required="true" label="Total To Do Hrs:" />
<s:textfield name="description: :" size="40" maxlength="40"
required="true" label="Description: " />
<tr align="right">
<td><div align="center">
<input type="submit" value="save">
</div>
<td align="center"><input type="reset" value="Reset"></td>
</tr>
</s:form>
<s:if test="hasActionErrors()">
<div id="fieldErrors">
<s:actionerror />
</div>
</s:if>
</body>
</html>
SprintAction.java:
package com.bits.sprintanalyzer.action;
import java.util.List;
import org.apache.log4j.Logger;
import com.bits.sprintanalyzer.ResourceException;
import com.bits.sprintanalyzer.dao.SprintDAO;
import com.opensymphony.xwork2.ActionSupport;
public class SprintAction extends ActionSupport {
private static final Logger LOG = Logger.getLogger(SprintAction.class);
/**
*
*/
private static final long serialVersionUID = -6257623073537028210L;
private String title;
private String begindate;
private String enddate;
private String pid;
private String sprintowner;
private String state;
private int targetestimatedpoints;
private int totalestimatedpoints;
private int totaldefaultestimatedhours;
private int todohours;
private String description;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getSprintowner() {
return sprintowner;
}
public void setSprintowner(String sprintowner) {
this.sprintowner = sprintowner;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getTargetestimatedpoints() {
return targetestimatedpoints;
}
public void setTargetestimatedpoints(int targetestimatedpoints) {
this.targetestimatedpoints = targetestimatedpoints;
}
public int getTotalestimatedpoints() {
return totalestimatedpoints;
}
public void setTotalestimatedpoints(int totalestimatedpoints) {
this.totalestimatedpoints = totalestimatedpoints;
}
public int getTotaldefaultestimatedhours() {
return totaldefaultestimatedhours;
}
public void setTotaldefaultestimatedhours(int totaldefaultestimatedhours) {
this.totaldefaultestimatedhours = totaldefaultestimatedhours;
}
public int getTodohours() {
return todohours;
}
public void setTodohours(int todohours) {
this.todohours = todohours;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String display() throws Exception {
return INPUT;
}
public String getBegindate() {
return begindate;
}
public void setBegindate(String begindate) {
this.begindate = begindate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getpidList() throws ResourceException {
return SprintDAO.getpidList();
}
public List<String> getOwnerList() throws ResourceException {
return SprintDAO.getOwnerList();
}
#Override
public void validate() {
}
#Override
public String execute() throws Exception {
LOG.info("title" + title);
LOG.info("begindate" + begindate);
LOG.info("enddate" + enddate);
LOG.info("pid" + pid);
LOG.info("sprintowner" + sprintowner);
LOG.info("state" + state);
LOG.info("targetestimatedpoints" + targetestimatedpoints);
LOG.info("totalestimatedpoints" + totalestimatedpoints);
LOG.info("totaldefaultestimatedhours" + totaldefaultestimatedhours);
LOG.info("todohours" + todohours);
LOG.info("description" + description);
// ProjectDAO.insert(projectname,description,scrummaster,productowner,begindate,enddate);
int i = SprintDAO.save(this);
if (i > 0) {
return "success";
}
return "error";
}
}
SprintDAO:
package com.bits.sprintanalyzer.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.bits.sprintanalyzer.ResourceException;
import com.bits.sprintanalyzer.action.SprintAction;
import com.bits.sprintanalyzer.util.ConnectionUtil;
public class SprintDAO {
private static final String PROJECTQUERY = "select pid from project";
private static final String USERQUERY = "select name from userdetail";
public static List<String> getpidList() throws ResourceException{
List<String> projectidList = new ArrayList<String>();
// this should be populated from DB
try (Connection con = ConnectionUtil.INSTANCE.getConnection();
PreparedStatement st = con.prepareStatement(PROJECTQUERY)){
ResultSet rs =st.executeQuery();
while(rs.next()){
projectidList.add(rs.getString(1));
}
return projectidList;
}
catch (SQLException | ResourceException e) {
throw new ResourceException("Failed to validate project id", e);
}
}
public static List<String> getOwnerList() throws ResourceException{
List<String> sprintownerList = new ArrayList<String>();
// this should be populated from DB
try (Connection con = ConnectionUtil.INSTANCE.getConnection();
PreparedStatement st = con.prepareStatement(USERQUERY)){
ResultSet rs =st.executeQuery();
while(rs.next()){
sprintownerList.add(rs.getString(1));
}
return sprintownerList;
}
catch (SQLException | ResourceException e) {
throw new ResourceException("Failed to validate productowner", e);
}
}
//insert into database
public static int save(SprintAction SA) throws Exception{
int status=0;
try{
Connection con = ConnectionUtil.INSTANCE.getConnection();
PreparedStatement ps = con.prepareStatement("insert into sprint(pid,title,begindate,enddate,owner,state,targetestimatedpoints,totalestimatedpoints,totaldefaultestimatedhours,todohours,description) values(?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, SA.getPid());
ps.setString(2, SA.getTitle());
ps.setString(3, SA.getBegindate());
ps.setString(4, SA.getEnddate());
ps.setString(5, SA.getSprintowner());
ps.setString(6, SA.getState());
ps.setInt(7, SA.getTargetestimatedpoints());
ps.setInt(8, SA.getTotalestimatedpoints());
ps.setInt(9, SA.getTotaldefaultestimatedhours());
ps.setInt(10, SA.getTodohours());
ps.setString(11, SA.getDescription());
status=ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();}
return status;
}
}
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"/WEB-INF/classes/struts-2.1.7.dtd">
<struts>
<!--
You could also set the constants in the struts.properties file
placed in the same directory as struts.xml
-->
<constant name="struts.devMode" value="true" />
<package name="sprintanalyzer" extends="struts-default" namespace="/">
<!--
If no class attribute is specified the framework will assume success and
render the result index.jsp
If no name value for the result node is specified the success value is the default
-->
<action name="">
<result>/jsp/login.jsp</result>
</action>
<!--
If the URL is hello.action then call the execute method of class HelloWorldAction.
If the result returned by the execute method is success render the HelloWorld.jsp
-->
<action name="login" class="com.bits.sprintanalyzer.action.LoginAction"
method="execute">
<result name="success">/jsp/sprintanalyzer.jsp</result>
<result name="input">/jsp/login.jsp</result>
</action>
<action name="projectform" class="com.bits.sprintanalyzer.action.ProjectAction"
method="display">
<result name="input">/jsp/projectform.jsp</result>
</action>
<action name="projectInsert" class="com.bits.sprintanalyzer.action.ProjectAction"
method="execute">
<result name="success">/jsp/sprintanalyzer.jsp</result>
</action>
<action name="sprintform" class="com.bits.sprintanalyzer.action.SprintAction"
method="display">
<result name="input">/jsp/sprintform.jsp</result>
</action>
<action name="sprintInsert" class="com.bits.sprintanalyzer.action.SprintAction"
method="execute">
<result name="success">/jsp/sprintanalyzer.jsp</result>
</action>
</package>
</struts>
Issue is coming from both projectidlist and sprintownerList. Please advise accordingly.
Please find below stacktrace:
2016-10-01T18:23:38.916+0530|Info: 2016-10-01 18:23:38,916 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The first TextProvider in the ValueStack (com.opensymphony.xwork2.ActionSupport) could not locate the message resource with key 'Login'
2016-10-01T18:23:38.917+0530|Info: 2016-10-01 18:23:38,917 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The default value expression 'Login' was evaluated and did not match a property. The literal value 'Login' will be used.
2016-10-01T18:23:38.925+0530|Info: 2016-10-01 18:23:38,924 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The first TextProvider in the ValueStack (com.opensymphony.xwork2.ActionSupport) could not locate the message resource with key 'Login'
2016-10-01T18:23:38.925+0530|Info: 2016-10-01 18:23:38,925 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The default value expression 'Login' was evaluated and did not match a property. The literal value 'Login' will be used.
2016-10-01T18:23:57.121+0530|Info: 2016-10-01 18:23:57,120 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The first TextProvider in the ValueStack (com.opensymphony.xwork2.ActionSupport) could not locate the message resource with key 'Login'
2016-10-01T18:23:57.121+0530|Info: 2016-10-01 18:23:57,121 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The default value expression 'Login' was evaluated and did not match a property. The literal value 'Login' will be used.
2016-10-01T18:23:57.128+0530|Info: 2016-10-01 18:23:57,128 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The first TextProvider in the ValueStack (com.opensymphony.xwork2.ActionSupport) could not locate the message resource with key 'Login'
2016-10-01T18:23:57.129+0530|Info: 2016-10-01 18:23:57,128 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The default value expression 'Login' was evaluated and did not match a property. The literal value 'Login' will be used.
2016-10-01T18:24:03.841+0530|Severe: Sat Oct 01 18:24:03 IST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2016-10-01T18:24:04.022+0530|Info: 2016-10-01 18:24:04,021 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The first TextProvider in the ValueStack (com.bits.sprintanalyzer.action.LoginAction) could not locate the message resource with key 'welcome to Sprint Analyzer Tool'
2016-10-01T18:24:04.022+0530|Info: 2016-10-01 18:24:04,022 WARN org.apache.struts2.util.TextProviderHelper.warn:45 - The default value expression 'welcome to Sprint Analyzer Tool' was evaluated and did not match a property. The literal value 'welcome to Sprint Analyzer Tool' will be used.
2016-10-01T18:24:06.835+0530|Warning: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'pid': The requested list key 'projectidList' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:237)
at org.apache.struts2.components.Component.findValue(Component.java:358)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:80)
at org.apache.struts2.components.Select.evaluateExtraParams(Select.java:105)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:856)
at org.apache.struts2.components.UIBean.end(UIBean.java:510)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.jsp.sprintform_jsp._jspx_meth_s_select_0(sprintform_jsp.java:236)
at org.apache.jsp.jsp.sprintform_jsp._jspx_meth_s_form_0(sprintform_jsp.java:144)
at org.apache.jsp.jsp.sprintform_jsp._jspService(sprintform_jsp.java:88)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:875)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:739)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:575)
at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:546)
at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:428)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:378)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:154)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptorcom.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
2016-10-01T18:24:06.844+0530|Warning: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'pid': The requested list key 'projectidList' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:237)
at org.apache.struts2.components.Component.findValue(Component.java:358)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:80)
at org.apache.struts2.components.Select.evaluateExtraParams(Select.java:105)
org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:739)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:575)
at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:546)
at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:428)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:378)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:154)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
at
Here is the login code:
package com.bits.sprintanalyzer.action;
import org.apache.log4j.Logger;
import com.bits.sprintanalyzer.ResourceException;
import com.bits.sprintanalyzer.dao.LoginDAO;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private static final Logger LOG = Logger.getLogger(LoginAction.class);
/**
*
*/
private static final long serialVersionUID = 6877145894906143530L;
private String username;
private String password;
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;
}
#Override
public void validate(){
if (username==null || username.length()==0 || password ==null || password.length() ==0 )
addActionError(getText("User name or Password cannot be null"));
}
#Override
public String execute() throws Exception {
try{
if( LoginDAO.isValidUser(username, password) ){
return SUCCESS;
}
else
{
addActionError(getText("Invalid Username or Password"));
}
}catch(ResourceException e){
LOG.error("Failed to valid User", e);
addActionError(getText("Something Went wrong with DBConnection"));
}
return INPUT;
}
}
Latest stacktrace after changing connection string:
2016-10-01T18:55:04.396+0530|Warning: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'pid': The requested list key 'projectidList' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:237)
at org.apache.struts2.components.Component.findValue(Component.java:358)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:80)
at org.apache.struts2.components.Select.evaluateExtraParams(Select.java:105)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:856)
at org.apache.struts2.components.UIBean.end(UIBean.java:510)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at va:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)

1) You have MySQL connection exception as below:
Establishing SSL connection without server's identity verification is not recommended.
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.
To resolve this use the connection string like below:(change the db name to your existing db name)
jdbc:mysql://localhost:3306/dbname?autoReconnect=true&useSSL=false
This needs to be sorted first, that's why the values of the variables are not been rendered
2) In the Latest trace the requested list key 'projectidList' could not be resolved as a collection/array/map/enumeration/iterator type.
This error occurs when you try to access a list/collection which haven't been created.
Try to initialize the collection objects List<String> projectidList at class level.
when particular action is triggered at that time, JSP page is not knowing the the type of field, in this case, when you write List<String> projectidList = new ArrayList<String>(); instead of this, change it to ArrayList projectidList = new ArrayList();.
Make sure that you access list after the action class is instantiated i.e. corresponding action is called.
If you want to directly access it before calling action make it static and access it inside jsp.

Related

File upload not working with Struts2 Model-Driven Interface

When I am using Model driven interface, my file upload operation is not working.
It is not popping any error, nor it is generating any log.
My code is attached hereby,
I want to know for file, do we have to generate its getters/setters in Model or Action with Model-Driven interface.
Atleast it should get uploaded to temp folder, as with struts by default uploads to temp.
Action
ProductAction.java
package com.fileupload.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.fileupload.model.FileUploadModel;
/**
* Action class to requests
* #package com.fileupload.action
*/
public class FileUploadAction extends ActionSupport implements ModelDriven<Object>{
FileUploadModel fileModel = new FileUploadModel();
#Override
public Object getModel() {
return fileModel;
}
}
Model ProductModel.java
package com.fileupload.model;
import java.io.File;
/**
* Model class to handle data
* #package com.fileupload.model
*/
public class FileUploadModel {
private String employeeName;
private File image;
private String imageFileName;
private String imageFileCotentType;
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getImageFileCotentType() {
return imageFileCotentType;
}
public void setImageFileCotentType(String imageFileCotentType) {
this.imageFileCotentType = imageFileCotentType;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
Configuration struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"/>
<package name="FileUploadStruts" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="submitForm" class="com.fileupload.action.FileUploadAction">
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
View CreateProduct.jsp
<%--
Document : index
Created on : Nov 26, 2017, 12:50:38 PM
Author : owner
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File upload example</title>
</head>
<body>
<h1>Fill the form below</h1>
<s:form action="submitForm" enctype="multipart/form-data" name="employeeform">
<s:textfield name="employeeName"/>
<s:file name="image"/>
<s:submit value="Submit"/>
</s:form>
</body>
</html>
Of,course,your file upload operation can working When you using Model
driven interface but you made a few mistake:
public class FileUploadModel {
private String employeeName;
private File image;
private String imageFileName;
// YourCode was wrong : private String imageFileCotentType;
private String imageFileContentType;
(get set)...
And then,you need to add a piece of code to your code for upload like
this:
#Namespace("/")
#ParentPackage("struts-default")
public class FileUploadAction extends ActionSupport implements ModelDriven<FileUploadModel> {
private static final long serialVersionUID = 1L;
FileUploadModel fileModel = new FileUploadModel();
#Override
public FileUploadModel getModel() {
return fileModel;
}
#Action(value = "submitForm", results = {
#Result(name = "success", location = "/result.jsp") })
public String submitForm() {
HttpServletRequest request = ServletActionContext.getRequest();
String tomcatPath = ServletActionContext.getServletContext().getRealPath("/");
String projectName = request.getContextPath();
projectName = projectName.substring(1);
String filePath = tomcatPath.substring(0, tomcatPath.indexOf(projectName)) + "uploadFile";
File dest = new File(filePath, fileModel.getImageFileName());
try {
FileUtils.copyFile(fileModel.getImage(), dest);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
if you implements the function based on my answer,please reply to
me,smile.

displaytag not working with struts 2 use tiles

In my application using struts 2 framework and tiles.
Now, I want to use displaytag to display the data in a database table. I did the following:
in my struts.xml:
<action name="users_admin" class="com.controller.admin.UserAction">
<interceptor-ref name="checkSession" />
<result name="login">/login.jsp</result>
<result type="tiles" name="none">/users_admin.tiles</result>
</action>
In file UserAction:
public class UserAction extends ActionSupport{
private List<Users> listUsers;
private String myActionName;
public String getMyActionName() {
return myActionName;
}
public void setMyActionName(String myActionName) {
this.myActionName = myActionName;
}
public List<Users> getListUsers() {
return listUsers;
}
public void setListUsers(List<Users> listUsers) {
this.listUsers = listUsers;
}
#Override
public String execute() throws Exception {
listUsers = UserServices.selectAll();
return NONE;
}
}
And In file user_admin.jsp(file use in tiles):
<s:actionerror cssStyle="color:red"/>
<div class="well">
<display:table name="listUsers" id="listUsers" requestURI="/UserAction" cellpadding="5px;"
cellspacing="5px;" style="margin-left:50px;margin-top:20px;">
<display:column property="EMAIL" title="Email"/>
<display:column property="NAME" title="Name"/>
</display:table>
</div>
File user model:
package com.model;
public class Users {
private String EMAIL;
private String NAME;
public String getEMAIL() {
return EMAIL;
}
public void setEMAIL(String EMAIL) {
this.EMAIL = EMAIL == null ? null : EMAIL.trim();
}
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME == null ? null : NAME.trim();
}
}
When I run the application error occurs in apache tomcat log
org.apache.catalina.core.ApplicationDispatcher.invoke Servlet.service() for servlet jsp threw exception
java.lang.ClassNotFoundException: org.apache.commons.collections.IteratorUtils
Who can help me point out why the error, in the solution to overcome it?
Add commons-collections-3.1.jar to your libraries.
Note that you are using only one Interceptor, unless checkSession is the name of your stack.
EDIT
Interceptor checkSession to check my log on the website. How should I use.
You can define a custom interceptor stack, and then reference it, or include your custom interceptor AND another stack (for example, the default one) for a single action, like this:
<action name="users_admin" class="com.controller.admin.UserAction">
<interceptor-ref name="checkSession" />
<interceptor-ref name="defaultStack" />
<result name="login">/login.jsp</result>
<result type="tiles" name="none">/users_admin.tiles</result>
</action>

Could not access bean in action Struts2

I have index.jsp where I have one link,on clicking on that link that page specific action gets called.Now as on the click of this link,I need to display a page with already populated multiselect list along with few input text fields,in the constructor of the action I populated the TransactionBean which will be bound with fields on next page i.e transactionData.jsp.
The transactionData.jsp page is getting displayed correctly with populated multiselected list.Now user can select values from multiselect list and can enter dates in text field and will click on click button,so that a bar chart is displayed.
On click on Click button ,I am calling another action ,which also has TransactionBean as its property.In the execute method of this action, I am trying to access transactionbean with its getter but it gives me NullPointerException. I got to know that, if we are submitting a page which has fields of bean binded ,then on calling action,bean will be instantiated automatically through interceptors but seems like something is not correct here.
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>
<title>Hello World</title>
</head>
<body>
<s:form action="displayAction.action">
<h1>Hello World</h1>
Transaction Chart
</s:form>
</body>
</html>
DisplayAction.java
package com.tutorialspoint.struts2;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class DisplayAction extends ActionSupport {
TransactionBean transactionBean;
public TransactionBean getTransactionBean() {
return transactionBean;
}
public void setTransactionBean(TransactionBean transactionBean) {
this.transactionBean = transactionBean;
}
public String execute() {
return SUCCESS;
}
public DisplayAction() {
System.out.println("Inside Constructor");
List<String> leftChannelsList = new ArrayList<String>();
leftChannelsList.add("Channel1");
leftChannelsList.add("Channel2");
//TransactionBean transactionBean = new TransactionBean();
setTransactionBean(new TransactionBean());
getTransactionBean().setLeftChannelsList(leftChannelsList);
//Transaction Type Dta
List<String> leftTransTypesList = new ArrayList<String>();
leftTransTypesList.add("TransType1");
leftTransTypesList.add("TransType2");
getTransactionBean().setLeftTransTypesList(leftTransTypesList);
}
}
transactionData.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>
<s:head theme="ajax" debug="true"/>
<title>Hello World</title>
</head>
<body bgcolor="grey">
<s:form action="displayChart.action">
<s:datetimepicker label="Select From" name="transactionBean.fromDate" displayFormat="MM-dd-yy" required="true" /> <s:datetimepicker label="Select To" name="transactionBean.toDate" displayFormat="MM-dd-yy" required="true" />
<s:optiontransferselect
label="Channels"
name="transactionBean.leftChannels"
leftTitle="Unselected Channels"
rightTitle="Selected Channels"
list="transactionBean.leftChannelsList"
multiple="true"
headerKey="-1"
doubleList="transactionBean.rightChannelsList"
doubleName="transactionBean.rightChannels"
doubleHeaderKey="-1"
doubleHeaderValue="Please Select"/>
<!-- Transaction Types -->
<s:optiontransferselect
label="transaction Types"
name="transactionBean.leftTransTypes"
leftTitle="Unselected Transaction Type"
rightTitle="Selected Transaction Type"
list="transactionBean.leftTransTypesList"
multiple="true"
headerKey="-1"
doubleList="transactionBean.rightTransTypesList"
doubleName="transactionBean.rightTransTypes"
doubleHeaderKey="-1"
doubleHeaderValue="Please Select"/>
<s:submit value="click" align="center"/>
</s:form>
</body>
</html>
JfreeChartAction.java
public class JfreeChartAction extends ActionSupport {
private JFreeChart chart;
private TransactionBean transactionBean;
private TransactionDao transactionDao;
public TransactionDao getTransactionDao() {
return transactionDao;
}
public void setTransactionDao(TransactionDao transactionDao) {
this.transactionDao = transactionDao;
}
public TransactionBean getTransactionBean() {
return transactionBean;
}
public void setTransactionBean(TransactionBean transactionBean) {
this.transactionBean = transactionBean;
}
// This method will get called if we specify <param name="value">chart</param>
public JFreeChart getChart() {
return chart;
}
public void setChart(JFreeChart chart) {
this.chart = chart;
}
public JfreeChartAction() {}
public String execute() throws Exception {
System.out.println("Inside Execute: Start");
System.out.println("From date:" + getTransactionBean().getFromDate());
System.out.println("From date:" + getTransactionBean().getToDate());
System.out.println("leftChannelsList:" + getTransactionBean().getLeftChannelsList());
System.out.println("Left Trans type List" + getTransactionBean().getLeftTransTypesList());
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
dataSet.setValue(0, "01-04-2014", "Channel1");
dataSet.setValue(15000, "01-04-2014", "Channel2");
dataSet.setValue(9000, "01-05-2014", "Channel1");
dataSet.setValue(1500, "01-05-2014", "Channel2");
dataSet.setValue(10000, "01-06-2014", "Channel1");
dataSet.setValue(8000, "01-06-2014", "Channel2");
chart = ChartFactory.createBarChart(
"Demo Bar Chart", //Chart title
"Mobile Manufacturer", //Domain axis label
"TRANSACTIONS", //Range axis label
dataSet, //Chart Data
PlotOrientation.VERTICAL, // orientation
true, // include legend?
true, // include tooltips?
false // include URLs?
);
chart.setBorderVisible(true);
System.out.println("Inside Execute: End");
return SUCCESS;
}
}
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="default" namespace="/" extends="struts-default">
<action name="displayAction"
class="com.tutorialspoint.struts2.DisplayAction"
method="execute">
<result name="success">transactionsData.jsp</result>
</action>
</package>
<package name="defaultJfreeChart" namespace="/" extends="jfreechart-default">
<action name="displayChart"
class="com.tutorialspoint.struts2.JfreeChartAction"
method="execute">
<result name="success" type="chart">
<param name="value">chart</param>
<param name="type">jpeg</param>
<param name="width">600</param>
<param name="height">400</param>
</result>
</action>
</package>
</struts>
TransactionBean.java
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jfree.chart.JFreeChart;
public class TransactionBean {
private Date dateTime;
private Integer volume;
private String leftChannels;
private String rightChannels;
private String toDate;
private String fromDate;
private List<String> leftChannelsList;
private List<String> rightChannelsList;
//Transaction type data
private String leftTransTypes;
private List<String> leftTransTypesList;
private String rightTransTypes;
private List<String> rightTransTypesList;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public Integer getVolume() {
return volume;
}
public void setVolume(Integer volume) {
this.volume = volume;
}
public TransactionBean(){
//System.out.println("Inside TransactionBean constructor");
}
public String getLeftTransTypes() {
return leftTransTypes;
}
public void setLeftTransTypes(String leftTransTypes) {
this.leftTransTypes = leftTransTypes;
}
public List<String> getLeftTransTypesList() {
return leftTransTypesList;
}
public void setLeftTransTypesList(List<String> leftTransTypesList) {
this.leftTransTypesList = leftTransTypesList;
}
public String getRightTransTypes() {
return rightTransTypes;
}
public void setRightTransTypes(String rightTransTypes) {
this.rightTransTypes = rightTransTypes;
}
public List<String> getRightTransTypesList() {
return rightTransTypesList;
}
public void setRightTransTypesList(List<String> rightTransTypesList) {
this.rightTransTypesList = rightTransTypesList;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public String getLeftChannels() {
return leftChannels;
}
public void setLeftChannels(String leftChannels) {
this.leftChannels = leftChannels;
}
public String getRightChannels() {
return rightChannels;
}
public void setRightChannels(String rightChannels) {
this.rightChannels = rightChannels;
}
public List<String> getRightChannelsList() {
return rightChannelsList;
}
public void setRightChannelsList(List<String> rightChannelsList) {
this.rightChannelsList = rightChannelsList;
}
public List<String> getLeftChannelsList() {
return leftChannelsList;
}
public void setLeftChannelsList(List<String> leftChannelsList) {
this.leftChannelsList = leftChannelsList;
}
}
can you please let me know which version should be used.
Always use the latest version. At the moment it's Struts 2.3.16.3 GA. You can also see Version Notes and Migration Guide.

Input values from jsp are null in Struts action class. How to access the registration form input values in Action class

Registration.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<%# taglib uri="/struts-tags" prefix="s"%>
<s:form action="getRegistered.action" method="post" validate="true">
<div>
<table>
<s:textfield label="First Name" key="firstname" />
<s:textfield label="Last Name" key="lastname" />
<s:password label="Create your password" key="regpassword" />
<s:password label="Confirm your password" key="conpassword" />
<s:textfield label="Email" key="regemail1" />
<s:textfield label="Re-Type Email" key="conemail" />
<s:textfield label="Phone" key="phone" />
<tr>
<td><s:submit value="Register" theme="simple"/></td>
<td><s:submit value="Cancel" theme="simple" onclick="document.forms[0].action='login.jsp';" /></td>
</tr>
</table>
</div>
</s:form>
</center>
</body>
</html>
I'm passing the register input values to Action class.
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="default" extends="struts-default">
<action name="getLogin" class="login.action.LoginAction"
method="login">
<result name="success">/Success.jsp</result>
<result name="input">/LoginError.jsp</result>
</action>
<action name="getRegistered" class="login.action.LoginAction"
method="register">
<interceptor-ref name="validation">
<param name="excludeMethods">register</param>
</interceptor-ref>
<result name="success">/Success.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
This is the struts xml
LoginAction.java:
package login.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
import login.service.LoginDao;
import login.service.RegisterDao;
#SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
private String username;
private String password;
private HttpServletRequest httpServletRequest;
private String firstname;
private String lastname;
private String regpassword;
private String conpassword;
private String regemail;
private String conemail;
private String phone;
public String register(){
RegisterDao rdao = new RegisterDao();
System.out.println("firstname action::: "+firstname);
rdao.registerdao(firstname,lastname,regpassword,conpassword,regemail,conemail,phone);
return SUCCESS;
}
public String login() {
httpServletRequest.getSession().setAttribute("key", username);
httpServletRequest.getSession().setAttribute("key", password);
LoginDao db = new LoginDao();
Boolean validate = db.loginresult(username, password);
if (validate == true) {
return SUCCESS;
} else {
return INPUT;
}
}
public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
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 getRegpassword() {
return regpassword;
}
public void setRegpassword(String regpassword) {
this.regpassword = regpassword;
}
public String getConpassword() {
return conpassword;
}
public void setConpassword(String conpassword) {
this.conpassword = conpassword;
}
public String getRegemail() {
return regemail;
}
public void setRegemail(String regemail) {
this.regemail = regemail;
}
public String getConemail() {
return conemail;
}
public void setConemail(String conemail) {
this.conemail = conemail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setServletRequest(HttpServletRequest request) {
this.httpServletRequest = request;
}
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;
}
#Override
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
}
}
When i submit the registration form , the input values pass to Action class is null. How can i access the registration values in action class under register() method.
The above issue is resolved .
Now i'm facing another strange issue .. When i submit the form action = getLogin.action , its always returning INPUT from the interceptor . I dont wish to exclude the method login from the validator.
How could i resolve it ?
When i change the struts xml like below , its redirecting to success jsp . But i dont want to exclude the login method from validation
<action name="getLogin" class="login.action.LoginAction"
method="login">
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">login</param>
</interceptor-ref>
<result name="success">/Success.jsp</result>
<result name="input">/LoginError.jsp</result>
</action>
You are using only one Interceptor, you need to use the whole Stack:
Change this:
<interceptor-ref name="validation">
<param name="excludeMethods">register</param>
</interceptor-ref>
to this
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">register</param>
</interceptor-ref>

JSF viewAction passing param and it gets set, but returns to null

JSF 2.2
Primefaces 4.0
JBoss Wildfly
From a page with a list of customers, and want a button for each customer where the user can add items.
When I click the "New Item" button I am redirected to the new item page.
In the url is the customer id
newItem.jsf;jsessionid=Xw7tdljr9f0atzyET2Fy6_WI?customerId=3
I can debug that the set customer id method in the new item bean in called with the value 3, nice :)
But right after I debug that the get customer id method is called.. and now the customer id is null :(
And I made a syso :
18:10:25,312 INFO [stdout] (default task-9) Setting customer id 3
So the customer id is begin set... but is reset to null somehow ????
customers.xhtml
<ui:define name="content">
<f:metadata>
<f:viewParam name="customerId" value="#{customerController.customerEnt.id}" />
</f:metadata>
<h:form id="customers" prependId="false" includeViewParams="true">
<p:dataTable id="dataTable" var="customer"
value="#{customerController.customers}" rowKey="#{customer.id}"
styleClass="userDataTableStyle" paginator="true" rows="10"
selection="#{customerController.selectedCustomers}"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
lazy="true" rowsPerPageTemplate="10,15,50">
...
<p:column>
<p:commandButton ajax="false" value="New Item" action="#{customerController.newItem(customer)}"/>
</p:column>
</p:dataTable>
</h:form>
newItem.xhtml
<ui:define name="content">
<f:metadata>
<f:viewParam name="customerId"
value="#{newItemController.customerId}" />
<f:viewAction action="#{newItemController.init()}"/>
</f:metadata>
<h:form id="item" includeViewParams="true">
...
newItemController.java
#SuppressWarnings("serial")
#ViewScoped
#Named
public class NewItemController implements Serializable {
private CustomerEnt customerEnt;
private String customerId;
#PostConstruct
public void init() {
itemEnt = new ItemEnt();
if (customerId == null) {
String message = "Bad request. Please use a link from within the system.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
return;
}
customerEnt = customerDas.find(Long.parseLong(customerId));
if (customerEnt == null) {
String message = "Bad request. Unknown customer.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
}
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
System.out.println("Setting customer id " + customerId);
}
}
CustomerController.java
#SuppressWarnings("serial")
#SessionScoped
#Named
public class CustomerController implements Serializable {
private Long customerId;
public String newItem(CustomerEnt customerEnt) {
customerId = customerEnt.getId();
return "newItem?faces-redirect=true&customerId=" + customerId;
}
As L-Ray stated, the init was called twice, so I made this change in NewItemController:
public void init() {
System.out.println("In init");
}
#PostConstruct
public void postConstruct() {
itemEnt = new ItemEnt();
System.out.println("In postConstruct");
}
public void loadData() {
if (customerId == null) {
String message = "Bad request. Please use a link from within the system.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
return;
}
}
public void save() throws Exception {
try {
serviceSLSB.save(Long.parseLong(customerId), itemEnt);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Saved!", "Item saved successful");
facesContext.addMessage(null, m);
postConstruct();
} catch (ConstraintViolationException e) {
itemEnt.setBid(null);
String errorMessage = getRootErrorMessage(e);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Saving unsuccessful");
facesContext.addMessage(null, m);
} catch (Exception e) {
String errorMessage = getRootErrorMessage(e);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Saving unsuccessful");
facesContext.addMessage(null, m);
}
}
and in the newItem.xhtml
<f:metadata>
<f:viewParam name="customerId"
value="#{newItemController.customerId}" />
<f:viewAction action="#{newItemController.loadData()}"/>
</f:metadata>
And now it works... :) but now I have a new problem.. i will create a separate question for that :)
Thanks for the help
The given source looks good - just one thing caught my eyes: At the moment, your NewItemController.init() get's called twice
as #PostConstruct
through f:viewAction
If you call the method anyway, you don't need the annotation, isn't it?
i will never understand f:viewParam... maybe you miss includeViewParams=true in CustomerController.newItem()? never saw on a form, maybe it is JSF 2.2
i am doing it this way:
#ViewScoped
#Named
public class NewItemController implements Serializable
{
private CustomerEnt customerEnt;
#ManagedProperty("#{param.customerId}")
private String customerId;
#PostConstruct
public void init()
{
if(customerId == null)
{
String message = "Bad request. Please use a link from within the system.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
return;
}
customerEnt = customerDas.find(Long.parseLong(customerId));
if(customerEnt == null)
{
String message = "Bad request. Unknown customer.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
}
}
public String getCustomerId()
{
return customerId;
}
public void setCustomerId(String customerId)
{
this.customerId = customerId;
System.out.println("Setting customer id " + customerId);
}
}
and newItem.xhtml
<ui:define name="content">
<!--
<f:metadata>
<f:viewParam name="customerId"
value="#{newItemController.customerId}" />
<f:viewAction action="#{newItemController.init()}"/>
</f:metadata>
-->
<h:form id="item">
...
</ui:define>

Resources