strut 1 : Actionforward to forward back to calling view with same ActionForm - struts-1

I have application in struts 1.
In this I have mailing form (to , from , subject , body etc) after user filling up the form . calls the action (press send button ) which will get the data from Form and send the mail
Here when mailing fails I have to send back the user to same mailing form with same data entered by him (i.e.., same ActionForm )
Can some one please help me how to achieve this in Struts 1

This should help you get started.
In the struts configuration file, the page gets redirected to the "input" attribute value if it fails, in this example "email.jsp" page.
Struts config file:
<struts-config>
<form-beans>
<form-bean name="emailForm" type="com.EmailForm">
</form-bean>
</form-beans>
<action path="/sendEmail"
type="com.SendEmailAction"
scope="request" name="mailForm"
input="email.jsp"
parameter="getCgrs">
<forward name="success" path="email.jsp"></forward>
</action>
</struts-config>
Your jsp Page:
<html:form action="/sendEmail" >
<html:text property = "toEmail" />
<input type="submit" value="Send Email"/>
</html:form>
In your form class you should have a property "toEmail" that matches the property in your jsp page.
public class EmailForm extends ActionForm{
private String toEmail;
public void setToEmail(String toEmail){
this.toEmail = toEmail;
}
public String getToEmail(){
return toEmail;
}
}

Related

How to handle session to keep login information using Spring MVC

I want to make login form with Spring MVC using Hibernate.
I found that I need to use 'session' to keep login information.
So, I use it in 'Controller.java', '.jsp'.
But It seems didn't work.
Below is my code. Controller.java:
#Controller
public class PassengerController {
#Autowired
private PassengerService passengerService;
public void setPassengerService(PassengerService passengerService) {
this.passengerService = passengerService;
}
#RequestMapping(value = "/login")
public String login(HttpSession session, HttpServletRequest request) {
String id = request.getParameter("idInput");
String pw = request.getParameter("pwInput");
// check DB
// if it is right, add session.
session.setAttribute("id", id);
session.setAttribute("pw", pw);
return "flightschedule";
}
#RequestMapping(value = "/logout")
public String logout(HttpSession session) {
session.invalidate();
return "flightschedule";
}
}
Below is part of flightschedule.jsp:
<c:if test="${sessionScope.loginId eq null}">
<!-- Not login: show login button -->
<div class="loginArea">
<form action="${loginAction}"> <!-- // URL '/login' -->
<input type="text" name="idInput" placeholder="ID" class="loginInput">
<input type="password" name="pwInput" placeholder="PASSWORD" class="loginInput">
<input id="loginButton" type="submit" value="login">
</form>
</div>
</c:if>
<c:if test="${sessionScope.loginId ne null}">
<!-- already login: show logout button -->
<div class="loginArea">
<form action="${logoutAction}"> <!-- // URL '/logout' -->
<input type="button" name="idInput" id="loginInfo" value="Welcome ${sessionScope.loginId}">
<input id="logoutButton" type="submit" value="LOGOUT">
</form>
</div>
</c:if>
I intended that when session.id exists, show log out button and when session.id doesn't exist, show login button.
I don't want to use interceptors or spring security etc..
I thought they're too complex to my little project.
And, I have login/logout form at all most of my pages. I don't use a separate page to login.
So I don't want to use interceptor. I just want to check whether session key exists in some jsp pages. Depending on its presence, I want to change page's view.
Above's code work partly. When login, it shows 'Welcome userId'.
But, when I click page's logo(then go to the first page), It still show 'login' button. It have to show 'log-out' button becuase session.loginId exists!
Do you have any solution?
In login method you put
// check DB
// if it is right, add session.
session.setAttribute("id", id);
session.setAttribute("pw", pw);
but on JSP check sessionScope.loginId , looks like you should check attribute with name id.

How to send data to a faces-flow?

