class SampleAction extends ActionSupport {
private Map<String,String> circleIdNameMap;
public String preprocess(){
--logic for populating value of MAP
}
--getters and setters
}
Now my problem is on page load I call preprocess function and populate the value of Map. After page submit another method is called and during that after some DB interaction it redirects to JSP, but this time the value of Map is empty. I am using this Map for drop-down tag in Struts2.
My preprocess is associated in the link like:
href="/gma/preprocessConfigureTspThreshold?operatorId=5102&sessionId=12332"`
So only first time when the link is clicked preprocess is called, after that when I redirect to my JSP so its not called then, so second time the value of Map is empty.
Shall I put the map in a session so that it is retained? Or can do something else?
I read that don't use preprocess function, use Preparable interface. But as per docs:
The prepare method will always be called by the Struts 2 framework's prepare interceptor
whenever any method is called for the Action class.
So, it will be called for every method. I want preprocess to be called only when page loads.
The prepare method of the Preparable action class is called on every action execution, that's right. That might be the reason why you prepare the map for a drop-down in the preprocess method.
public class SampleAction extends ActionSupport {
private Map<String,String> circleIdNameMap;
private String circleId;
//getters and setters here
protected boolean reload = false;
private void preprocess(){
// Get the Map by calling a stateless Session bean
circleIdNameMap = remoteInterface.getMap();
}
public String action1(){
preprocess();
Map session = ActionContext.getContext().getSession();
session.put("circleIdNameMap ", circleIdNameMap );
return SUCCESS;
}
public String action2(){
Map session = ActionContext.getContext().getSession();
circleIdNameMap = (Map<String,String>)session.get("circleIdNameMap");
if (circleIdNameMap == null){
if (reload) {
preprocess();
Map session = ActionContext.getContext().getSession();
session.put("circleIdNameMap ", circleIdNameMap );
} else {
addActionError("circleIdNameMap is null");
return ERROR;
}
}
return SUCCESS;
}
...//other actions
}
the JSP for drop-down
<s:select name="circleId" list="circleIdNameMap" listKey="key" listValue="value"/>
The meaning of this code is: you should not return result SUCCESS or INPUT if fields in JSP aren't initialized.
Related
I'am developing Struts2 Application. There is a value in database table and I want to use that value in many different Jsp pages. For that I am using singleton class.
DAO Class:
public class TestDAO {
public String getServerName() throws DAOException {
String findStatement = "SELECT name FROM classTest where value='1234';";
PreparedStatement ps=null;
ResultSet rs =null;
try {
ps=DBAccessManager.prepareStatement(findStatement);
rs = ps.executeQuery();
String name = rs.getString("name");
return name;
}catch{ //some text }
}
}
Singleton Class:
public class TestSingleton {
private static TestSingleton INSTANCE;
private String name;
private ServerSingleton() {
try {
setName(new TestDAO().getServerName());
} catch (DAOException e) {
e.printStackTrace();
}
}
public static TestSingleton getINSTANCE() {
return INSTANCE;
}
public static void setINSTANCE(TestSingleton iNSTANCE) {
INSTANCE = iNSTANCE;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
How can I use session in singleton class and read the session in JSP page
In JSP pages you can get the value from the valueStack. Once you get hitted your action to the controller the action context and valueStack are created by the Struts2 filter. You retrieve the value from the database using DAO and store it to the valueSrack. Note, that the valueStack is available not only in the controller but also in the view referencing a JSP page. In Struts2 the controller itself is exposed to the view via OGNL or EL. It is set on top of the valueStack.
So any changes to properties of the controller are reflected to JSP returned as a result with dispatcher result type which is default. If you use many JSP pages in many results then you have to retrieve the value from the database each time the request is made. Then you set the value to the property of controller.
Thus it is available to JSP returned as a result to the view via OGNL. All struts tags are supported to use OGNL in their attributes where you can write OGNL expressions or use EL.
It doesn't matter how you set the properties of the controller by the singleton object or prototype oblect the value is evaluated by OGNL expression. For it to work you provide your oblects with accessors and don't use a static context. Because the static context is turned off by default Struts2 configuration.
However if the objects are evaluated by many requests the singleton objects are shared by different threads and should be thread-safe.
If you use a session object which is implemented as a map in Struts2 and instance is already sinchronized. So you have only referencing a session scoped objects from the map which is available in the action context.
I have a Struts 2 textfield tag where I just need to get a user enter value and send to the action.
<s:textfield name="user.firstAnswer" size="110" cssClass="FormObjectCompulsary" autocomplete="off" />
Even when this page loads user object contains value for first answer, I don't want to display it in the text field instead I want the text field to be blank.
But with out specify the value attribute still the value in user object shows in this field.
If you are adding a new object user, then you should create this object with new operator before you show it in the JSP. It will contain null references that are not displayed. If the value attribute is not specified, then name is used to show the value.
Make your user object null after inside the execute(). So again it will not show value inside text box.
eg. user = null;
I am showing you piece of code, may be it will help you.
See the execute().
package online.solution;
import com.opensymphony.xwork2.Action;
public class MyAction implements Action {
UserBean user = new UserBean();
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
#SuppressWarnings("finally")
#Override
public String execute() throws Exception {
String result = "";
try {
user.setGuest("Bye bye");
System.out.println(user.getUsername() + " " + user.getPassword());
if (user.getUsername().equals(user.getPassword())) {
result = SUCCESS;
}
else {
result = ERROR;
}
user = null; //Make it null when all task completed.
}
catch (Exception exception) {
System.out.println("Exception -> " + exception);
}
finally {
return result;
}
}
#Override
protected void finalize() throws Throwable {
super.finalize();
}
}
By looking at name="user.firstAnswer" I am thinking that you are implementing ModelDriven<> to your action class. What might be happening is that when you return success in your action class and come to the jsp page, and if in action your user model had some values on it.. model driven will set those fields for your on your JSP page.
I have used this approach for update form functionality while learning struts2. Just make sure that user object contains nothing before you return...
I am trying to create an action with two methods (JSON action). I am calling them from JSP files. If I try to call an action value as 'medias' in my code, it simply run both the methods every time.
#Action(value="medias", results = {#Result(name="success",type="json")})
public String getMedias(){
System.out.println("IN METHOD CALL medias");
return SUCCESS;
}
#Action(value="allMediaTypes", results = {#Result(name="success",type="json")})
public String getAllMediaTypes(){
System.out.println("IN METHOD CALL allMediaTypes");
return SUCCESS;
}
Both method runs simultaneously, no matter which method is getting called from jsp, it runs both the methods.
Don't prefix your method names with get - doing this has implications.
It's a good idea to name them the same as your action names for consistency, ie:
public String medias() {
...
}
public String allMediaTypes() {
...
}
I have a scenario where I need to call a Java method which sets some request properties and the same has to be reflected in the jsp page.
<script type="text/javascript">
setInterval(function() {
ajaxAction($('#refresh'), 'moveETHAction_fetchExecutorData');
return false;
//callNextMethod(document.getElementById('moveForm'), 'moveETHAction_',
// 'fetchExecutorData');
}, 60 * 1000);
function ajaxAction(form, url) {
/* the time and hour are added to the request for create an unique URL for IE.
* The call to the server is realised only if the url is different...
*/
params = Form.serialize(form) + '&ms=' + new Date().getTime();
currentFocused = document.activeElement.id;
lastActionCalled = url;
formUsed = form;
var myAjax = new Ajax.Request(url, {
method : 'post',
parameters : params,
onComplete : showResponse
});
}
function showResponse(originalRequest) {
xml = originalRequest.responseXML;
}
</script>
as you see, I want to hit action class and the respective method.
However I don't have to replace anything in view part except fetching some request attributes which will be set in Java action class.
the total view part is in one form ('sendOrder') and i included one more form('refresh' within the main form. sorry, i don't know how to achieve my requirement. I just gave this try.
Please let me know how can I resolve this? It's not mandatory to use AJax, all i need to do is hit the java method and display the same page with updated request properties.
I am not sure how many fields you want to get from the Action and you can very well use Jquery along with Struts2-Json Plugin to do the work for you.
S2 Json plugin will help you to send back response in JSON format and you can use Jquery JSon feature to parse those fields and fill the values as per your way.
This is what you have to do
var myFormValues='id='+uuid;
$.getJSON('myAction',myFormValues,function(data) {
$.each(data.myObject,function(key, value){
alert(key);
alert(value);
});
});
here key is the name of the field and value is the value it hold with respect to that fiel
In above you are calling a action namely myAction which will return the JSON back based on the value sent by you myFormValues.
This is a mock for your action
public class MyAction extends ActionSupport{
private String id;
//getter and setter
private String vallue1;
private String vallue2;
private String vallue3;
//there getter ans setters
public String execute() throw Exception{
//Fill you values based on the condition
return SUCCESS;
}
}
<package name="JSON" extends="json-default">
<action name="myAction" class="MyAction">
<result type="json"></result>
</action>
Hope this will give you some idea
I am a newbie to java and struts2. I need to change the locale when the user clicks on text in jsp page.I need to do this by setting the session attribute using an action class
Jsp:
(so it would look something like this)
<richtext>[url="switchLang?lang=de"]Deutsch[/url]</richtext>
where "switchLang" does reset the language in the user session.
SwitchLangAction.java:
public class SwitchLangAction extends ActionSupport implements SessionAware {
Map<String, Object> session;
#Override
public String execute(){
session.put("WW_TRANS_I18N_LOCALE", "de");
return SUCCESS;
}
#Override
public void setSession(Map<String, Object> session) {
this.session=session;
}
}
I need to fetch the session object in another .java file and fetch the locale. How do I do it ?
class test{
// I need to fetch the locale here
}
What should I do in switchlang.java class ??? Is my below switchLang.java correct ?
The footer.jsp is a part of every page in the website. I need to reload the current page with language changes.How do I do it ?
footer.jsp:
<richtext>
[url="switchLang?request_locale=de"]Deutsch[/url]
[br]
[url="switchLang?request_locale=en"]English[/url]
</richtext>
switchLangAction.java:
public class SwitchLangAction extends ActionSupport implements SessionAware {
Map<String, Object> session;
#Override
public String execute(){
session.put("WW_TRANS_I18N_LOCALE", "de");
return SUCCESS;
}
#Override
public void setSession(Map<String, Object> session) {
this.session=session;
}
}
Struts.xml: // How to reload the same page ?
<action name="switchLang" method="execute" class="com.mobile.action.SwitchLangAction">
<result name="success" type="redirectAction">?????</result>
</action>
If you want to fetch the session object in other java/action to class to determined user preferred locale than i believe there is other very clean and efficient way S2 provides out of the box.
Default Stack already includes an interceptor named I18n Interceptor which will take care of handling the user locale through the user-session.
This interceptor work around with two parameters
parameterName (optional) - the name of the HTTP request parameter that dictates the locale to switch to and save in the session. By default this is request_locale.
attributeName (optional) - the name of the session key to store the selected locale. By default this is WW_TRANS_I18N_LOCALE.
This interceptor will take care of setting the user locale in ActionContext each time a new request came and will set the locale as per the user request.
You have following option to ask S2 to handle I18N specific work for you
<richtext>[url="switchLang?lang=de"]Deutsch[/url]</richtext> in place of lang=de use the request_locale as parameter key and S2 will handle the rest for you.
If you can not change the parameter key , create a hidden field with name request_locale and set the locale value before form submission.