Posts Tagged ‘Struts2’

How to change locale in Struts2 from database

i need to change the language of the user from the database, so to do this all in need is to set “request_locale”, see example. if i put this code below in my struts.properties, then dutch will be my default language

struts.locale = du_NL

a user can also change language, so i have to save the language settings in database, so that next time when the user logs in, he/she will get his/her language instead of the default one. to do this i have added “param” in my struts.xml

<result name="success" type="redirectAction">
                <param name="actionName">myAction</param>
                <param name="request_locale">${userLang}</param>
            </result>

“userLang” is what i have set from the action i.e. en, du or fr. once the “request_locale” is set the page will be displayed as per the “userLang”. we can see this by using the code below

session.get("WW_TRANS_I18N_LOCALE").toString();

because myAction.action?request_locale=en_US or myAction.action?request_locale=du_NL etc will set the locale in user session. i must say struts2 is really cool.

Struts2 devMode (struts.i18n.reload)

i was trying to reload my properties file so that every time i make any changes, i don’t need to build and deploy it again. what i need is on every request the the resource bundle is reloaded. this feature is available in struts2 see documentation. but it is not working. I did not understand what i am missing. in my struts.properties i have

struts.devMode = true
struts.i18n.reload = true

so when i update my struts2.1.8.1 to struts2.2.3.1, its works, i don’t how it is working now because i have not change any thing, may be it a version issue.

Struts2 File Upload to Desire Folder Location

Lets starts with action class, I have created the action class named “WebAction“,

public class WebAction extends ActionSupport {

    private File myfile;
    private String myfileFileName;
    private String myfileContentType;
    private String filePathToSaveInDB;

    public String openHome() {
        return "open";
    }

    public String uploadFileToMyFolder() {
        try {
            ServletContext servletContext = ServletActionContext.getServletContext();
            String path = "MyFolder/";
            //getting the path to where the images will be uploaded
            String filePath = servletContext.getRealPath(path);

            File uploadDir = new File(filePath);
            //if the folder does not exits, creating it
            if (uploadDir.exists() == false) {
                uploadDir.mkdirs();
            }
            setFilePathToSaveInDB(path + "/" + myfileFileName);
            FileUtils.copyFile(myfile, new File(uploadDir, myfileFileName));
          
        } catch (Exception e) {
            System.out.println("Exception : " + e);
            addActionError(e.getMessage());
            return "failure";
        }
        return "success";
    }

// GETTER AND SETTER GOES HERE


In Above “WebAction” action we have
private File myfile: This contains the content of the uploaded file.
private String myfileFileName: The mime type of the uploaded file . (Optional)
private String myfileContentType: This is actual file name of the uploaded file. (Optional)
private String filePathToSaveInDB; It contains path of the image which we use to display the image. (also can be stored in db to be used in latter use)

Now struts.xml consists of

<action name="uploadFileToMyFolder" method="uploadFileToMyFolder" class="com.debraj.WebAction">
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">2097152</param>
                <param name="allowedTypes">
                              image/png,image/gif,image/jpeg,image/jpg
                </param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">/pages/web/Success.jsp</result>
            <result name="failure">/pages/web/failure.jsp</result>
</action>

Two parameter, “maximumSize” and “allowedTypes” are added to the interceptor. “allowedTypes” parameter specifies the content type of the file to be upload i.e “text/plain” specifies uploaded file will be a text file. “maximumSize” parameter set the size of the file to be uploaded, by default the size is 2Mb, but we can increase the upload size limit by adding a single line of code in struts.xml i.e.

<constant name="struts.multipart.maxSize" value="2147483648" />

Struts2 default.properties defines setting to upload file i.e.
“struts.multipart.parser=jakarta/pell” (is used by the fileUpload interceptor to handle HTTP POST requests)
“struts.multipart.maxSize=2097152” (to specify the size of the file)
“struts.multipart.saveDir=” (location to where the file will be saved)

Now Home.jps

<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload" /></title>
    </head>
    <body>
        <div>
            <s:form id="uploadFileToMyFolder" name="uploadFileToMyFolder" action="uploadFileToMyFolder" enctype="multipart/form-data">
                <s:text name="Upload Image : " />
                <s:file name="myfile" id="myfile"/>
                <s:submit name="submit"/>
            </s:form>
        </div>
    </body>
</html>

Success.jsp

<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload Success" /></title>
    </head>
    <body>
        <div>
            <s:actionmessage />
            <s:property value="myfile"/><br />
            <s:property value="myfileFileName"/><br />
            <s:property value="myfileContentType"/><br />
            <img src="<s:text name='%{filePathToSaveInDB}'/>"/><br />
            
        </div>
    </body>
</html>

failure.jsp

<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload Failure" /></title>
    </head>
    <body>
        <div>
            <s:actionerror />
        </div>
    </body>
</html>

That’s all. If you need to display that how many bytes the file has, then in WebAction action just add the below lines of code

String fileSize = FileUtils.byteCountToDisplaySize(logofile.length());

All the uploading files are saved into a temporary directory (by the framework) before being passed in to an Action. Error message like “struts.messages.error.uploading”, “struts.messages.error.file.too.large” and “struts.messages.error.content.type.not.allowed” specifies error while uploading files, size of the file exceeds the maximumSize and content type of the file is doesn’t match with the specified allowedTypes respectively. Actually fileUpload interceptor does the validation.

There are other methods also for uploading file in struts2. This is my approach of file uploading.
Enjoy.