2

我试图将参数从 java 小程序页面传递到 php 页面,特别是在 theme-woocommerce.php 中。Java 页面将涉及将特定关键字发送到 theme-woocommerce.php 的过程。

例如:

用户将输入句子“我想买蓝色球衣”。用户将单击“发送”按钮 Java 部分将处理并获取关键字“Blue Jersey”

然后同时,“Blue Jersey”关键字将被发送到使用http-post的php页面。

我现在面临的问题是我真的不知道应该如何以及在哪里将 post 数组放在 php 页面中。

这是将参数传递给php页面的java部分:

try {  



                String data2 = URLEncoder.encode("keyword", "UTF-8") + "=" + URLEncoder.encode(system.askquestion(instring,outstring,getkeyword)[1], "UTF-8"); 
                String data =    data2 ;  

                String inLine;  

                URL u1 = new URL("http://localhost/echo.php");  
                URLConnection uc1 = u1.openConnection();  

                uc1.setDoOutput(true);  
                OutputStreamWriter out = new OutputStreamWriter(uc1.getOutputStream());  
                out.write(data); 
                out.flush();  

                BufferedReader in = new BufferedReader( new InputStreamReader( uc1.getInputStream() ) );  

                while ((inLine = in.readLine()) != null) {  
                    System.out.println(inLine);  
                }  

                in.close();  
            }  
            catch( Exception E ) {  
                E.printStackTrace();  
            }  
        }
        return false;
    }

这个是theme-woocommerce.php 代码:

<form role="search" method="get" id="searchform" class="searchform" action="<?php echo home_url();?>">
        <label class="screen-reader-text" for="s"><?php _e('Search for:', 'woothemes'); ?></label>
        <input type="text" value="<?php the_search_query(); ?>" name="s" id="s"  class="field s" placeholder="<?php _e('Search for products', 'woothemes'); ?>" />
        <input type="image" class="submit btn" name="submit" value="<?php _e('Search', 'woothemes'); ?>" src="<?php echo get_template_directory_uri(); ?>/images/ico-search.png">
        <?php if ($woo_options['woo_header_search_scope'] == 'products' ) { echo '<input type="hidden" name="post_type" value="product" />'; } else { echo '<input type="hidden" name="post_type" value="post" />'; } ?>
    </form>
    <div class="fix"></div>

