注意:可以使用模板,也可以不使用
区别:只有Controller的注解不同 - 使用模板:@Controller - 不使用模板: @RestController(不需要写HTML页面,直接返回数据库查询到的数据)使用模板
普通类(与数据库中的字段一致) public class SpClass { private int userID; private String userName; private String userPwd; private String userRight; public int getUserID() { return userID; } public String getUserName() { return userName; } public String getUserPwd() { return userPwd; } public String getUserRight() { return userRight; } public void setUserID(int userID) { this.userID = userID; } public void setUserName(String userName) { this.userName = userName; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public void setUserRight(String userRight) { this.userRight = userRight; } } 接口(操作数据库) @Mapper public interface SpMapper { //与数据库操作关键字一致:@Select @Insert @Delete @Update @Select("select*from user where userID=#{userID}") //@Param确保参数一致:#{a}和@Param("a")中的参数必须一致,后面的参数可以不一样 List<User> selectUser(@Param("userID")Integer userID); } Controller @Controller public class SpController { //Spring容器帮助建立Mapper对象,不能直接使用 @Resource private SpMapper spMapper; //浏览器访问路径 @RequestMapping("/user") public String index(){ //返回的是模板的名称,不能加.html,在配置文件中已经配置了扩展名 return "test"; } //user.json就是ajax请求的路径 @RequestMapping(value = "user.json", method = {RequestMethod.GET}) //页面响应的数据 @ResponseBody public String user(@RequestParam(value = "userID") Integer userID){ List<User> user = spMapper.selectUser(userID); //转换为json字符串 String s = JSON.toJSONString(user); System.out.println(user); System.out.println(s); return s; } } 模板 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../js/jquery.js"></script> <style> div{ width:300px; height:300px; margin-left:100px; padding: 5px; border:1px solid blue; } #info { width:200px; height:150px; margin:5px auto; border:1px solid greenyellow; } </style> </head> <body> <div> 用户名:<input type="text" name="userID" id="name"> <input type="button" value="查询" id="sub"> <div id="info"> </div> </div> <script> $(function () { $("#sub").click(function () { $.ajax({ url:"/user.json", dataType:"json", type:"get", data:{"userID":$("#name").val()}, success:function (data) { var html="<ul><li>学号:"+data[0].userID+"</li><li>姓名:"+data[0].userName+"</li><li>权限:"+data[0].userRight+"</li></ul>"; $("#info").append(html); } }); }); }) </script> </body> </html>session.getAttribute和session.setAttribute:获取和设置属性