如何将XHTML页面中的Java applet中的String传递给托管bean

时间:2013-04-14 01:42:20

标签: html jsf-2 xhtml javabeans glassfish-3

据我所知,我正在扩展我之前的问题,以获取打开我的网页的系统的用户名,然后相应地验证该用户。感谢一些有用的建议,经过长时间的阅读和测试,我设法编写了一个非常简单的Java Applet,我将其嵌入login.xhtml页面。但是,现在我停留在下一个适当的步骤,以便将java applet选择的用户名传递给登录托管bean。允许我的网页根据系统的用户名对用户进行身份验证,而用户实际上不必将用户名放在login.xhtml页面中。同时试图寻找下一个合适的步骤,我觉得我的理解上下颠倒。我能选择的最好的是,现在为了将从java applet中获取的用户名传递给登录bean,我将不得不编写JavaScript?但我不确定这是否真的是需要的,或者还有另一个适当的步骤来更优雅地处理这个问题。请原谅我对此有限的了解。

根据答案进行的更新

Java Applet代码

  import java.applet.Applet;

    public class SSOApplet extends Applet {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        String sysUser = null;

        public String getSystemUsername() {
            try {
                sysUser = System.getProperty("user.name");
                return sysUser;
            } catch (Exception e) {
                System.out.println(e);
                return null;
            }

        }

    public void sendToJs() {
        String name = getSystemUsername();
        System.out.println("sendTOJS picked this username of user" + name);
        try {
            JSObject window = JSObject.getWindow(this);
            window.call("updateServer", new Object[] {name});
        } catch (JSException jse) {
            jse.printStackTrace();
        }
    }
    }

来自我的login.xhtml的代码片段

<script type="text/javascript">
    function updateServer(name) {
        document.getElementById('username').value = name;
        document.getElementById('button').click();
    }
</script>
    <object>
            <param name="myApplet" value="SSOApplet.class" />
        </object>

如果有人可以建议下一个合适的步骤,那将会非常有用。非常感谢提前!

UserDaoBean控制器类

public boolean validateUser(String username) {
        try {

            String checkUser = (String) entityManager
                    .createQuery(
                            "select u.username from User u where u.username =:username")
                    .setParameter("username", username).getSingleResult();
            System.out.println("User found in database: " + checkUser);

            if (checkUser.equalsIgnoreCase(username)) {
                System.out.println("Loggin sucessful!");
                return true;
            }
        } catch (NoResultException e) {
            System.out.println("No result found in database");

            return false;
        }
        return false;

    }

登录管理Bean

@ManagedBean(name = "loginBean")
@RequestScoped
public class LoginBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @EJB
    private UserDaoBean uDB;
    @EJB
    private UserGroupDaoBean uGDB;
    private User userId;

    SSOApplet myapplet = new SSOApplet();

    public String username = myapplet.getSystemUsername();

//  private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String login() {
        FacesContext context = FacesContext.getCurrentInstance();
System.out.println("JS sent this username" + username);
        if (uDB.validateUser(username)) {
            userId = uDB.findUser(username);

            context.getExternalContext().getSessionMap().put("userId", userId);
            if (uGDB.validateGroup(userId)) {
                return "home.jsf?faces-redirect=true&amp;includeViewParams=true";
            }
            return "normalHome.jsf?faces-redirect=true&amp;includeViewParams=true";

        } else {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary("Username doesn't exists! OR User is trying to login from someone else's account");
            context.addMessage("", message);
            return null;
        }
    }

消息在控制台中打印

INFO:JS发送了这个usernamenull 信息:数据库中未找到任何结果 信息:警告:FacesMessage已入队,但可能尚未显示。 sourceId = [severity =(ERROR 2),summary =(用户名不存在!或者用户正在尝试从其他人的帐户登录),detail =(用户名不存在!或者用户正在尝试从其他人的帐户登录)]

在Bean中调用Applet后出现异常

WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.ClassNotFoundException: netscape.javascript.JSException
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
    at beans.LoginBean.<init>(LoginBean.java:31)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:372)
    at java.lang.Class.newInstance(Class.java:325)
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:103)
    at com.sun.el.parser.AstValue.getTarget(AstValue.java:149)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:237)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用JSObject类,它允许Java与来自Applet的JavaScript进行通信,以您的字符串作为参数来调用JavaScript函数,该函数将执行更新服务器端托管的工作豆。

1。 Applet到JavaScript部分

在applet中引入以下方法:

public void sendToJs() {
    String name = getSystemUsername();
    try {
        JSObject window = JSObject.getWindow(this);
        window.call("updateServer", new Object[] {name});
    } catch (JSException jse) {
        jse.printStackTrace();
    }
}

2。 JavaScript更新

function updateServer(name) {
    document.getElementById('username').value = name;
    document.getElementById('button').click();
}

3。 JSF视图到JSF支持bean

<h:form prependId="false">
    <h:inputHidden id="username"/>
    <h:commandButton id="button" style="display:none">
        <f:ajax execute="@form/>
    </h:commandButton>
</h:form>

你可以注意到,如果使用Primefaces(查找<p:remoteCommand>)和jQuery这样的JS库,代码就会减少。另请注意,用户名可以通过POST / GET直接从applet发送到一个特殊的专用servlet进行处理(查找Apache的HttpClient)。