java - 使用java和htmlunit获取vbulletin中用户的用户组

标签 java authentication htmlunit vbulletin

我正在开发一个登录系统,用于检查用户是否位于特定的用户组中。

如果用户位于用户组“Access”中,那么我想向他们显示下一个表单。如果他们位于“注册用户”用户组中,则会显示“抱歉,您没有访问权限”

这是我到目前为止的代码:这将使用表单上显示的 2 个文本框进行登录。

我知道我不应该调用“gettext();”在密码字段上,但我不知道如何编码,以便 htmlunit 理解字符,并且如果我写“getpassword()”,则不会放入数组的字符

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package testmysql.gui;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;

/**
 *
 * @author Kjetil
 */
public class Login extends javax.swing.JFrame {

    public String setuser;
    public String setpass;
    public char[] input;
    /**
     * Creates new form Login
     */
    public Login() {
        initComponents();
        setLocationRelativeTo(null);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        txtboxPass = new javax.swing.JPasswordField();
        txtboxUser = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1));

        txtboxPass.setText("jPasswordField1");
        getContentPane().add(txtboxPass, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, -1));

        txtboxUser.setText("jTextField1");
        getContentPane().add(txtboxUser, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 110, -1));

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         


         setuser = txtboxUser.getText();
         setpass = txtboxPass.getText();

         Login();

    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JPasswordField txtboxPass;
    private javax.swing.JTextField txtboxUser;
    // End of variables declaration                   





private void Login()
{



        try {
            WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(false); // I think this speeds the thing up
            webClient.getOptions().setRedirectEnabled(true);
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());
            webClient.getCookieManager().setCookiesEnabled(true);

            String url = "http://svergja.com/forum";
            String name = setuser;
            String pass = setpass;

            HtmlPage page = webClient.getPage(url);

            System.out.println(
                    "1st page : " + page.asText());

            HtmlForm form = (HtmlForm) page.getElementById("navbar_loginform");
            HtmlInput uName = (HtmlInput) form.getByXPath("//*[@id=\"navbar_username\"]").get(0);

            uName.setValueAttribute(name);
            HtmlPasswordInput password = (HtmlPasswordInput) form.getByXPath("//*[@id=\"navbar_password\"]").get(0);

            password.setValueAttribute(setpass);
            HtmlSubmitInput button = form.getInputByValue("Log in"); 
            //(HtmlSubmitInput) form.getByXPath("//*[@id=\"loginbutton\"]").get(0);

            WebWindow window = page.getEnclosingWindow();
            button.click();


            while (window.getEnclosedPage() == page) {
                // The page hasn't changed.
                Thread.sleep(500);
            }
// This loop above will wait until the page changes.
            page = (HtmlPage) window.getEnclosedPage();

            System.out.println(
                    "2nd Page : " + page.asText());

            webClient.closeAllWindows();
        } catch (Exception ex) {
        }



}


}

如果登录成功,我想开始检查用户的用户组 ID。如果我登录,我的用户组是管理员。我将添加一个测试用户,以便您可以登录并亲自查看。

(使用“您将属于用户组(“注册用户”)”登录)

论坛网址:http://svergja.com/forum

用户名:stackoverflow

密码:stackit123

(测试用户信息)

最佳答案

登录成功后,使用anchor点击个人资料链接,然后使用span获取用户组。 代码的更改将是:

   private void Login() throws FailingHttpStatusCodeException, MalformedURLException, IOException
        {
            WebClient client = new WebClient();
            client.setJavaScriptEnabled(false);
            HtmlPage page = client.getPage("http://svergja.com/forum/");

            HtmlForm form = (HtmlForm) page.getElementById("navbar_loginform");

            HtmlTextInput username = (HtmlTextInput) page.getElementById("navbar_username");
                username.setValueAttribute("stackoverflow");
            HtmlPasswordInput password = (HtmlPasswordInput) page.getElementById("navbar_password");
                password.setValueAttribute("stackit123");
            HtmlSubmitInput button = form.getInputByValue("Log in"); 
            page = button.click();

            List<HtmlAnchor> anchorList = page.getAnchors();
                for (HtmlAnchor htmlAnchor : anchorList) {
                    if(htmlAnchor.getAttribute("href").contains("member.php?"))
                    {
                        page = htmlAnchor.click();
                    }
                }

                HtmlSpan span = (HtmlSpan) page.getElementById("userinfo");
                DomNodeList<DomNode> nodeList = span.getChildNodes();

                    for (DomNode domNode : nodeList) {

                        NamedNodeMap map = domNode.getAttributes();
                        Node node = map.getNamedItem("class");
                          if(node != null && node.getNodeValue() != null && node.getNodeValue().equals("usertitle"))
                          {
                                System.out.println("The usergroup is "+domNode.getTextContent());
                          }
                    }
            }

关于java - 使用java和htmlunit获取vbulletin中用户的用户组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21936934/

相关文章:

java - HtmlUnit 的 Click( ) 函数不起作用

seo - 如何使用 htmlunit + page.asXml 方法保留我的文档类型

java - java中的MaskFormatter

java - 为什么我的计算机在使用 String(char[]ch) 代码时发出蜂鸣声?

iphone - Twitter:身份验证已更改?应用程序突然在身份验证窗口(钛)上崩溃

svn - Jenkins Subversion 插件凭据错误

java - 在 JPA (Hibernate) 中保存非持久对象 ID

java - 为什么我的 0-16129 索引数组不为空,但其余索引为空?

c# - 在 ASP.net MVC 单页应用程序中删除身份验证

java - Javascript 更新后获取更改后的 HTML 内容? (html单元)