有了入门(3)中的例子,我们再其上创建相关的service、controller就实现了向前台传递数据。
首先创建一个Service。
其主要作用是根据用户名查找数据,然后将其转换为JSON字符串。当然,Service也不是必须的,因为我们这个功能很简单,所以如果你乐意将这些代码写在controller中也没问题。
package example3.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSON;
import example3.model.baiuser;
import example3.service.baiuserService;
import example3.dao.baiuserMapper;
public class baiuserServiceImpl implements baiuserService {
@Autowired
baiuserMapper userDao ;
@Override
public int insertUser(baiuser user) {
return userDao.insert(user);
}
@Override
public String selectUser(String username) {
baiuser user = userDao.selectByUsername(username);
String struser = JSON.toJSONString(user);
System.out.println(struser);
return struser;
}
}
package example3.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import example3.service.baiuserService;
@Controller
@RequestMapping("/user")
public class userController {
@Autowired
baiuserService userservice;
@RequestMapping("selectByUsername")
public @ResponseBody String selectByUsername(String username){
String str =userservice.selectUser(username);
return str;
}
}
这样配置好spring、springmvc配置文件,就可以正常工作了!当访问 /user/selectByUsername?username= xxx 的时候,就会将数据(注意这里是数据,因为返回值使用了@ResponseBody 注解)返回前台。
那么前台呢?
前台添加一个按钮,用jquery 的ajax方法来传递URL,并将返回值付给对应的文本框就好了。只需要注意,传回来的还是一个JSON字符串,而不是一个JSON对象,所以还需要有一句: var dataObj=eval("("+data+")"); 将JSON字符串转换为对象。
<script type="text/javascript" src="jsLib/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(function(){
$('#button3'). click(function(){
$.ajax({
type : "POST",
url : "user/selectByUsername.do?username="+$('#text5').val(),
success : function(data){
$('#textarea2').val(data);
var dataObj=eval("("+data+")");
$('#text3').val(dataObj.iD);
$('#text4').val(dataObj.uSERNAME);
//将得到的role插入表中
var row = $("<tr></tr>");
var td = $("<td></td>");
$.each(dataObj.role, function(i,item){
td.append(item.dESCN );
row.append(td);
});
$('#tab_role').append(row);
//
}
});
});
});
</script>
</head>
<body>
<table border="1"></table>
<table border="1">
<tr bgcolor="#6caef5"><td>please input username: </td><td><input type="text" id="text5"></td></tr>
<tr><td colspan="2" > </td></tr>
<tr><td>baiuser.id:</td> <td><input type="text" id="text3"></td></tr>
<tr><td>baiuser.name:</td><td><input type="text" id="text4"></td></tr>
</table>
<br>
<h4> roles:</h4>
<br>
<table id=tab_role> </table>
<br>
<textarea id="textarea2" rows="10" cols="50" ></textarea><br>
<input type="button" id="button3" value="getUser">
</body>
</html>
例子源码在:
http://download.csdn.net/detail/u013269938/7247549