最近這幾天在做一個用戶同步,具體就是當權限系統中添加用戶後,把該用戶的信息同步到論壇系統中去,服務器端發布webservice采用的是cxf框架,這時候一個業務需求就是能獲取到客戶端的ip,並將這字段存到數據庫中,用於論壇統計。
package com.bkbt.forum.service;
import java.io.Reader;
import java.io.StringReader;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import cn.jsprun.dao.UserDao;
import cn.jsprun.domain.Members;
import cn.jsprun.utils.BeanFactory;
import cn.jsprun.utils.Common;
import cn.jsprun.utils.Md5Token;
@WebService
public class UserServiceImpl implements UserService {
private Log log = LogFactory.getLog(UserServiceImpl.class);
private UserDao userDao = (UserDao) BeanFactory.getBean("userDao");
@Resource(name = "org.apache.cxf.jaxws.context.WebServiceContextImpl")
private WebServiceContext context;
public void addUser(String xml) {
try {
SAXReader saxReader = new SAXReader();
Reader reader = new StringReader(xml);
Document doc = saxReader.read(reader);
Element root = doc.getRootElement();
List<Element> list = root.elements();
Members member = new Members();
int salt = Common.rand(100000, 999999);
member.setUsername(list.get(0).getText());
member.setPassword(Md5Token.getInstance().getLongToken(Md5Token.getInstance().getLongToken(list.get(1).getText())+salt));
member.setEmail(list.get(2).getText());
member.setSalt(String.valueOf(salt));
int groupId = 10;
short id = (short)groupId;
Short Id = id;
member.setGroupid(Id); www.2cto.com
member.setRegip(this.getClientIpCxf());
member.setRegdate(Integer.valueOf(String.valueOf(new Date().getTime()).substring(0, 10)));
member.setLastip(this.getClientIpCxf());
member.setLastvisit(Integer.valueOf(String.valueOf(new Date().getTime()).substring(0, 10)));
member.setPmsound(Byte.valueOf("1"));
member.setShowemail(Byte.valueOf("1"));
member.setNewsletter(Byte.valueOf("1"));
member.setTimeoffset("9999");
member.setLastactivity(Integer.valueOf(String.valueOf(new Date().getTime()).substring(0, 10)));
userDao.saveMember(member);
} catch (Exception e) {
}
}
public String getClientIpCxf() {
MessageContext ctx = context.getMessageContext();
HttpServletRequest request = (HttpServletRequest)
ctx.get(AbstractHTTPDestination.HTTP_REQUEST);
String ip=request.getRemoteAddr();
return ip;
}
}