0

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

根据答案进行的更新

Java 小程序代码

  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;
        }
    }

控制台中打印的消息

信息:JS 发送此用户名null 信息:在数据库中未找到结果信息:警告:FacesMessage(s) 已入队,但可能尚未显示。sourceId=[severity=(错误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)
4

1 回答 1

2

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

1.小程序到JavaScript部分

在您的小程序中引入以下方法:

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)。

于 2013-04-14T07:17:36.930 回答