Set method is not called in struts2 for file input but called for other perameters - struts2

I am new to struts2. What I am trying is to get data from the client and insert into the db.But while doing this setImageFile(File fie) isnt called and thus imageFile object is null. While other set methods are called and is thus respective members contains values.
action.class
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.Map;
import javax.servlet.http.Part;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.dispatcher.SessionMap;
public class register extends ActionSupport implements SessionAware{
SessionMap<String, String> sessionMap;
private String name;
private String email;
private String dob;
private String address;
private File imageFile;
private String imageFileFileName;
private String imageFileContentType;
#Override
public void setSession(Map map)
{
sessionMap = (SessionMap)map;
sessionMap.put("", name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public File getImageFile() {
return imageFile;
}
public void setFile(File imageFile) {
this.imageFile = imageFile;
}
public void setSessionMap(SessionMap<String, String> sessionMap) {
this.sessionMap = sessionMap;
}
public String execute()
{
try
{
Class.forName("org.postgresql.Driver");
Connection conn=DriverManager.getConnection("jdbc:postgresql://localhost:5432/DemoDB", "postgres", "postgres");
InputStream imageInputStream = new FileInputStream(imageFile);
String query = "insert into userProfile('Name','Address','email','dob','img') values(?,?,?,?,?)";
Date date = Date.valueOf(dob);
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(0, name);
preparedStatement.setString(1, address);
preparedStatement.setString(2, email);
preparedStatement.setDate(3, date);
preparedStatement.setBinaryStream(4, imageInputStream, imageFile.length());
preparedStatement.execute();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return "success";
}
}
In the above code imageFile is null. And othe members contains value
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="register" namespace="/" extends="tiles-default">
<action name="register" class="com.passportseva.register">
<result name="success" type="tiles">login</result>
<result name="input" type="tiles">register</result>
<result name="error">layoutmanager.jsp</result>
</action>
</package>
</struts>
This is jsp where the action is called
registration.jsp
<%#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>JSP Page</title>
</head>
<body>
<form action="register" method="POST">
<div>
<div><h1>Name</h1></div>
<input type="text" name="name" hint="name"/>
</div>
<div>
<div><h1>Email</h1>></div>
<input type="text" name="email" hint="email"/>
</div>
<div>
<div><h1>DOB</h1></div>
<input type="date" name="dob"/>
</div>
<div>
<div><h1>Address</h1></div>
<input type="area" name="address" hint="address"/>
</div>
<div>
<s:file name="imageFile" label="image"/>
</div>
<input type="submit" value="register"/>
</form>
</body>
</html>
I used tiles here
tiles.xml
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="login" template="/layoutmanager.jsp">
<put-attribute name="title" value="Login Page"/>
<put-attribute name="body" value="/login.jsp"/>
</definition>
<definition name="register" template="/layoutmanager.jsp">
<put-attribute name="title" value="Passport seva registration"/>
<put-attribute name="body" value="/registration.jsp"/>
</definition>
</tiles-definitions>
The output says that invalid field value for imageFile.

Use Struts Form tag with enctype attribute.
<s:form action="register" method="POST" enctype="multipart/form-data">
</s:form>

Related

Struts2 Global Result and global exception not working

I am trying to get the exception via struts2 to display the global results jsp but its not working and instead I am getting a java exception show in console. Also would like to add that If i use interceptor-ref exception individually to an action its working fine but globally not working as intended.
Here is my struts.xml, just addded a simple global results and exceptions.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts-devmode" value="true"></constant>
<package name="user" extends="struts-default">
<global-results>
<result name="myresult">globalresult.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="myresult" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
<action name="UserAction" class="actionclasses.UserAction"
method="execute">
<interceptor-ref name="timer"></interceptor-ref>
<interceptor-ref name="params"></interceptor-ref>
<result name="input">index.jsp</result>
<result name="success">success.jsp</result>
</action>
<action name="LoginAction">
<result type="redirect">login.jsp</result>
</action>
</package>
</struts>
My UserAction class from where exception is raised.
package actionclasses;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
String userName;
String passWord;
public String execute()
{
System.out.println(userName);
int a=10/0;
return "success";
}
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;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
My login.jsp, my login page
<%# 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>User Login</title>
</head>
<body>
<h1>Login to Web page</h1>
<s:form action="UserAction" method="post">
<s:textfield name="userName" label="Enter UserName" />
<s:password name="passWord" label="Enter Password" />
<s:submit value="submit" />
</s:form>
</body>
</html>
Once you specify any interceptors you must specify all interceptors.

how to validate HashSet size greather than zero in Struts2 if tag?

I am using Struts2 and want to check the HashSet property size is greater than zero using Struts2 if tag.
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="bundle" extends="struts-default" namespace="/">
<action name="process"
class="sample.action.Process"
method="execute">
<interceptor-ref name="defaultStack" />
<result name="success">/jsp/result.jsp</result>
</action>
</package>
</struts>
POJO
package sample.pojo;
public class Customer{
private Integer id;
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
Action Class
package sample.action;
import java.util.HashSet;
import java.util.Set;
import sample.pojo.Customer;
import com.opensymphony.xwork2.ActionSupport;
public class Process extends ActionSupport
{
private Set<Customer> result = new HashSet<Customer>();
public String execute()
{
Customer cust1 = new Customer();
cust1.setId(1);
cust1.setAge(59);
cust1.setName("Subramanian");
result.add(cust1);
return SUCCESS;
}
public Set<Customer> getResult() {
return result;
}
public void setResult(Set<Customer> result) {
this.result = result;
}
}
VIEW
<!DOCTYPE html>
<html>
<head>
<%# taglib prefix="s" uri="/struts-tags"%>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=8;" />
<title>Welcome Page</title>
</head>
<body>
<s:if test="*<syntax>*">
java.util.HashSet size is <s:property value="result.size"/>
</s:if>
<s:else>
java.util.HashSet size is empty!
</s:else>
</body>
</html>
Please help with the Struts2 if tag syntax to be used in the View. Thank you!
Below code snippet worked for me
<s:if test="%{mySet.size()>0}">

Target Unreachable, identifier 'regionMaster' resolved to null

I created a managedBean & .xhtml page.It works fine on jsf 2.1 but not working on jsf 2.2 .Showing error Target Unreachable, identifier 'regionMaster' resolved to null
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:prime="http://primefaces.org/ui">
<head>
</head>
<ui:composition>
<h:form id="regionMaster" name="regionMaster">
<div id="region">
<table align="center">
<tr>
<td><prime:panel header="Region">
<prime:messages autoUpdate="true" />
<prime:panelGrid style="margin-top:20px">
<prime:row>
<prime:column>
<h:outputLabel for="txtRegionID" value="RegionID" />
</prime:column>
<prime:column colspan="3">
<prime:inputText id="txtRegionID" value="#{regionMaster.regionId}"
label="Region ID" required="true" />
</prime:column>
<prime:column>
<!-- <h:commandButton id="openPopUp" value="..."
target="RegionList.xhtml"
onclick="window.open('RegionList.xhtml','childWindow','status=no,toolbar=no,location=no,menubar=no,resizable = no,width=1008,height=390,scrollbars,left=100,top=50');"
action="#{regionList.xhtml}" />-->
<!-- <prime:commandButton value="View" icon="ui-icon-extlink"
actionListener="#{regionMaster.regionList}" validateClient="false" immediate="true" />-->
<prime:dialog id="basicDialog" header="Basic Dialog"
widgetVar="dlg1">
<h:outputText value="Resistance to PrimeFaces is futile!" />
</prime:dialog>
<prime:commandButton id="basic" value="Basic"
onclick="PF('dlg1').show();" type="button" />
</prime:column>
</prime:row>
<prime:row>
<prime:column>
<h:outputLabel for="txtRegionName" value="RegionName" />
</prime:column>
<prime:column colspan="3">
<prime:inputText id="txtRegionName" value="#{regionMaster.regionName}"
label="Region Name" required="true" />
</prime:column>
</prime:row>
<prime:row>
<prime:column>
</prime:column>
<prime:column colspan="1">
<prime:commandButton action="#{regionMaster.save}"
value="save" />
</prime:column>
<prime:column colspan="1">
<prime:commandButton accesskey="R" alt="Click to Reset"
validateClient="false" immediate="true"
action="#{regionMaster.reset}" value="Reset" />
</prime:column>
<prime:column colspan="1">
<prime:commandButton accesskey="D"
onclick="if (!confirm('Are you sure you want to delete?')) return false"
alt="Click to Delete" actionListener="#{regionMaster.delete}"
validateClient="false" immediate="true" value="delete">
</prime:commandButton>
</prime:column>
</prime:row>
</prime:panelGrid>
</prime:panel></td>
</tr>
</table>
</div>
</h:form>
</ui:composition>
</html>
MyBean is
package com.sst.cms.web.beans;
import javax.faces.bean.RequestScoped;
import org.primefaces.context.RequestContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.inject.Named;
#ManagedBean(name="regionMaster",eager=false)
#SessionScoped
#Named("regionMaster")
public class RegionMasterBean implements Serializable {
//private static final FacesMessage RegionList = null;
public RegionMasterBean() {
}
private String regionId;
private String regionName;
private String createdBy;
private Date createdDate;
private String modifiedBy;
private Date modifiedDate;
private String entity;
private ArrayList<RegionMasterBean> regionList;
public String getRegionId() {
System.out.println("Region id======"+regionId);
return regionId;
}
public void setRegionId(String regionId) {
System.out.println("Region id======"+regionId);
this.regionId = regionId;
}
// other getter+setter
public String save(){
System.out.println("Bean is calleddddddddd");
return "SUCCESSFUL";
}
public void reset(){
this.regionId = "";
this.regionName = "";
}
public String delete(){
return "Sucess";
}
// public String setId(){
// System.out.println("Region iddddddddddddd");
//
// FacesContext fc = FacesContext.getCurrentInstance();
// this.regionId = getCountryParam(fc);
//
// return regionId;
// }
//
public ArrayList<RegionMasterBean> regionListLoad(){
regionList = new ArrayList<RegionMasterBean>();
RegionMasterBean dto = new RegionMasterBean();
dto.setRegionId("REG001");
dto.setRegionName("India");
RegionMasterBean dto1 = new RegionMasterBean();
dto1.setRegionId("REG002");
dto1.setRegionName("Afganisthan");
regionList.add(dto);
regionList.add(dto1);
return regionList;
}
public ArrayList<RegionMasterBean> getRegionList() {
return regionList;
}
public void setRegionList(ArrayList<RegionMasterBean> regionList) {
this.regionList = regionList;
}
public String saveSetting(){
System.out.println("this is calleddddddd");
this.regionId = "Roo1";
return regionId;
}
#PostConstruct
public void regionList() {
System.out.println("region list is calledddddddd");
RequestContext.getCurrentInstance().openDialog("RegionList");
System.out.println("region list is calledddddddd");
}
}
It works fine with the project where i have jsf 1.2 but when i add this to a new project with jsf 2.2 it shows the error

Struts2 validation is not even working

I also configured all the setting for Struts2 basic validation, but nothing is working for me.
My login.jsp file
<%#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>
<title>Login Page</title>
<s:head />
</head>
<body>
<s:actionerror/>
<s:form action="Login" method="post">
<s:textfield name="userName" label="User Name" />
<s:password name="password" label="Password" />
<s:submit value="Login" />
<s:fielderror></s:fielderror>
</s:form>
</body>
</html>
My loginAction class is,
package com.test;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String userName;
private String password;
public LoginAction() {
}
public String execute() {
return "SUCCESS";
}
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;
}
}
my struts2.xml file is,
<package name="default" namespace="/" extends="struts-default">
<action name="Login" class="com.test.LoginAction" method="execute">
<result name="SUCCESS">login.jsp</result>
<result name="input">login.jsp</result>
</action>
</package>
</struts>
And I place my LoginAction-validation.xml file in the same package where the Action class is placed.
Please lookout my code and help me to resolve the validation issue.
You are returning same login.jsp page in your execute method in action class.
So this results in displaying login page with empty field every time you hit enter.
Try creating an additional jsp to which you are redirected to based on String returned from action class.
other than that i dont see any problem.

Struts2 parameters is coming null in action class

i am not able to get the value of the text entered in the textbox in jsp into my action class. below are my files. can anyone please help as this is very urgent.
my jsp is
<%# taglib uri="/struts-tags" prefix="s" %>
<html>
<body>
<s:form action="login" method="post">
<s:textfield name="userName" label="User Name" />
<s:submit type="button" id="submit" label="Submit"/>
<s:reset id="reset" label="Reset"></s:reset>
</s:form>
</body>
</html>
my action class is
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String userName;
public String getUserName() {
return userName;
}
public void setUsername(String username) {
this.userName = username;
}
public String execute(){
System.out.println("the userName is "+this.getUserName());
return SUCCESS;
}
}
and my struts.xml is
<?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>
<include file="struts-default.xml" />
<package name="default" extends="struts-default">
<action name="login" class="core.login.LoginAction">
<result name="error">>/webpages/login/Error.jsp</result>
<result name="success">/webpages/home/Home.jsp</result>
</action>
</package>
</struts>
Case-sensitivity is important.
public void setUsername(String username) {
this.userName = username;
}
Should be:
public void setUserName(String username) {
this.userName = username;
}
In your struts.xml, you have written
class="core.login.LoginAction"
but you are not declaring any package in your Action class.
Also setter and getter method are of different names. Remember they are case-sensitive as said by Steven.
Try removing minor mistakes like an extra ">"
In your textfield add value attribute like this:
<s:textfield name="userName" label="User Name" value="${userName}" />
That directly maps it to member variable in action class.
In Eclipse,
to solve case sensitivity problem right click on code writing area and go to source -> Generate getter and setter method
It will add getter and setter method for selected member variables.

Resources