这是我的问题:

  1. 我可以将参数传递给 theme-woocommerce.php
  2. 我应该如何以及在哪里将$_POST["keyword"]放入 theme-woocommerce.php
  3. 我是否可以使用从 java 页面接收输入的函数搜索。

    public boolean handleEvent(Event e)
    { String instring, outstring,getkeyword = null ; if ((( e.target instanceof TextField ) || ( e.target instanceof Button )) && ( e.id == Event.ACTION_EVENT )) { instring = questions.getText();

            outstring   = new String();
            if ( instring.length() > 0 ) {
                answer.appendText("\nYou: " + instring + "\n" );
                answer.appendText( "Faris: " + system.askquestion(instring,outstring,getkeyword) [0] + "\n" );
    
            questions.setText(" ");
        }
         if ( e.target instanceof Button ) {
             questions.requestFocus();
            }
    
         String truee = URLEncoder.encode(system.askquestion(instring , outstring, getkeyword)[1], "UTF-8");
         String formURL = "http://localhost/echo.php"; // this should be whatever home_url() in PHP returns
         URL url = new URL(formURL + "?s=" + truee); // s because there is <input ... name="s"...> in the form
         InputStream inputStream = url.openStream();
         try {
             // ... process the returned response
         } finally {
             inputStream.close();
         }
    

这是整个java编码

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;
import java.io.*;


import javax.swing.JPanel;



  public class VirtualAssistant extends Applet   {
//Declare the variables
    Image poster;
    Button askButton;
    TextField questions;
    TextArea answer;
    String newline;
    boolean     inited      = false;

    Responder   system;







    String      responderfile    = new String( "VirtualAssistant.dat" );



    public void init(){
         if ( !inited ) {




                try {
                    system  = new Responder( getDocumentBase(), responderfile );
                } catch ( IOException e ) {
                    System.out.println( "Can't open response file [" +
                        responderfile + "]" );
                    e.printStackTrace();
                }



                setSize(330,500);
        //Tell the applet not to use a layout manager. 
        setLayout(null);

        //Get image file
        poster=getImage(getDocumentBase(), "avatar.jpg");


        //create an object for textfield and button
        this.questions = new TextField(300);

        this.answer = new TextArea("Faris: I'm the Virtual Assistant. How can I help you?");
        answer.setEditable( false );

        this.askButton = new Button("Ask Me");



        //this.answerBox = new text(20);

         //add the button to the layout
         this.add(questions);
         this.add(answer);
         this.add(askButton);

         //Position of TextField and Button
         questions.setBounds(20,270,240,25); 
         answer.setBounds(20,300,290,200);
         askButton.setBounds(260,270,50,25); 


         /*RespondsQuestions = new TextArea( "Welcome to Dialogue Based Train Information System. How may I help you?\n", 20, 150 );
         RespondsQuestions.setEditable( true );*/

         //
         //askButton.addActionListener(this);
         questions.requestFocus();

            inited  = true;
         }
    }

    public void paint (Graphics g){
        Font font = new Font("Arial", Font.BOLD, 12);
         int height = font.getSize();

            g.setFont(font);


        //set image image width and height
        int imagewidth = 250;
        int imageheight = 250;

        //Positioning text and image
        g.drawImage(poster,15,30,imagewidth,imageheight,this);
        g.drawString("How Can I Help You?",180,130);
        g.drawString("Chatting with Virtual Assistant",60,20);

        //g.drawString(AskQuestions.getText(),20,100); 
    }



    public boolean handleEvent(Event e)  
    { 
        String instring, outstring,getkeyword = null ;
        if ((( e.target instanceof TextField ) || ( e.target instanceof Button )) &&
                ( e.id == Event.ACTION_EVENT )) 
        {
            instring    = questions.getText();

            outstring   = new String();
            if ( instring.length() > 0 ) {
                answer.appendText("\nYou: " + instring + "\n" );
                answer.appendText( "Faris: " + system.askquestion(instring,outstring,getkeyword) [0] + "\n" );

            questions.setText(" ");
        }
         if ( e.target instanceof Button ) {
             questions.requestFocus();
            }
         try {  


                //String data1 = URLEncoder.encode("answer", "UTF-8") + "=" + URLEncoder.encode(system.askquestion(instring,outstring,getkeyword)[0], "UTF-8");  
                String encodedKW = URLEncoder.encode("keyword", "UTF-8") + "=" + URLEncoder.encode(system.askquestion(instring,outstring,getkeyword)[1], "UTF-8"); 
                String keywords;
                String data =   encodedKW ;  

                String inLine;  

                URL u1 = new URL("http://localhost/echo.php");
                //URL u1 = new URL("http://smartjersionline.owhbisnes.com/wp-content/plugins/woocommerce/woocommerce-template.php" + "?s=" + encodedKW );  
                URLConnection uc1 = u1.openConnection();  

                uc1.setDoOutput(true);  
                OutputStreamWriter out = new OutputStreamWriter(uc1.getOutputStream());  
                out.write(data); 
                out.flush();  

                BufferedReader in = new BufferedReader( new InputStreamReader( uc1.getInputStream() ) );  

                while ((inLine = in.readLine()) != null) {  
                    System.out.println(inLine);  
                }  

                in.close();  
            }  
            catch( Exception E ) {  
                E.printStackTrace();  
            }  
        }


        return false;
    }









    public static void main( String args[] ) {
        Frame f         = new Frame( "Virtual Assistant/Application" );
        VirtualAssistant session   = new VirtualAssistant();

        session.init();








    }


    class Responder {



        String[] replies    = new String[ 600 ];
        String[] keywords   = new String[ 400 ];
        String  previous    = new String();         // previous question
        int keyword;                                // index into keyword array
        int numkeys;                                // total number of keys read in
        int maxkey          = 0;                    // number of keywords
        int minreply        = 0;                    // first reply for current keyword.
        int maxreply        = 0;                    // last reply for current keyword





        int[] first         = new int[ 400 ];       // first reply for keyword number in subscript.
        int[] last          = new int[ 400 ];       // last reply   "     "      "     "     "    .
        int[] offset        = new int[ 400 ];       // offset from first reply for each keyword.




        String  trace       = new String();

        Responder( URL baseURL, String respfile ) throws IOException {
            InputStream     file;
            DataInputStream dis;
            String          line;
            int             numkeys;
            boolean         isreply = false;

            file    = ( new URL( baseURL, respfile )).openStream();
            dis     = new DataInputStream( file );

            numkeys = 0;
            while (( line = dis.readLine()) != null ) {
                line = line.trim();
                if ( !( line.startsWith( "//" )) && ( line.length() != 0 )) {



                    if ( line.startsWith( "!" )) {
                        isreply = true;
                    } else if ( line.startsWith( "." )) {

                        isreply = false;


                        for ( keyword = ( maxkey - numkeys ); keyword < maxkey; keyword++ ) {
                            first[ keyword ]    = minreply;
                            last[ keyword ]     = maxreply - 1;
                        }
                        numkeys     = 0;                        // reset new key count
                        minreply    = maxreply;                 // point at next slot
                    } else {                                    // store the line

                        if ( isreply ) {
                            replies[ maxreply++ ]   = line;
                        } else {
                            keywords[ maxkey++ ]    = " " + line + " ";
                            numkeys++;
                        }
                    }
                }
            }
        }



        public String[] askquestion( String question, String answer,String returnkeyword) {
            String temp         = new String();
            String remains      = new String();     // remainder of question
            String NOKEYFOUND   = new String( " NOKEYFOUND " );
            int pos;
            int i;
            Character curchar;
            int test;
            boolean addQMark    = false;

            question    = question.toUpperCase();
            for ( i = 0; i < question.length(); ++i ) {
                curchar = new Character( question.charAt( i ));
                test    = curchar.charValue();
                if ((( test >= 'A' ) && ( test <= 'Z' )) ||
                    (( test >= '0' ) && ( test <= '9' )) ||
                    ( test == ' ' )) {

                    temp    = temp + curchar;
                }
            }
            temp    = " " + temp + " ";





            for ( i = 0, pos = 0, keyword = 0; i < maxkey; i++ ) {
                if (( pos = temp.indexOf( keywords[ i ] )) != -1 ) {
                    keyword = i;

                    if (( keyword < maxkey ) &&
                        ( keywords[ keyword ] != NOKEYFOUND )) {
                        remains = temp.substring( pos - 1 + keywords[ i ].length());
                    } else {
                        remains = "";       // ???
                    }
                    break;
                }
            }
            if ( keyword == 0 ) {       // find NOKEYFOUND set
                for ( i = 0; i < maxkey; i++ ) {
                    if ( keywords[ i ].equals( NOKEYFOUND )) {
                        keyword = i;
                        break;
                    }
                }
                remains = "";
            }



                if (keywords[keyword].equals(  " BLUE JERSEY " ))
                    returnkeyword = keywords[keyword];
                else if (keywords[keyword].equals(  " RED JERSEY " ))
                    returnkeyword = keywords[keyword];
                else if (keywords[keyword].equals(  " WHITE JERSEY " ))
                    returnkeyword = keywords[keyword];













               // now get reply using the keyword number

            answer  = replies[ first[ keyword ] + offset[ keyword ]];







            offset[ keyword ]++;
            if ( offset[ keyword ] + first[ keyword ] > last[ keyword ] ) {
                offset[ keyword ] = 0;
            }



            for ( i = 0; i < maxkey; i++ ) {
                if ( first[ i ] == first[ keyword ] ) {
                    offset[ i ] = offset[ keyword ];
                }
            }

            // return the answer

            return new String[]{answer,returnkeyword};

        }
        //return new String[]{answer,returnkeyword};
    }


       }

这是整个主题-woocommerce.php

<?php
/*-----------------------------------------------------------------------------------*/
/* Any WooCommerce overrides and functions can be found here
/*-----------------------------------------------------------------------------------*/

// Check WooCommerce is installed first
add_action('wp_head', 'woostore_check_environment');

function woostore_check_environment() {
 if (!class_exists('woocommerce')) wp_die(__('WooCommerce must be installed',         'woothemes')); 
}

  // Add html5 shim
 add_action('wp_head', 'wootique_html5_shim');
 function wootique_html5_shim() {
 ?>
 <!-- Load Google HTML5 shim to provide support for <IE9 -->
 <!--[if lt IE 9]>
 <script src="https://html5shim.googlecode.com/svn/trunk/html5.js"></script>
 <![endif]-->
<?php
 }

 // Disable WooCommerce styles 
 define('WOOCOMMERCE_USE_CSS', false);

 /*-----------------------------------------------------------------------------------  */
/* Header
   /*-----------------------------------------------------------------------------------*/

//Parameter plugin
global $wp_query;

if (isset($wp_query->query_vars['keyword']))
{
print $wp_query->query_vars['keyword'];
    }



 // Hook in the search
 add_action('woo_nav_before', 'wootique_header_search');
  function wootique_header_search() {
global $woo_options;
?>

<div id="search-top">
        <form role="search" method="get" id="searchform" action="<?php echo       esc_url( home_url( '/'  ) ); ?>">
        <div>
            <label class="screen-reader-text" for="s"><?php _e( 'Search    for:', 'woocommerce' ); ?></label>
            <input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder="<?php _e( 'Search for products', 'woocommerce' ); ?>" />
            <input type="submit" id="searchsubmit" value="query_vars["keyword"]" />
            <input type="hidden" name="post_type" value="product" />
        </div>
    </form>


</div><!-- /.search-top -->
<?php
    }

   add_action('woo_nav_after', 'wootique_cart_button', 10);
   function wootique_cart_button() {
   echo current(woostore_header_add_to_cart_fragment());
   }

   add_action('woo_nav_after', 'wootique_checkout_button', 20);
   function wootique_checkout_button() {
   global $woocommerce;
   ?>
   <ul id="account-nav" class="nav fr">

  <?php
   if (sizeof($woocommerce->cart->cart_contents)>0) :
    echo '<li class="checkout"><a href="'.$woocommerce->cart-   >get_checkout_url().'">'.__('Checkout','woothemes').'</a></li>';
endif; 
?>

   </ul>
  <?php
  }

// Remove WC sidebar
remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10);

// Adjust markup on all WooCommerce pages
                               remove_action( 'woocommerce_before_main_content',        'woocommerce_output_content_wrapper', 10);
  remove_action( 'woocommerce_after_main_content',   'woocommerce_output_content_wrapper_end', 10);

 add_action('woocommerce_before_main_content', 'woostore_before_content', 10);
 add_action('woocommerce_after_main_content', 'woostore_after_content', 20);

   // Fix the layout etc
     function woostore_before_content() {
?>
<!-- #content Starts -->
<?php woo_content_before(); ?>
   <div id="content" class="col-full">

    <!-- #main Starts -->
    <?php woo_main_before(); ?>
    <div id="main" class="col-left">
     <?php
    }
    function woostore_after_content() {
?>    
        <?php if ( is_search() && is_post_type_archive() ) { add_filter(        'woo_pagination_args', 'woocommerceframework_add_search_fragment', 10 ); } ?>
    <?php woo_pagenav(); ?>
    </div><!-- /#main -->
           <?php woo_main_after(); ?>

        </div><!-- /#content -->
    <?php woo_content_after(); ?>
       <?php
       }

    function woocommerceframework_add_search_fragment ( $settings ) {
$settings['add_fragment'] = '&post_type=product';
return $settings;
     } // End woocommerceframework_add_search_fragment()

    // Add the WC sidebar in the right place
    add_action( 'woo_main_after', 'woocommerce_get_sidebar', 10);

  // Remove breadcrumb (we're using the WooFramework default breadcrumb)
  remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0);
  add_action( 'woocommerce_before_main_content', 'woostore_breadcrumb', 01, 0);

   function woostore_breadcrumb() {
global  $woo_options;
if ( $woo_options[ 'woo_breadcrumbs_show' ] == 'true' ) {
    woo_breadcrumbs();
}
    }

   // Remove pagination (we're using the WooFramework default pagination)
   remove_action( 'woocommerce_pagination', 'woocommerce_pagination', 10 );

  // Adjust the star rating in the sidebar
  add_filter('woocommerce_star_rating_size_sidebar', 'woostore_star_sidebar');

  function woostore_star_sidebar() {
return 12;
   }

  // Adjust the star rating in the recent reviews
  add_filter('woocommerce_star_rating_size_recent_reviews', 'woostore_star_reviews');

  function woostore_star_reviews() {
return 12;
  }

  // Change columns in product loop to 3
  add_filter('loop_shop_columns', 'woostore_loop_columns');

  function woostore_loop_columns() {
return 3;
  }

   // Change columns in related products output to 3

     remove_action( 'woocommerce_after_single_product_summary',     'woocommerce_output_related_products', 20);
    add_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20);

  function woocommerce_output_related_products() {
   woocommerce_related_products(3,3); // 3 products, 3 columns
  }

   // Display 12 products per page
  add_filter('loop_shop_per_page', create_function('$cols', 'return 12;'));

 // Move the price below the excerpt on the single product page
  remove_action( 'woocommerce_template_single_summary',     'woocommerce_template_single_price', 10, 2);
   add_action( 'woocommerce_template_single_summary', 'woocommerce_template_single_price', 25, 2);

       // Handle cart in header fragment for ajax add to cart
         add_filter('add_to_cart_fragments', 'woostore_header_add_to_cart_fragment');

           function woostore_header_add_to_cart_fragment(  ) {
           global $woocommerce;

$fragments['#btn-cart'] = '
<div id="btn-cart" class="fr">
    <a href="'.$woocommerce->cart->get_cart_url().'" title="'.__('View your shopping   cart', 'woothemes').'">
        <span>'.sprintf(_n('%d item &ndash; ', '%d items &ndash; ',      $woocommerce->cart->get_cart_contents_count(), 'woothemes'), $woocommerce->cart- >get_cart_contents_count()) . $woocommerce->cart->get_cart_total() . '</span>
    </a>
</div>
';

return $fragments;

           }

