SSh中Ajax与action的交互

demo描述:

简单的小例子,SSH中实现Ajax与后台交互;

必要jar:

ssh基本jar

fastjson (用来将数据转换成json格式)

代码:

前台ajax代码:

$(function(){

$.ajax({

 

type: "POST",

url:"${PageContext.request.contextpath}userAction_userLoginById.action",

data: {"id" : 2},

success: function(data) {

alert(data.id);

console.log(data.hello);

},

error:function(e){

console.log(e);

},

dataType:"json"

});

});

Action代码:

publicclass UserAction extends ActionSupport implements ModelDriven {

privatestatic final long serialVersionUID = 1L;

//spring注入service

privateUserService userService;

//模型驱动注入对象

privateUser u = new User();

/* 根据id查询用户信息 */

publicvoid userLoginById() throws IOException {

System.out.println("根据id查询用户信息Action");

System.out.println(u);

Useruser = userService.userLoginById(u);

if(user != null) {

String userStr =JSON.toJSONString(user);//使用fastjson将数据转换成json格式

PrintWriterwriter = ServletActionContext.getResponse().getWriter();

writer.write(userStr);

System.out.println("成功");

writer.flush();

writer.close();

}else {

System.out.println("失败");

}

}

// 注入Service

publicUserService getUserService() {

returnuserService;

}

publicvoid setUserService(UserService userService) {

this.userService= userService;

}

 

// 模型驱动

@Override

publicUser getModel() {

returnu;

}

dao层代码:

publicclass UserDaoImpl extends HibernateDaoSupport implements UserDao {

/*根据用户id查询用户信息*/

@Override

publicUser userLoginById(final User u) {

returngetHibernateTemplate().execute(new HibernateCallback() {

@Override

publicUser doInHibernate(Session session) throws HibernateException {

Useruser = session.get(User.class, u.getId());

returnuser;

}

});

}

struts配置文件:

method="{1}">


你可能感兴趣的:(SSH)