DWR2中调用Servlet相关类(简单例子)


DWR2一大特性就是在DWR中可以访问WEB上下文的SERVLET,REQUEST等,主要用到的类是WebContext,WebContextFactory,使用WebContextFacotry.get()方法得到当前的WebContext,原理是将WebContext与当前thread绑定,内部使用ThreadLocal来维护。

use case:
在IE中使用JAVASCRIPT来判断制定用户名经是否已经登陆。

client(index.jsp)
<% @ page language = " java "   import = " java.util.* "  pageEncoding = " gb2312 " %>
<%
String path 
=  request.getContextPath();
String basePath 
=  request.getScheme() + " :// " + request.getServerName() + " : " + request.getServerPort() + path + " / " ;
// 为演示:假设已经登录成功
request.getSession( true ).setAttribute( " cur_user " , " jack " );
%>

<! DOCTYPE HTML PUBLIC  " -//W3C//DTD HTML 4.01 Transitional//EN " >
< html >
  
< head >
    
< base href = " <%=basePath%> " >
 
    
< script type = ' text/javascript '  src = ' dwr/engine.js ' >   </ script >
    
< script type = ' text/javascript '  src = ' dwr/util.js ' >   </ script >
    
< script type = ' text/javascript '  src = ' dwr/interface/UserCheck.js ' >   </ script >
   
    
< script language = " javascript " >
        function checkUserIsLogin(name) 
{
            UserCheck.checkUserIsLogin(name,function(res) 
{
                    var retMsg 
= ( true == res ) ? "已经登录" : "未登录";
                    DWRUtil.setValue(
"msg",retMsg);
                }

            );
        }

    
</ script >
  
</ head >
 
  
< body >
   
< input type = " text "  name = " username "   />< input type = " button "  value = " check "  onclick = " checkUserIsLogin(document.all.username.value) "   /> 当前session中保存为jack
   
< br />
   
< div id = " msg " ></ div >
  
</ body >
</ html >

服务端:UserCheckUtil.java


package  com.dwr;

import  javax.servlet.http.HttpSession;

import  org.directwebremoting.WebContext;
import  org.directwebremoting.WebContextFactory;

public   class  UserCheckUtil  {
    
/**
     * 
     * 
@param username
     * 
@return
     
*/

    
public boolean checkUserIsLogin(String username) {
        WebContext ctx 
= WebContextFactory.get();
        HttpSession session 
= ctx.getSession(false);
        
if (null != session && username.equals(String.valueOf(session.getAttribute("cur_user"))))
            
return true;
        
else
            
return false;
    }


}

配置文件:dwr.xml

<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd" >

< dwr >

  
< allow >
    
< create  creator ="new"  javascript ="UserCheck" >
      
< param  name ="class"  value ="com.dwr.UserCheckUtil" />
    
</ create >

  
</ allow >

</ dwr >

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值