below is the code snippet, I want to retrieve the selected value, the autocomplete works perfectly fine,
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<script type="text/javascript">
function sayPramod()
{
alert("hiii");
}
</script>
<sx:head />
</head>
<body>
<h1>Struts 2 autocompleter + JSON example</h1>
<s:form >
<s:url id="databaseList" action="databaseJSON"
/>
<sx:autocompleter label="What's your favorite Database Server?"
href="%{databaseList}" name="yourFavDatabase"
/>
<s:submit value="submit" name="submit" onclick="sayPramod();" />
</s:form>
</body>
</html>
The java code is:
package com.krcl.rap.common.menu.action;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.Action;
public class DatabaseJSON {
private Map<String, String> databases = new HashMap<String, String>();
public DatabaseJSON(){
databases.put("Google", "www.google.com");
databases.put("Oracle", "Oracle");
databases.put("PostgreSQL", "PostgreSQL");
databases.put("Microsoft SQL Server", "Microsoft SQL Server");
databases.put("DB2", "DB2");
}
public String execute() {
return Action.SUCCESS;
}
public Map<String, String> getDatabases() {
return databases;
}
public void setDatabases(Map<String, String> databases) {
this.databases = databases;
}
}
struts.xml
<package name="json" namespace="/" extends="json-default">
<action name="databaseJSON" class="com.krcl.rap.common.menu.action.DatabaseJSON">
<result type="json" >
<param name="root">databases</param>
</result>
</action>
</package>
<package name="default" namespace="/" extends="struts-default">
<action name="autoCompleterAction"
class="com.krcl.rap.common.menu.action.AutoCompleterAction"
method="display">
<result name="none">pages/autocompleter-json.jsp</result>
</action>
<action name="resultAction"
class="com.krcl.rap.common.menu.action.AutoCompleterAction" >
<result name="success">pages/result.jsp</result>
</action>
</package>
Use
<sx:autocompleter label="What's your favorite Database Server?"
href="%{databaseList}" name="yourFavDatabase"
id="yourFavDatabase"/>
in your jsp and
var yourFavDb=dojo.widget.byId('yourFavDatabase').getValue();
in your script to get the value. If you want to get the selected value in your Action class it will come on its own, once you submit the form.
Related
I use Struts 2.3.32 and this is the code.
methodPrefix.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:form action="methodPrefix" theme="simple">
name: <br/>
<s:textfield name="name"/>
<br><br>
<s:submit value="Create Person"/>
<s:submit name="method:cancel" value="Cancel"/>
</s:form>
</body>
</html>
MethodPrefixAction.java
public class MethodPrefixAction
{
private String name;
private String message;
public String execute() throws Exception
{
message = name + " create";
return "success";
}
public String cancel() throws Exception
{
message = "cancel";
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.mapper.action.prefix.enabled" value="true" />
<package name="default" extends="struts-default" namespace="">
<action name="goMethodPrefixPage">
<result>/chapter4/methodPrefix.jsp</result>
</action>
<action name="methodPrefix" class="example.chapter4.MethodPrefixAction">
<result>/chapter4/methodPrefixResult.jsp</result>
</action>
</package>
</struts>
when I push Cancel button, It do not call cancel() method, just call execute() method.
I don't know why method: prefix not work.
I searched a lot, and I know method: prefix configuration is false by default in Struts 2.3.32, so I used a constant..... but it did not work
This constant
<constant name="struts.mapper.action.prefix.enabled" value="true" />
works only for action: prefix, not a method: prefix. So you should use the action attribute to submit tag.
<s:submit action="cancel" value="Cancel"/>
Note: If you have DMI turned off the action: prefix is still available.
This tutorial explains it and this tutorial shows how to do validation
Method MethodPrefixAction.execute should return success or cancel string.
In struts.xml you can redirect user to different pages based on return string:
<action name="methodPrefix" class="example.chapter4.MethodPrefixAction">
<result name="success">/chapter4/methodPrefixResult.jsp</result>
<result name="cancel">/chapter4/methodPrefix.jsp</result>
</action>
I am using primefaces 5.2 dialog framework to popup a dialog from my backing bean. That dialog with a simple login form.
main.xhtml as:
<h:form prependId="false">
......
<p:commandButton value="#{apps['application.sec.login']}" immediate="true" actionListener="#{loginControlBean.fireLoginDialog}" icon="fa fa-fw fa-sign-in" />
.....
</h:form>
backing bean LoginControlBean.java as:
#Named(value = "loginControlBean")
#SessionScoped
public class LoginControlBean implements Serializable{
private static final Logger logger =Logger.getLogger(LoginControlBean.class.getName());
#Inject
private StaffSession staffSession;
/* ... get/set pairs ...*/
......
public void fireLoginDialog() {
Map<String,Object> options = new HashMap<String, Object>();
options.put("modal", true);
options.put("draggable", false);
options.put("resizable", false);
RequestContext.getCurrentInstance().openDialog("/sec/login", options, null);
}
.......
public void login(ActionEvent event) {
logger.info("Passed in information: User name: "+staffSession.getTempUserName()+" Password: "+staffSession.getTempPassword());
.......
}
login.xhtml as:
<?xml version="1.0" encoding="UTF-8"?>
<!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:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:outputStylesheet library="css" name="default.css"/>
<h:outputStylesheet library="css" name="cssLayout.css"/>
<title>Staff Login</title>
</h:head>
<h:body>
<ui:composition>
<h:form id="loginform">
<p:growl id="logingrowl" sticky="true" showDetail="true" life="60000" />
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="username" value="#{apps['application.sec.username']}" />
<p:inputText id="username" value="#{staffSession.tempUserName}" required="true" label="username" />
<h:outputLabel for="password" value="#{apps['application.sec.password']}" />
<p:password id="password" value="#{staffSession.tempPassword}" required="true" label="password" />
<f:facet name="footer">
<p:commandButton process="#form" value="Login" update="logingrowl" actionListener="#{loginControlBean.login}"/>
</f:facet>
</h:panelGrid>
</h:form>
</ui:composition>
</h:body>
</html>
dialog popup properly and when I input user name and password, then hit login button. I got exception in my backend(server side) log as:
####<Nov 2, 2016 5:20:10 PM AEDT> <Info> <com.longz.ozssc.web.staff.LoginControlBean> <macmini16g.tweedheadstorage.com.au> <OzsscWEBServer> <[ACTIVE] ExecuteThread: '5' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <49d77419-9b42-461a-92bb-25b06f512a63-0000001d> <1478067610444> <[severity-value: 64] [rid: 0] [partition-id: 0] [partition-name: DOMAIN] > <BEA-000000> <Passed in information: User name: null Password: null>
filled in fields in the form were bound to staffSession, but unfortunately, when I tried to access the values from backing bean staffSession, it is "null". Seems form submit is not working.
Any idea??
You didn't set the values of your input fields correctly.
value="#{staffSession.tempUserName}"
You need to add the bean to the values:
value="#{loginControllBean.staffSession.tempUserName}"
This question already has answers here:
How to choose the right bean scope?
(2 answers)
Closed 6 years ago.
I am facing a proplem with the ?faces-redirect=true I want to show the follwoing link http://localhost:8080/FirstJSPApplication/home.xhtml in the url after clicking the submit button in the index.xhtml but when adding ?faces-redirect=true to action="home" I am losing the value of the input field and am just getting Welcome back in the home.xhtml without the value of the username input field.
How can I show home.xhtml in the url after clicking the submit button without losing the username?
MainBean
package com.firstApp;
import javax.faces.bean.ManagedBean;
#ManagedBean
public class MainBean {
private String username;
public MainBean() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
index.xhtml
<!DOCTYPE html>
<html xmlns="htpp://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Facelt Title</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel value="username" for="username" />
<!-- value="#{mainBean.username}" -->
<h:inputText id="username" value="#{mainBean.username}" required="true" requiredMessage="#{msg['msg.username.validation']}" />
<h:message for="username" />
<f:facet name="footer">
<!-- '?faces-redirect=true"' add home.xhtml to the url-->
<h:commandButton value="Submit" action="home?faces-redirect=true" />
</f:facet>
</h:panelGrid>
</h:form>
</h:body>
</html>
home.xhtml
<!DOCTYPE html>
<html xmlns="htpp://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Home pages</title>
</h:head>
<h:body>
<!-- #{mainBean.username} -->
<h:outputLabel value="Welcome back #{mainBean.username}" style="font-size: 25px;"/>
<footer style="margin-top: 300px; border: 1px solid red;">
<h:outputLabel value="#{msg['page.footer.copyright']}"/>
</footer>
</h:body>
</html>
Ok the problem is solved if I add the following notation #SessionScoped to the MainBean class
#ManagedBean
#SessionScoped
public class MainBean {
}
I want to set gwt-locale taking user chosen locale with the help of Spring LocaleContextHolder.
public static final String getCurrentLocale() {
return LocaleContextHolder.getLocale().getLanguage();
}
I actually have login interface in Spring MVC and inner Dashboard in gwtp. The same locale user chooses in outer interface before login has to be passed to gwt as well.
Unfortunately, I don't see any gwt inbuilt Locale setters.
My X.gwt.xml with default locale as kh is :
<inherits name="com.google.gwt.uibinder.UiBinder" />
<inherits name="com.google.gwt.inject.Inject" />
<inherits name="com.gwtplatform.mvp.Mvp" />
<inherits name="gwtquery.plugins.droppable.Droppable"/>
<source path="client" />
<source path="shared" />
<define-configuration-property name="gin.ginjector" is-multi-valued="false"/>
<set-configuration-property name="gin.ginjector" value="com.prayagupd.client.mvp.XGInjector"/>
<set-configuration-property name="UiBinder.useSafeHtmlTemplates" value="true" />
<extend-property name="locale" values="kh" />
<extend-property name="locale" values="en" />
<set-property name="locale" value="kh"/>
<set-property-fallback name="locale" value="kh"/>
<entry-point class="com.prayagupd.client.XEntryPoint"/>
My XEntryPoint.java reads as :
public class XEntryPoint implements EntryPoint {
private final IUserServiceAsync rpc = GWT.create(IUserService.class);
#Override
public void onModuleLoad() {
//
rpc.getLocale(new AsyncCallback<String>() {
#Override
public void onSuccess(String locale) {
GWT.log("Locale From Spring : " + locale);
GWT.log("Locale From GWT : " + LocaleInfo.getCurrentLocale().getLocaleName());
//here i want to set locale to gwt
//something like GWTLocale.setLocale(locale);
}
#Override
public void onFailure(Throwable caught) {
GWT.log(caught.getMessage());
}
});
DelayedBindRegistry.bind(ginjector);
ginjector.getPlaceManager().revealCurrentPlace();
}
}
home.jsp for gwt-loading
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
<%#tag import="java.util.Calendar"%>
<%# tag body-content="scriptless"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spr" tagdir="/WEB-INF/tags"%>
<%# attribute name="isgwt" required="true" type="java.lang.Boolean"%>
<!-- <!DOCTYPE html> -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="shortcut icon" type="image/png" href="/images/favicon.png" />
<script type="text/javascript" src="js/reload.captcha.js"></script>
<script type="text/javascript" src="js/date.picker.js"></script>
<link rel="stylesheet" href="/styles/innerstyle.css" type="text/css" />
<c:if test="${not isgwt}">
<link rel="stylesheet" href="/styles/mainstyler.css" type="text/css" />
<script type="text/javascript" src="js/modernizer.custom.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui-custom.min.js"></script>
<script src="js/jquery.thumbnailScroller.js"></script>
</c:if>
<c:if test="${isgwt}">
<meta name="gwt:property" content="locale=${locale}">
<script type="text/javascript" language="javascript" src="upd/upd.nocache.js"></script>
</c:if>
<script type="text/javascript">
$(window).load(function() {
$('#slider').nivoSlider();
});
</script>
<title><c:out value="${locale}"></c:out><spring:message code="page.header" /></title>
</head>
<body>
<c:choose>
<c:when test="${empty username}">
<div class="header_con">
<div class="header_in">
<spr:header />
<spr:login />
<div class="clear"></div>
</div>
<div class="main_con">
<jsp:doBody />
<spr:footer />
</div>
<div class="clear"></div>
</div>
</c:when>
<c:otherwise>
<div id="mainHolder">
<div id="wrapper">
<spr:headerInner />
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1'
style="position: absolute; width: 0; height: 0; border: 0"></iframe>
<div>
<div id="gwt_holder">
<c:if test="${isgwt}">
<div id="loader" class="loader">
</div>
</c:if>
<div id="gwt"></div>
</div>
</div>
</div>
</div>
</c:otherwise>
</c:choose>
</body>
</html>
Adding ?locale=en or ?locale=kh to gwt url works perfectly, but want to tell GWT only once that I want this locale programmatically and want it to work always with that locale onwards.
When I look at the *.html source code, I can see the injected the <meta> tag with proper locale passed from SpringController.
References
GWT dynamic internationalization, Colin Alworth
How i change the locale language of the application
Use a dynamic host page where you inject the proper <meta name="gwt:property" content="locale=XXX">.
Remember the GWT bootstrap sequence: once your onModuleLoad has been called, the choice of the permutation (which includes the locale) has already been made. You have to alter the bootstrap sequence so it chooses the proper permutation for the user. ?locale=XXX does this (because the locale property has a <property-provider> that reads the locale query-string parameter, among other things), as well as the <meta> above.
See also https://code.google.com/p/google-web-toolkit-incubator/wiki/ServerSideLocaleSelection for some idea (BEWARE: deprecated project!)
Finally, there are a few issues with your *.gwt.xml, starting with kh not being a valid locale.
The workflow for internationalizing your app is as follows:
list your locales:
<extend-property name="locale" value="en" />
<extend-property name="locale" value="fr" />
remove the default locale by setting the locale property to the full list of supported locales:
<set-property name="locale" value="en,fr" />
set the fallback locale:
<set-property-fallback name="locale" value="en" />
Optionally, you can select how the locale is determined using the properties locale.queryparam, locale.cookie, locale.usemeta, locale.useragent, and locale.searchorder (see the I18N.gwt.xml for their default and accepted values).
And finally, add code to select the locale (e.g. the dynamic <meta> above)
The solution inspired by Thomas Broyer,
X.gwt.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.3.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.3.0/distro-source/core/src/gwt-module.dtd">
<module rename-to="x">
<inherits name="com.google.gwt.user.User"/>
<inherits name="com.google.gwt.i18n.I18N" />
<inherits name="com.google.gwt.http.HTTP" />
<inherits name="com.google.gwt.json.JSON"/>
<inherits name="com.google.gwt.uibinder.UiBinder" />
<inherits name="com.google.gwt.inject.Inject" />
<inherits name="com.gwtplatform.mvp.Mvp" />
<inherits name="gwtquery.plugins.droppable.Droppable"/>
<source path="client" />
<source path="shared" />
<define-configuration-property name="gin.ginjector" is-multi-valued="false"/>
<set-configuration-property name="gin.ginjector" value="com.prayagupd.client.mvp.XGInjector"/>
<set-configuration-property name="UiBinder.useSafeHtmlTemplates" value="true" />
<extend-property name="locale" values="kh" />
<extend-property name="locale" values="en" />
<set-property-fallback name="locale" value="kh"/>
<entry-point class="com.prayagupd.client.XEntryPoint"/>
</module>
And , home.jsp
<c:if test="${isgwt}">
<meta name="gwt:property" content="locale=${locale}">
<script type="text/javascript" language="javascript" src="upd/upd.nocache.js"></script>
</c:if>
locale being passed from Spring Controller
{
//...
modelMap.put("locale", locale);
return "home";
}
Thomas Broyer's answer is correct, except one thing. You don't mandatory need to use "dynamic host page", meta tag can be defined dynamically on the client side:
<script type="text/javascript">
$.ajax("rest/service/default-locale").done(function(data) {
if (data) {
var metaLocale = $("<meta name='gwt:property' content='locale=" + data + "'>");
$("head").append(metaLocale);
}
var jsLink = $("<script src='myapp.nocache.js'>");
$("head").append(jsLink);
});
</script>
This way any additional modifications can be done on the client side before GWT app starts.
I have a problem with the propagation of a long running conversation when I redirect the view by the handleNavigation() method. Here is my test code:
I have a conversationscoped bean and two views:
conversationStart.xhtml is called in Browser with URL
http://localhost/tests/conversationStart.jsf?paramTestId=ParameterInUrl
<!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">
<f:metadata>
<f:viewParam name="paramTestId" value="#{conversationTest.fieldTestId}" />
<f:event type="preRenderView" listener="#{conversationTest.preRenderView}" />
</f:metadata>
<h:head>
<title>Conversation Test</title>
</h:head>
<h:body>
<h:form>
<h2>Startpage Test Conversation with Redirect</h2>
<h:messages />
<h:outputText value="Testparameter: #{conversationTest.fieldTestId}"/><br />
<h:outputText value="Logged In: #{conversationTest.loggedIn}"/><br />
<h:outputText value="Conversation ID: #{conversationTest.convID}"/><br />
<h:outputText value="Conversation Transient: #{conversationTest.convTransient}"/><br />
<h:commandButton action="#{conversationTest.startLogin}" value="Login ->" rendered="#{conversationTest.loggedIn==false}" /><br />
<h:commandLink action="/tests/conversationLogin.xhtml?faces-redirect=true" value="Login ->" rendered="#{conversationTest.loggedIn==false}" /><br />
</h:form>
<h:link outcome="/tests/conversationLogin.xhtml" value="Login Link" rendered="#{conversationTest.loggedIn==false}">
<f:param name="cid" value="#{conversationTest.convID}"></f:param>
</h:link>
</h:body>
</html>
The Parameter is written to the beanfield and displayed in the view correctly. There are 3 different possibilities to navigate to the next View. All 3 work fine. The beanfield shows up the next view (conversationLogin.xhtml) too:
<!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">
<h:head>
<title>Conversation Test</title>
</h:head>
<h:body>
<h:form>
<h2>Loginpage Test Conversation with Redirect</h2>
<h:messages />
<h:outputText value="Testparameter: #{conversationTest.fieldTestId}"/><br />
<h:outputText value="Logged In: #{conversationTest.loggedIn}"/><br />
<h:outputText value="Conversation ID: #{conversationTest.convID}"/><br />
<h:outputText value="Conversation Transient: #{conversationTest.convTransient}"/><br />
<h:commandButton action="#{conversationTest.login}" value="Login And Return" /><br />
</h:form>
</h:body>
</html>
When I return to the Startpage by clicking the button the conversation bean still contains all values. So everything is fine. Here is the bean:
package test;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Inject;
import javax.inject.Named;
#Named
#ConversationScoped
public class ConversationTest implements Serializable{
private static final long serialVersionUID = 1L;
final String CONVERSATION_NAME="longRun";
#Inject Conversation conversation;
private boolean loggedIn;
private String fieldTestId;
#PostConstruct
public void init(){
if(conversation.isTransient()){
conversation.begin(CONVERSATION_NAME);
System.out.println("New Conversation started");
}
loggedIn=false;
}
public String getConvID(){
return conversation.getId();
}
public boolean isConvTransient(){
return conversation.isTransient();
}
public boolean getLoggedIn(){
return loggedIn;
}
public String startLogin(){
return "/tests/conversationLogin.xhtml?faces-redirect=true";
}
public String login(){
loggedIn=true;
return "/tests/conversationStart.xhtml?faces-redirect=true";
}
public void preRenderView(ComponentSystemEvent ev) {
// if(!loggedIn){
// System.out.println("Will redirect to Login");
// FacesContext ctx = FacesContext.getCurrentInstance();
// ctx.getApplication().getNavigationHandler().handleNavigation(ctx, null, "/tests/conversationLogin.xhtml?faces-redirect=true");
// ctx.renderResponse();
// }
}
public void setFieldTestId(String fieldTestId) {
System.out.println("fieldTestID was set to: "+fieldTestId);
this.fieldTestId = fieldTestId;
}
public String getFieldTestId() {
return fieldTestId;
}
}
Now comes the problem
As soon as I try to redirect the page in the preRenderView method of the bean (just uncomment the code in the method), using handleNavigation() the bean is created again in the next view instead of using the already created instance. Although the cid parameter is propagated to the next view !
Has anybody an idea what's wrong ?
best regards
Thomas