Js通过PhoneGap调用Java方法并互相传参的。
一、JAVA代码
写一个类,该类继承自Plugin并重写execute方法。
import org.json.JSONA
import android.app.A
import android.app.AlertD
import android.content.ActivityNotFoundE
import android.content.DialogI
import android.content.I
import android.net.U
import android.os.B
import com.phonegap.api.PhonegapA
import com.phonegap.api.P
import com.phonegap.api.PluginR
public class PluginTest extends Plugin { public&static&String&ACTION&=&"hello";
public PluginTest() {
* Executes the request and returns PluginResult.
* @param action
The action to execute.
* @param args
JSONArray of arguments for the plugin.
* @param callbackId
The callback id used when calling back into JavaScript.
A PluginResult object with a status and message.
public PluginResult execute(String action, JSONArray args, String callbackId) {
JSONObject jsonObj = new JSONObject();//可以返回给JS的JSON数据
if (action.equals("hello")) {
String str1= args.getString(0); //获取第一个参数
String str2= args.getString(1); //获取第二个参数
jsonObj.put("str1", str1+"1");
//把参数放到JSONObject对象中
jsonObj.put("str2", str2+"2"); //把参数放到JSONObject对象中
PluginResult r = new PluginResult(PluginResult.Status.OK,jsonObj);
} catch (Exception e) {
e.printStackTrace();
二、在plugins.xml中配置插件
在plugins.xml文件中添加对新插件的配置信息
&?xml version="1.0" encoding="utf-8"?&
&plugin name="App" value="com.phonegap.App"/&
&plugin name="Geolocation" value="com.phonegap.GeoBroker"/&
&plugin name="Device" value="com.phonegap.Device"/&
&plugin name="Accelerometer" value="com.phonegap.AccelListener"/&
&plugin name="Compass" value="com.phonegap.CompassListener"/&
&plugin name="Media" value="com.phonegap.AudioHandler"/&
&plugin name="Camera" value="com.phonegap.CameraLauncher"/&
&plugin name="Contacts" value="com.phonegap.ContactManager"/&
&plugin name="Crypto" value="com.phonegap.CryptoHandler"/&
&plugin name="File" value="com.phonegap.FileUtils"/&
&plugin name="Network Status" value="com.phonegap.NetworkManager"/&
&plugin name="Notification" value="com.phonegap.Notification"/&
&plugin name="Storage" value="com.phonegap.Storage"/&
&plugin name="Temperature" value="com.phonegap.TempListener"/&
&plugin name="FileTransfer" value="com.phonegap.FileTransfer"/&
&plugin name="Capture" value="com.phonegap.Capture"/&
&!-- 新增的插件类配置 name 写你的类名,value写 包名.类名--&
&plugin name="PluginTest" value="com.easyway.barcode.PluginTest "/&
&/plugins&
三、Javascript文件中注册插件
新建一个.js文件,并把该文件和phonegap文件放在同一目录。(新建一个simplePlugin.js文件)
var SimplePlugin = function() {};
//str1和str2是传到JAVA的参数
SimplePlugin.prototype.hello = function(successCallback, failureCallback, str1, str2) {
// exec 內的參數分別是: Success Callback, Failure Callback, Registered Plugin name:就是在XML文件配置的那个所对应的name,
// 'hello'是传入Java文件的execute方法中的参数String action
// name (從 HTML 傳進來的參數)
return PhoneGap.exec(successCallback, failureCallback, 'PluginTest', 'hello', [str1,str2]);
// 这里是 PhoneGap Plugin 的註冊,Plugin 的名稱還有 Native Class 的名稱別打錯了,就是我們剛剛輸入的那些
PhoneGap.addConstructor(function() {
// Register the javascript plugin with PhoneGap
PhoneGap.addPlugin('simpleplugin', new SimplePlugin());
//simpleplugin是插件名称, new SimplePlugin()实例化的是本Javascript的类名
四、在HTML文件中调用方法
在html文件中引入phonegap和插件的js文件,调用方法
&!DOCTYPE html&
&meta charset="utf-8"&
&title&JAVA传参&/title&
&script src="phonegap.js"&&/script& &!--phonegap包--&
&script src="js/jquery.js"&&/script&
&script src="simplePlugin.js"&&/script&&!--自定义的插件文件--&
$(document).ready(function(e) {
$("#btn_test").click(function(){
window.plugins.simplePlugin.hello(
function(result) {
alert("返回的第一个参数:"+result.str1+"返回的第二个参数"+result.str2);
function(error) {
"第一个参数",
"第二个参数"
&button type="button"
id="btn_test"&Click Me!&/button&
阅读(...) 评论()java调用js方法_百度文库
您的浏览器Javascript被禁用,需开启后体验完整功能,
享专业文档下载特权
&赠共享文档下载特权
&100W篇文档免费专享
&每天抽奖多种福利
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
java调用js方法
&&最近在研究这一块,共同进步
阅读已结束,下载本文需要
定制HR最喜欢的简历
下载文档到电脑,同时保存到云知识,更方便管理
加入VIP
还剩2页未读,
定制HR最喜欢的简历
你可能喜欢java类文件里向调用页面输出javascript代码的方法
java类文件里向调用页面输出javascript代码的方法
08-12-26 &匿名提问
请登录后再发表评论!
请登录后再发表评论!
如果你会struts用action类输出也一样.给你一个我的一个actionpackage com.ecg.struts.import java.io.IOEimport java.io.PrintWimport java.util.Limport javax.servlet.http.HttpServletRimport javax.servlet.http.HttpServletRimport org.apache.struts.action.Aimport org.apache.struts.action.ActionFimport org.apache.struts.action.ActionFimport org.apache.struts.action.ActionMimport org.hibernate.Simport org.hibernate.Timport org.json.JSONEimport org.json.JSONOimport po.Himport po.Mimport po.Simport po.Simport publicclass.CommUimport dao.CommSimport dao.SmsDAO;import util.EasySimport util.CharFimport util.GetT/**
* MyEclipse Struts * Creation date: 12-12-2008 *
* XDoclet definition: * @struts.action validate=&true& */public class SmsAction extends Action { /*
* Generated Methods
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws IOException
* @throws JSONException
*/ public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
// TODO Auto-generated method stub
String command = request.getParameter(&command&) ;
response.setContentType( &text/ charset=utf-8& );
PrintWriter out = response.getWriter() ;
request.setCharacterEncoding(&utf-8& ) ;
if ( command != null )
if ( command.equals(&listsms&))
int start =EasyStr.parseInt(request.getParameter(&start&)) ;
int limit = EasyStr.parseInt(request.getParameter(&limit&)) ;
String type = request.getParameter(&type&) ;
CommUser  cmur = (CommUser)request.getSession().getAttribute(&commuser&) ;
JSONObject json = new SmsDAO().getSms(start, limit , type , cmur ) ;
out.print(json) ;
else if ( command.equals(&read&))
String smsid = request.getParameter(&smsid&) ;
boolean b = new SmsDAO().updateSms(smsid) ;
out.print(&{success:true,msg:'更新成功!'}&);
out.print(&{success:false,msg:'更新失败!'}&) ;
else if ( command.equals(&delete&))
String smsid = request.getParameter(&smsid&) ;
boolean b = new SmsDAO().delete(smsid) ;
if ( b == true )
out.print(&数据删除成功!&);
out.print(&数据删除失败!&);
else if ( command.equals(&insert&) )
String type = request.getParameter(&type&) ;
if ( type == null )
if ( type.equals(&sys&))
//String title = CharFilter.ExtjstoChinese(request.getParameter(name)(&title&) );
//String content = CharFilter.ExtjstoChinese(request.getParameter(&content&)) ;
String title = CharFilter.ExtjstoChinese(request.getParameter(&title&)) ;
String content =CharFilter.ExtjstoChinese( request.getParameter(&content&)) ;
String data =  null  ;
   Session session = CommSession.openSession() ;
   Transaction tx =  session.beginTransaction() ;
   
   String hql = &from Smstype where smstypeid=1&  ;
   
   Smstype smstype =(Smstype) CommSession.queryOne(session, hql) ;
   
   Sms sms = new Sms() ;
   
   try
   {
    sms.setContent(content) ;
    sms.setSmstype(smstype) ;
    sms.setSmstitle(title) ;
    sms.setDatetime(new GetTime().getDate()) ;
   
    session.saveOrUpdate(sms) ;
    //提交事务
    tx.commit() ;
   
    //System.out.println(&id:& +sms.getSmsid()) ;
   
    data =  &{success:true,msg:'添加成功!',smsid:& + sms.getSmsid() +  &}& ;
   }
   catch(Exception e )
   {
    e.printStackTrace() ;
    //tx.rollback() ;
   
    data =  &{success:false,msg:'添加失败!'}& ;
   }
   finally
   {
   
    //关闭
   CommSession.closeSession(session) ;
   }
   
   out.print(data) ;
else if ( type.equals(&hospital&))
String sendType = request.getParameter(&sendtype&) ;
if ( sendType.equals(&all&))
String title = CharFilter.ExtjstoChinese(request.getParameter(&title&)) ;
String content =CharFilter.ExtjstoChinese( request.getParameter(&content&) ) ;
String data =  null  ;
   Session session = CommSession.openSession() ;
   Transaction tx =  session.beginTransaction() ;
   
   String hql = &from Smstype where smstypeid=2&   ;
   
   Smstype smstype =(Smstype) CommSession.queryOne(session, hql) ;
   
   //得到管理员ID
   CommUser  cmur = (CommUser)request.getSession().getAttribute(&commuser&) ;
   
   //查找中心
   
   
   if ( cmur.getUserType().equals(&manager&) )
   {
   
   
   String sql = &select hospitalid from hospital order by hospitalid asc  & ;
   
   List list = CommSession.querySQLPage(session, sql, -1 , -1 ) ;
   
   try
   {
   
   for ( int i = 0 ; i & list.size() ; i++  )
   {
   
   
    Sms sms = new Sms() ;
    sms.setContent(content) ;
    sms.setSmstype(smstype) ;
    sms.setSmstitle(title) ;
    sms.setDatetime(new GetTime().getDate()) ;
    sms.setFromid(cmur.getId()) ;
    sms.setToid(Integer.valueOf(((Object)list.get(i)).toString())) ;
   
   
    session.saveOrUpdate(sms) ;
   
   
   
   }
//提交事务
    tx.commit() ;
   
    data =  &{success:true,msg:'添加成功!'}& ;
   
   }
   catch(Exception e )
   {
    e.printStackTrace() ;
    tx.rollback() ;
   
    data =  &{success:false,msg:'添加失败!'}& ;
   }
   finally
   {
   
    //关闭
   CommSession.closeSession(session) ;
   }
   }
   
   
   
   out.print(data) ;
else if ( sendType.equals(&single&))
String hospitalid = request.getParameter(&hospital&) ;
String title = request.getParameter(&title&) ;
String content = request.getParameter(&content&) ;
String data =  null  ;
   Session session = CommSession.openSession() ;
   Transaction tx =  session.beginTransaction() ;
   
   String hql = &from Smstype where smstypeid=2&  ;
   
   Smstype smstype =(Smstype) CommSession.queryOne(session, hql) ;
   
   //得到管理员ID
   CommUser  cmur = (CommUser)request.getSession().getAttribute(&commuser&) ;
   
   //查找中心
   
   
   if ( cmur.getUserType().equals(&manager&) )
   {
   
   
    try
   {
   
   
    Sms sms = new Sms() ;
    sms.setContent(content) ;
    sms.setSmstype(smstype) ;
    sms.setSmstitle(title) ;
    sms.setDatetime(new GetTime().getDate()) ;
    sms.setFromid(cmur.getId()) ;
    sms.setToid(Integer.valueOf(hospitalid)) ;
   
    session.saveOrUpdate(sms) ;
    //提交事务
    tx.commit() ;
   
    data =  &{success:true,msg:'添加成功!',smsid:& + sms.getSmsid() +  &}& ;
   
   
   
   
   }
   catch(Exception e )
   {
    e.printStackTrace() ;
    tx.rollback() ;
   
    data =  &{success:false,msg:'添加失败!'}& ;
   }
   finally
   {
   
    //关闭
   CommSession.closeSession(session) ;
   }
   }
   
   
   
   out.print(data) ;
out.flush() ;
}}其中out输出的,你可以写入javascript代码
请登录后再发表评论!
谢谢各位!
请登录后再发表评论!
普通的class么,那你就写一个返回值是String的方法,去构造javascript,呵呵比如String str=&&script type='text/javascript'&asdfasdf&/script&&;
请登录后再发表评论!
你可以用dwr
请登录后再发表评论!
如果你会struts用action类输出也一样.给你一个我的一个actionpackage com.ecg.struts.import java.io.IOEimport java.io.PrintWimport java.util.Limport javax.servlet.http.HttpServletRimport javax.servlet.http.HttpServletRimport org.apache.struts.action.Aimport org.apache.struts.action.ActionFimport org.apache.struts.action.ActionFimport org.apache.struts.action.ActionMimport org.hibernate.Simport org.hibernate.Timport org.json.JSONEimport org.json.JSONOimport po.Himport po.Mimport po.Simport po.Simport publicclass.CommUimport dao.CommSimport dao.SmsDAO;import util.EasySimport util.CharFimport util.GetT/** * MyEclipse Struts* Creation date: 12-12-2008* * XDoclet definition:* @struts.action validate=&true&*/public class SmsAction extends Action {/** Generated Methods*//** * Method execute* @param mapping* @param form* @param request* @param response* @return ActionForward* @throws IOException * @throws JSONException */public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException {// TODO Auto-generated method stubString command = request.getParameter(&command&) ; response.setContentType( &text/ charset=utf-8& );PrintWriter out = response.getWriter() ; request.setCharacterEncoding(&utf-8& ) ; if ( command != null ){if ( command.equals(&listsms&)){int start =EasyStr.parseInt(request.getParameter(&start&)) ; int limit = EasyStr.parseInt(request.getParameter(&limit&)) ; String type = request.getParameter(&type&) ; CommUser  cmur = (CommUser)request.getSession().getAttribute(&commuser&) ; JSONObject json = new SmsDAO().getSms(start, limit , type , cmur ) ; out.print(json) ; }else if ( command.equals(&read&)){String smsid = request.getParameter(&smsid&) ; boolean b = new SmsDAO().updateSms(smsid) ; {if ( b ){out.print(&{success:true,msg:'更新成功!'}&);}else{out.print(&{success:false,msg:'更新失败!'}&) ;}}}else if ( command.equals(&delete&)){String smsid = request.getParameter(&smsid&) ; boolean b = new SmsDAO().delete(smsid) ; if ( b == true ){out.print(&数据删除成功!&);}else{out.print(&数据删除失败!&);} }else if ( command.equals(&insert&) ){String type = request.getParameter(&type&) ; if ( type == null ) if ( type.equals(&sys&)){//String title = CharFilter.ExtjstoChinese(request.getParameter(name)(&title&) ); //String content = CharFilter.ExtjstoChinese(request.getParameter(&content&)) ;String title = CharFilter.ExtjstoChinese(request.getParameter(&title&)) ; String content =CharFilter.ExtjstoChinese( request.getParameter(&content&)) ; String data =  null  ;   Session session = CommSession.openSession() ;
  Transaction tx =  session.beginTransaction() ;
  String hql = &from Smstype where smstypeid=1&  ;
  Smstype smstype =(Smstype) CommSession.queryOne(session, hql) ;
  Sms sms = new Sms() ;  
  try   {    sms.setContent(content) ;
   sms.setSmstype(smstype) ;
   sms.setSmstitle(title) ;
   sms.setDatetime(new GetTime().getDate()) ;
       session.saveOrUpdate(sms) ;  
   //提交事务    tx.commit() ;
       //System.out.println(&id:& +sms.getSmsid()) ;
       data =  &{success:true,msg:'添加成功!',smsid:& + sms.getSmsid() +  &}& ;   }   catch(Exception e )   {    e.printStackTrace() ;
   //tx.rollback() ;
       data =  &{success:false,msg:'添加失败!'}& ;   }   finally   {  
   //关闭   CommSession.closeSession(session) ;
  }  
  out.print(data) ; }else if ( type.equals(&hospital&)){String sendType = request.getParameter(&sendtype&) ; if ( sendType.equals(&all&)){String title = CharFilter.ExtjstoChinese(request.getParameter(&title&)) ; String content =CharFilter.ExtjstoChinese( request.getParameter(&content&) ) ; String data =  null  ;   Session session = CommSession.openSession() ;
  Transaction tx =  session.beginTransaction() ;
  String hql = &from Smstype where smstypeid=2&   ;
  Smstype smstype =(Smstype) CommSession.queryOne(session, hql) ;
  //得到管理员ID   CommUser  cmur = (CommUser)request.getSession().getAttribute(&commuser&) ;  
  //查找中心  
  if ( cmur.getUserType().equals(&manager&) )   {    
      String sql = &select hospitalid from hospital order by hospitalid asc  & ;
  List list = CommSession.querySQLPage(session, sql, -1 , -1 ) ;
  try   {       for ( int i = 0 ; i & list.size() ; i++  )   {            Sms sms = new Sms() ;    sms.setContent(content) ;
   sms.setSmstype(smstype) ;
   sms.setSmstitle(title) ;
   sms.setDatetime(new GetTime().getDate()) ;    sms.setFromid(cmur.getId()) ;
   sms.setToid(Integer.valueOf(((Object)list.get(i)).toString())) ;
           session.saveOrUpdate(sms) ;    
          } //提交事务    tx.commit() ;    
   data =  &{success:true,msg:'添加成功!'}& ;
      }   catch(Exception e )   {    e.printStackTrace() ;
   tx.rollback() ;    
   data =  &{success:false,msg:'添加失败!'}& ;   }   finally   {  
   //关闭   CommSession.closeSession(session) ;
  }   }      
  out.print(data) ; }else if ( sendType.equals(&single&)){String hospitalid = request.getParameter(&hospital&) ; String title = request.getParameter(&title&) ; String content = request.getParameter(&content&) ; String data =  null  ;   Session session = CommSession.openSession() ;
  Transaction tx =  session.beginTransaction() ;
  String hql = &from Smstype where smstypeid=2&  ;
  Smstype smstype =(Smstype) CommSession.queryOne(session, hql) ;
  //得到管理员ID   CommUser  cmur = (CommUser)request.getSession().getAttribute(&commuser&) ;  
  //查找中心  
  if ( cmur.getUserType().equals(&manager&) )   {    
       try   {    
       Sms sms = new Sms() ;    sms.setContent(content) ;
   sms.setSmstype(smstype) ;
   sms.setSmstitle(title) ;
   sms.setDatetime(new GetTime().getDate()) ;    sms.setFromid(cmur.getId()) ;
   sms.setToid(Integer.valueOf(hospitalid)) ;
       session.saveOrUpdate(sms) ;  
   //提交事务    tx.commit() ;
       data =  &{success:true,msg:'添加成功!',smsid:& + sms.getSmsid() +  &}& ;    
              }   catch(Exception e )   {    e.printStackTrace() ;
   tx.rollback() ;    
   data =  &{success:false,msg:'添加失败!'}& ;   }   finally   {  
   //关闭   CommSession.closeSession(session) ;
  }   }      
  out.print(data) ; }}}}out.flush() ; }}其中out输出的,你可以写入javascript代码
请登录后再发表评论!
用serverout.plent(&js&)
请登录后再发表评论!}