*编辑代码 theme-woocommerce.php*** (miffet 建议)

<head profile="http://gmpg.org/xfn/11">
<script type="text/javascript">
this.name = "smartjersionline";
</script> 
</head>

<?php
/*-----------------------------------------------------------------------------------*/
/* Any WooCommerce overrides and functions can be found here
/*-----------------------------------------------------------------------------------*/

// Check WooCommerce is installed first
add_action('wp_head', 'woostore_check_environment');

   function woostore_check_environment() {
 if (!class_exists('woocommerce')) wp_die(__('WooCommerce must be installed',  'woothemes')); 

}

java页面的编辑代码(miffet建议)

try {  


                //String data1 = URLEncoder.encode("answer", "UTF-8") + "=" + URLEncoder.encode(system.askquestion(instring,outstring,getkeyword)[0], "UTF-8");

                //String encodedKW = URLEncoder.encode("keyword", "UTF-8") + "=" + URLEncoder.encode(system.askquestion(instring,outstring,getkeyword)[1], "UTF-8"); 
                //String keywords;
                //String data =   encodedKW ;  

                String encodedKW = URLEncoder.encode(system.askquestion(instring , outstring, getkeyword)[1], "UTF-8");
                String formURL = "http://smartjersionline.owhbisnes.com/wp-content/plugins/woocommerce/woocommerce-template.php"; // this should be whatever home_url() in PHP returns
                URL url = new URL(formURL + "?s=" + encodedKW + "&post_type=product"); // s because there is <input name="s"...> in the form
                getAppletContext().showDocument(url, "smartjersionline"); // the second argument is target window name

                String inLine;  

                URL u1 = new URL("http://localhost/echo.php");
                //URL u1 = new URL("http://smartjersionline.owhbisnes.com/wp-content/plugins/woocommerce/woocommerce-template.php" + "?s=" + encodedKW );  
                URLConnection uc1 = u1.openConnection();  

                uc1.setDoOutput(true);  
                OutputStreamWriter out = new OutputStreamWriter(uc1.getOutputStream());  
                out.write(encodedKW); 
                out.flush();  

                BufferedReader in = new BufferedReader( new InputStreamReader( uc1.getInputStream() ) );  

                while ((inLine = in.readLine()) != null) {  
                    System.out.println(inLine);  
                }  

                in.close();  
            }  
