Struts 2 get result string in JSP - java

How to get the action result string in JSP?
I want to use the same JSP for all results.
public String doSth()
{
return a ? "ok" : "failed";
}

same.jsp:
<%--
Author : Prabhakar
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
The Result is : <s:property value="a" />
</body>
</html>
ActionClass.java:
package com.prabhakar;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
/**
*
* #author Prabhakar
*/
public class ActionClass extends ActionSupport {
private String a;
public String getA() {
return this.a;
}
public void setA(String a) {
this.a = a;
}
public String doSth() {
if (some condition) {
a = "success";
} else {
a = "failed";
}
return a;
}
}
struts.xml
<struts>
<package name="somename" extends="struts-default">
<action name="resultName" method="doSth" class="com.prabhakar.ActionClass">
<result name="success">same.jsp</result>
<result name="failed">same.jsp</result>
</action>
</package>
</struts>

Only static access is available
<s:property value="#com.opensymphony.xwork2.ActionContext#getContext().getActionInvocation().getResultCode()"/>
For this code being able to work you need a configuration
<constant name="struts.ognl.allowStaticMethodAccess" value="true" />

Related

How to save file with its original name in Struts2 while uploading a file

I need to save uploaded file with its original name and type instead of temporary file name in separate folder.
By using below code i can get file name and type but how can i change temporary name with its original name.
private File file1;
private String file1ContentType;
private String file1FileName;
public File getFile1() {
return file1;
}
public void setFile1(File file1) {
this.file1 = file1;
}
public String getFile1ContentType() {
return file1ContentType;
}
public void setFile1ContentType(String file1ContentType) {
this.file1ContentType = file1ContentType;
}
public String getFile1FileName() {
return file1FileName;
}
public void setFile1FileName(String file1FileName) {
this.file1FileName = file1FileName;
}
public String upld() {
File dest = new File("/home/desktop/images/");
try {
System.out.println("file1FileName........"+file1FileName);
System.out.println("file1ContentType........"+file1ContentType);
System.out.println("file1........"+file1);
FileUtils.copyFileToDirectory(file1, dest);
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
By this code its possible to save video with its temporary file name but i want to save file with its original name and type....
or else is it possible to rename temporary file with its original name before saving in to the folder
Turn
File dest = new File("/home/desktop/images/");
/* ... */
FileUtils.copyFileToDirectory(file1, dest);
into
File dest = new File("/home/desktop/images/" + file1FileName);
/* ... */
FileUtils.copyFile(file1, dest);
Try below code.
jsp code:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
<body>
<h1>Struts 2 file upload example</h1>
<s:form action="resultAction" namespace="/"
method="POST" enctype="multipart/form-data">
<s:file name="upload" label="Select a File to upload" size="40" />
User file : <s:property value="uploadFileName"></s:property>
<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>
Java Code:
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
public class FileUploadAction extends ActionSupport implements ServletRequestAware {
private File upload;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadDocContentType() {
return uploadDocContentType;
}
public void setUploadDocContentType(String uploadDocContentType) {
this.uploadDocContentType = uploadDocContentType;
}
private String uploadDocContentType;
public HttpServletRequest request;
public HttpSession session;
public String uploadFileName;
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String uploadImg() throws IOException{
String targetPath ="/Desination path/";
session = request.getSession(true);
System.out.println("targetPath->"+uploadFileName);
File fileToCreate = new File(targetPath, uploadFileName);
try
{
FileUtils.copyFile(this.upload, fileToCreate);
}
catch (IOException e)
{
addActionError(e.getMessage());
}
return "success";
}
#Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request=request;
}
}
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.multipart.maxSize" value="20097152" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default ,json-default">
<action name="resultAction" class="FileUploadAction" method="uploadImg">
<interceptor-ref name="fileUpload">
<param name="maximumSize">1024000</param>
<param name="allowedTypes">image/png,image/gif,image/jpeg,image/pjpeg </param>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
<result name="success">/index.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>

Saving form data in the database using Struts 2

When we click the save button it must save the form data in the database but its doing nothing.
Below is the code:
BodyDaywise.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Day Wise</title>
</head>
<body align="center">
<h1 align="center">Day Wise Form</h1>
<html:form action="daywise" class="BodyDaywiseAction" method="POST" >
LoginDate: <input type="date" name="LoginDate" displayformat="yyyy-mm-dd" label="Login Date(yyyy-mm-dd)"/><br><br>
LoginTime:<input id="start" type="time" name="LoginTime"/><br><br>
LogoutTime:<input id="end" type="time" name="LogoutTime"/><br><br>
Task:<input type="textarea" name="Task" label="Task" cols="20" rows="5"/><br><br>
<input type="submit" value="save" name="Save" onClick=""/>
<button type="submit" value="Clear" name="clear">Clear</button>
<input type="button" value="cancel" onClick="history.back();"/>
</html:form>
</body>
</html>
Action class: BodyDaywiseAction.java:
package com.timesheet.action;
import com.opensymphony.xwork2.ActionSupport;
import com.timesheet.db.DaywiseDBO;
import java.sql.Date;
import java.sql.Time;
public class BodyDaywiseAction extends ActionSupport {
public BodyDaywiseAction()
{
}
private Date LoginDate;
private Time LoginTime;
private Time LogoutTime;
private String Task;
public Date getLoginDate() {
return LoginDate;
}
public void setLoginDate(Date LoginDate) {
this.LoginDate = LoginDate;
}
public Time getLoginTime() {
return LoginTime;
}
public void setLoginTime(Time LoginTime) {
this.LoginTime = LoginTime;
}
public Time getLogoutTime() {
return LogoutTime;
}
public void setLogoutTime(Time LogoutTime) {
this.LogoutTime = LogoutTime;
}
public String getTask() {
return Task;
}
public void setTask(String Task) {
this.Task = Task;
}
private static final long serialVersionUID = 1L;
#Override
public String execute() throws Exception {
int i=DaywiseDBO.save(this);
if(i>0){
return "success";
}
return "error";
}
#Override
public void validate() {
if("".equals(getTask())){
addFieldError("Task", "Task must be filled !");
}
}
}
DaywiseDBO.java:
package com.timesheet.db;
import com.timesheet.action.BodyDaywiseAction;
import com.timesheet.dbutil.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DaywiseDBO {
public static int save(BodyDaywiseAction BDA) throws Exception{
int status=0;
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
DBUtil util = null;
try{
util = new DBUtil();
conn = util.getConnection();
ps = conn.prepareStatement("insert into logintable values(?,?,?,?)");
ps.setDate(1,BDA.getLoginDate());
ps.setTime(2,BDA.getLoginTime());
ps.setTime(3,BDA.getLogoutTime());
ps.setString(4,BDA.getTask());
status=ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();}
return status;
}
}
struts.xml:
<!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="default" extends="struts-default, tiles-default">
<result-types>
<result-type name="tiles"
class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="loginaction" class="com.timesheet.action.LoginAction" method="execute">
<result name="input" >/Login.jsp</result>
<result name="success" type="tiles">/bodydaywise.tiles</result>
<result name="error" type="tiles">/error.jsp</result>
</action>
<action name="daywise" class="com.timesheet.action.BodyDaywiseAction">
<result name="success" type="tiles">/bodydaywisesuccess.tiles</result>
<result name="error" type="tiles">/error.jsp</result>
</action>
</package>
</struts>
Please let me know if I'm missing something.
You are using wrong date/time type in the action class. Struts2 have not build-in converters for java.sql.* types. The date/time values should be converted to date if you use java.util.Date. objects of this type can contain both date and time values.
import java.util.Date;
import java.sql.Time;
Change the getters and setters accordingly to return the required. You can also set the date object to Calendar and do some calculations, after that you can create a Timestamp object from the calendar. For example
user.setCreateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
sets the current date & time to the user object before the user is added to the database.
The example of using PreparedStatement: JDBC PreparedStatement example – Insert a record.
There's also an example to save only date part of the Date: Insert date value in PreparedStatement. (Don't use it, because it doesn't save a time portion of the Date).

two action method in an action class using the same stack in liferay struts2 [duplicate]

This question already exists:
action class do not passing objects to jsp class ,using struts2 in liferay
Closed 7 years ago.
i am using liferay with Struts2, i have two action method in one action class, i create an object from a class in first action method(execute()) and passing that to the view and showing it successfully, in view.jsp i'm using that object but when i submit the form and going to second action method(sendMessage()) an exception happened.
what should i do? what is the problem?
struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package namespace="/support" extends="struts-portlet-default,json-default"
name="subjectview">
<action name="index" class="com.xxx.actions.SupportFormAction"
method="execute">
<result>/html/support/view.jsp</result>
</action>
<action name="sendmsg" class="com.xxx.actions.SupportFormAction"
method="sendMessage">
<result name="success">/html/support/send-message-success-ajax.jsp</result>
<result name="error">/html/support/send-message-fail-ajax.jsp</result>
</action>
</package>
</struts>
SupportFormAction.java
package com.xxx.actions;
import com.iknito.model.SendEmail;
import com.opensymphony.xwork2.ActionSupport;
public class SupportFormAction extends ActionSupport {
private SendEmail sendEmail;
#Override
public String execute() throws Exception {
sendEmail = new SendEmail();
return "success";
}
public String sendMessage(){
try{
System.out.println(sendEmail.getName()); /* nullpointer exception happened here*/
return "success";
}
catch(Exception ex){
ex.printStackTrace();
return "error";
}
}
public SendEmail getSendEmail() {
return sendEmail;
}
public void setSendEmail(SendEmail sendEmail) {
this.sendEmail = sendEmail;
}
}
SendEmail.java
package iknito.com.actions;
public class SendEmail {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
view.jsp
<%# include file="/html/init.jsp" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<s:form id="form1" action="addsubjects" theme="simple">
<label for="name">Name:</label>
<s:textfield type="text" name="sendEmail.name" placeholder="Hamed Yousefi" required="required"/>
<s:submit value="enter name"/>
</s:form>
Your object is lost after it is rendered on JSP page.
You need to either
put it in the page, for example in hidden inputs, and re-trasmit it completely (in your case, one hidden parameter for each attribute of the object)
or (much better when there is an entire object and not a simple String) put it in the session, and retrieve it later.

Struts 2 file upload : File object being null

I am trying to use Struts 2 file upload but it seems to me that its not working. Below is my code.
UploadAction.java:
public class UploadAction extends ActionSupport{
private File file;
private String orgFileName;
private String orgContentType;
public void setUpload(File file){
this.file=file;
}
public void setUploadContentType(String contentType){
this.orgContentType=contentType;
}
public void setUploadFileName(String fileName){
this.orgFileName=fileName;
}
#Override
public String execute(){
if(file==null)
{
System.out.println("No file....");
}
System.out.println(orgContentType);
System.out.println(orgFileName);
return SUCCESS;
}
}
struts.xml:
<constant name="struts.multipart.maxSize" value="20971520" />
<constant name="struts2.multipart.saveDir" value="C:/users/sabertooth/desktop/upload" />
<include file="example.xml"/>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="upload" class="UploadAction">
<result name="success">/example/HelloWorld.jsp</result>
</action>
</package>
I am also trying to set struts2.multipart.saveDir property as you can see above but when I read the server logs I see this line
unable to find `struts.multipart.saveDir` defaulting to `javax.servlet.dir`
Also the file object is null as no file... gets printed out on console.
I can't figure out what is wrong here.
EDIT:
fileupload.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>
<h1>upload file below</h1>
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
</body>
</html>
Apart from changing the saveDir (really not necessary, and dangerous), your are not following the conventions in the Action class: the name of an private variable must match the names of its Getters and Setters; and finally, in page you are mismatching the name by pointing to the private variable, not the setter. Change it to:
public class UploadAction extends ActionSupport{
private File upload;
private String uploadFileName;
private String uploadContentType;
public void setUpload(File upload){
this.upload=upload;
}
public void setUploadContentType(String uploadContentType){
this.uploadContentType=uploadContentType;
}
public void setUploadFileName(String uploadFileName){
this.uploadFileName=uploadFileName;
}
#Override
public String execute(){
if(upload==null)
{
System.out.println("No file....");
}
System.out.println(uploadContentType);
System.out.println(uploadFileName);
return SUCCESS;
}
}
JSP
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
Change this
<input type="file" name="file" id="uploadfile" />
to
<input type="file" name="upload" id="uploadfile" />
Your setter in your action class is setUpload so it is looking for a request parameter called upload, not file. For the sake of convention you should also change
private File file;
public void setUpload(File file){
this.file=file;
}
to
private File upload;
public void setUpload(File file){
this.upload=file;
}

What naming convention should be used for custom Interceptor class and package in order to avoid struts.xml in Struts2

I am interested to know if there is any convention for naming custom interceptor in struts2 for the auto detection of interceptors like there are for the action classes.
I am using "struts2-convention-plugin-2.3.24.1.jar".
The Package structure is as follow
ProtienTracker
>Java Resources
>src
>com.nagarro.actions
>HelloAction.java
>com.nagarro.interceptors
>custInterceptor.java
>WebContent
>META_INF
>WEB_INF
>content
>hello.jsp
>lib
>web.xml
The code runs perfect without "struts.xml" and without "custInterceptor". The action is automatically detected by the struts2-convention-plugin.
As soon as i attach the interceptor with
#org.apache.struts2.convention.annotation.Action(value="hello",
interceptorRefs=#InterceptorRef("custInterceptor"))
i get the error as shown below.
The files are as follow
hello.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>Hello</title>
</head>
<body>
<h1><s:property value="greeting"/></h1>
<p>hi</p>
</body>
</html>
HelloAction.java
package com.nagarro.actions;
import com.opensymphony.xwork2.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
public class HelloAction implements Action {
private String greeting="ab";
#Override
#org.apache.struts2.convention.annotation.Action(value="hello",
interceptorRefs=#InterceptorRef("custInterceptor"))
public String execute() throws Exception {
setGreeting("Hello Structs 2");
return "success";
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
custInterceptor.java
package com.nagarro.interceptors;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class custInterceptor implements Interceptor{
private static final long serialVersionUID = 1L;
#Override
public void destroy() {
System.out.println("custInterceptor destroy() is called...");
}
#Override
public void init() {
System.out.println("custInterceptor init() is called...");
}
#Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("custInterceptor intercept() is called...");
System.out.println(invocation.getAction().getClass().getName());
return invocation.invoke();
}
}
I get the following error:
Caused by: Unable to find interceptor class referenced by ref-name custInterceptor - [unknown location]
at com.opensymphony.xwork2.config.providers.InterceptorBuilder.constructInterceptorReference(InterceptorBuilder.java:63)
at org.apache.struts2.convention.DefaultInterceptorMapBuilder.buildInterceptorList(DefaultInterceptorMapBuilder.java:95)
at org.apache.struts2.convention.DefaultInterceptorMapBuilder.build(DefaultInterceptorMapBuilder.java:86)
at org.apache.struts2.convention.DefaultInterceptorMapBuilder.build(DefaultInterceptorMapBuilder.java:70)
at org.apache.struts2.convention.PackageBasedActionConfigBuilder.createActionConfig(PackageBasedActionConfigBuilder.java:947)
at org.apache.struts2.convention.PackageBasedActionConfigBuilder.buildConfiguration(PackageBasedActionConfigBuilder.java:734)
at org.apache.struts2.convention.PackageBasedActionConfigBuilder.buildActionConfigs(PackageBasedActionConfigBuilder.java:355)
at org.apache.struts2.convention.ClasspathPackageProvider.loadPackages(ClasspathPackageProvider.java:53)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:274)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
... 17 more
As mentioned in define interceptors with struts2 annotations.
you cannot eliminate a need of struts.xml if you are using custom
interceptors.
To define a new interceptor in xml you need to define it in struts.xml files
<struts>
......
<package name="my-default" extends="struts-default" />
<!-- Define the intercepor class and give it a name-->
<interceptors>
<interceptor name="custInterceptor" class=com.nagarro.interceptors.custInterceptor" />
</interceptors>
<!-- Add it to a package. for example I add
the interceptor at top of struts default stack-->
<interceptor-stack name="myDefaultStack">
<interceptor-ref name="custInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
<!-- Use the interceptor stack in your action with #InterceptorRef or set it as default -->
<default-interceptor-ref name="myDefaultStack" />
</package>
</struts>
You can see struts-default.xml https://struts.apache.org/docs/struts-defaultxml.html as a good sample for how interceptors are defined and used.

Categories