My use case: the user choose a questionnaire in a form. When the form is submitted, a faces-flow is started to display the questions of the questionnaire.
To send the questionnaire to the flow, in the bean of the flow I inject the CDI bean of the page which contains the form.
I wonder if there are other ways to send the questionnaire to the flow. If there are several ways, what's the best one?
You can pass parameters via the form and get them in the initializer method called at the initialization of your flow.
Form (just replace the inputHidden parameter with whatever you're using to select your questionnaire)
<h:form id="myForm" prependId="false">
<h:commandLink value="Enter myFlow" action="my-flow"/>
<h:inputHidden id="parameter" name="parameter" value="8"/>
</h:form>
Flow
#Produces #FlowDefinition
public Flow defineFlow(#FlowBuilderParameter FlowBuilder flowBuilder) {
String flowId = "my-flow";
flowBuilder.id("", flowId);
flowBuilder.initializer("#{myFlowBean.startFlow()}");
...
}
Backing bean
#Named
#FlowScoped("my-flow")
public class MyFlowBean implements Serializable {
public void startFlow() {
String parameter = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("parameter");
//now do sthg with the parameter, such as fetching the questionnaire
....
}
}
See this answer for more details
Addition to "thomas.g"s helpful answer:
I had the same problem, but could not fix it with the hiddenInput approach. Despite the prependId="false" attribute my id and name of the hidden input field got changed by the primefaces p:dataTable element I used. The issue could be fixed with the f:param elemtent inside the h:commandLink element:
<h:commandLink value="Enter myFlow" action="my-flow" >
<f:param name="parameter" value="8"/>
</h:commandLink>
I hope this might be helpfull to someone with a similar problem.
This can be done in the flow xml file using the initializer tag
<initializer>
#{myFlowBean.startFlow()}
</initializer>
to call the your initialize method in the flow scoped bean

How to use saving the file without page refresh?

My JSP page have entry like:
demo.jsp:
<s:form action="demo" theme="simple">
Enter the location and filename for template to be saved (eg: C:\temp\a.xml)
<s:textfield name="fileLoation" id="FileLoationID" />
<s:submit value="Save" method="saveTemplate" />
</s:form>
struts.xml:
<action name="demo" class="com.test.action.DemoAction" >
<result name="preview">/jsp/demo/preview.jsp</result>
<result name="save">/jsp/demo/demo.jsp</result>
<result name="success">/jsp/demo/demo.jsp</result>
<result name="error">/loginError.jsp</result>
</action>
action class:
public String saveTemplate() {
try {
previewTemplate();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = (DOMSource) animalTemplateDetails.get("xmlStringDOMSource");
File file = new File(fileLoation);
file.getParentFile().mkdirs();
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "save";
}
Current process:
I provided path like "C:/temp/abc.xml"
Click save.
Goes to action class method saveTemplate() and save the file. And returns "save"
Will redirect to same page since <result name="save">/jsp/demo/demo.jsp</result>
My requirement:
I provided path like "C:/temp/abc.xml"
Click save.
Without Page refresh, it need to hit action class method saveTemplate().
Actually i tried with ajax, but that button is not working..
This is what i did:
Added <%# taglib prefix="sx" uri="/struts-dojo-tags"%>
Added <sx:head />
This part i am confused: i tried
(a) <s:submit value="Save" method="saveTemplate" theme="ajax" />
but here its showing error: "FreeMarker template error!Expression parameters.pushId is undefined on line 103, column 6 in template/ajax/submit.ftl."
(b) <sx:submit value="Save" method="saveTemplate" /> but here the button is not working. Nothing is happening.
Can anyone help?
<s:form action="demo" theme="simple" target="foo">
Enter the location and filename for template to be saved (eg: C:\temp\a.xml)
<s:textfield name="fileLoation" id="FileLoationID" />
<s:submit value="save" method="saveTemplate" target="foo" />
</s:form>
<iframe style="display:none" name="foo">
This is an hidden iframe targeted by the form to
avoid page refresh and new page / tab opening
</iframe>
And you can return NONE from the Action.
Btw you will have to notify the user if the operation has been successfully executed or not, then use iframe to receive an JSP snippet with the ok or ko message...
This is only ONE of the several ways to call Actions without refreshing the page, it's up to you...
But the code of your Action is executed on your SERVER, not on your CLIENT.
Then you need to change paradigm; use an Action that returns a Stream result, with content-disposition: attachment: this will ask the user where to download the file.
Read this too.

how to link one visualforce page from another visualforce page?

I want to add two numbers that are given in a vf page text boxes. I want to print the result in another vf page by clicking the button (add button) in first page.
You can do this by routing to the next page in Visualforce and passing the value you want to display as a parameter. Something like this in Apex should work:
PageReference gotoPage()
{
PageReference pr = Page.YourSecondVFPage;
pr.getParameters().put('secondnumber', '' + this.secondNumber);
pr.setRedirect(true);
return pr;
}
Then in Visualforce:
<apex:commandButton value="Go!" action="{!gotoPage}"/>
I think you might want to try using the same controller on both pages. That way you don't have to pass all that data, assuming you have more than just a couple of fields to maintain, as url parameters or have to store the data somewhere if you don't have to.
If both pages are using the same controller and when you redirect the user using a PageReference make sure to set the redirect value to false, otherwise Salesforce treats as a new request and starts the page with a new instance of the controller.
The sample code below lets the user type some text into a field and then when print view is clicked it renders a PDF using that same information. No data was saved to database.
Controller
public with sharing class MyController {
public string MyData {get;set;}
public MyController() {
MyData = '';
}
public PageReference printView() {
PageReference oPageRef = Page.MyPage2;
oPageRef.setRedirect(false);
return oPageRef;
}
}
Page 1:
<apex:page controller="MyController">
<apex:sectionheader title="Test" subtitle="My Page"/>
<apex:form id="formData">
<apex:pageBlock title="My Data">
<apex:pageBlockButtons >
<apex:commandButton value="Printable View" action="{!printView}" />
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel value="My Data"/>
<apex:inputTextArea value="{!MyData}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Page 2:
<apex:page controller="MyController"
renderAs="pdf">
{!MyData}
</apex:page>

How to pass a parameter value to a4j:jsFunction

On my page I have a button that opens a list of items in a popup. When I select 1 item in the list, I want to pass the id of the item to the backingbean of my first page. Is it possible? It tried to do it with a4j:jsFunction and a4j:param but it does'nt work.
This is my code:
page 1:
<a4j:jsFunction name="renderGuarantor" render="guarantor" actionListener="#{prospectDetail.setNewGuarantor}">
<a4j:param name="param1" assignTo="#{prospectDetail.newGuarantorId}" />
</a4j:jsFunction>
popuppage:
<h:outputLink value="" onclick="window.opener.renderGuarantor(#{applicant.deposit_id});window.close();">
<h:graphicImage style="padding:0 1px; border:0" value="${path.staticRootUrl}images/confirm.gif" alt="${msg.applicantslist_select}" title="${msg.applicantslist_select}"/>
</h:outputLink>
And this is the backing bean code for the first page
private Integer newGuarantorId;
public void setNewGuarantor() {
guarantor = newGuarantorId;
}
public Integer getNewGuarantorId() {
return newGuarantorId;
}
public void setNewGuarantorId(Integer newGuarantorId) {
this.newGuarantorId = newGuarantorId;
}
When selecting in the popup the method in my backingbean is called, but newGuarantorId is null and setNewGuarantorId is never called.
Is there a solution to my problem?
Hmm.. thats strange, nothing looks wrong..Not an answer to your question but try this workaround - instead of assigning the value to guarantorId, keep the param as <a4j:param name="param1"/> and in the actionListener method retrieve this param1 from the request as String param1 = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().‌​get("param1");.
And then convert this param to int and utilize it further. That should work
Try switching from actionListener to action:
<a4j:jsFunction name="renderGuarantor" render="guarantor" action="#{prospectDetail.setNewGuarantor}">
<a4j:param name="param1" assignTo="#{prospectDetail.newGuarantorId}"/>
</a4j:jsFunction>
Here is recommended reading on the topic: a4j:jsFunction
I think you can try this:
<a4j:jsFunction name="renderGuarantor" render="guarantor"
actionListener="#{prospectDetail.setNewGuarantor(prospectDetail.newGuarantorId)}" />
And in your Managed bean, define the setNewGuarantor method as following:
public void setNewGuarantor(int newGuarantorId) {
guarantor = newGuarantorId;
}

Resources