4

1 回答 1

0

目前尚不清楚您要对 in 中的关键字做什么theme-woocommerce.php。我了解您正在尝试发送请求,就好像您在问题中列出的表格已提交一样。在这种情况下,您不需要$_POST["keyword"],因为表单具有不同的请求变量,例如“s”(name="s")。

此外,表单使用 GET 方法,因此您可以更轻松地将关键字放在查询字符串中请求的 URL 中。

最后,您没有关闭 Java 代码中的连接,这也可能是一个问题。


编辑:如果目标是在原始窗口中打开 URL http://smartjersionline.owhbisnes.com/?s=blue&post_type=product,那么您尝试从 Java 代码在浏览器中进行重定向。

这超出了我的专业领域。不过我发现了这篇文章。需要的是

  1. 命名目标窗口。您可以通过将以下脚本放入<head>网页部分(此处)来执行此操作:

    <script type="text/javascript">
        this.name = "smartjersionline";
    </script> 
    
  2. 在您的 Java 代码中,调用getAppletContext().showDocument()

    String encodedKW = URLEncoder.encode(system.askquestion(instring , outstring, getkeyword)[1], "UTF-8");
    String formURL = "http://smartjersionline.owhbisnes.com/"; // this should be whatever home_url() in PHP returns
    URL url = new URL(formURL + "?s=" + encodedKW + "&post_type=product"); // s because there is <input name="s"...> in the form
    getAppletContext().showDocument(url, "smartjersionline"); // the second argument is target window name
    

    另请参阅javadoc

于 2013-05-23T18:46:39.310 回答