- controller
package com.Lee.connect.controller; import com.Lee.connect.mapper.UserMapper; import com.Lee.connect.table.TableUser; 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.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "/") public class UserController{ @Autowired UserMapper userMapper; @RequestMapping(value = "/getUser") @ResponseBody public Object getUser(@RequestParam("id") Integer id){ TableUser user = userMapper.getUserById(id); return user; } @RequestMapping(value = "/delUser") @ResponseBody public Object delUser(@RequestParam("id") Integer id){ userMapper.delUserById(id); return "delete finished"; } @RequestMapping(value = "/setUser") @ResponseBody public Object setUser(@RequestParam("UserName") String UserName,@RequestParam("PassWord") String PassWord,@RequestParam("id") Integer id){ TableUser user = new TableUser(); user.setId(id); user.setUserName(UserName); user.setPassWord(PassWord); userMapper.updateUser(user); return user; } }
此处定义了三个方法,分别用于删改查
@RequesBody的value值也根据方法的作用进行更改,在http中就是请求的路径不同
使用@RequestParam("username") String username可以作为类的参数,这样就需要使用?参数1&参数2来http请求传入参数给controller
- mapper
package com.Lee.connect.mapper; import com.Lee.connect.table.TableUser; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Component; @Mapper @Component(value = "UserMapper") public interface UserMapper { //select @Select("select * from t1 where id=#{id}") TableUser getUserById(@Param("id") Integer id); //delete @Delete("delete from t1 where id=#{id}") void delUserById(@Param("id") Integer id); //update @Update("update t1 set UserName=#{UserName},PassWord=#{PassWord} where id=#{id}") void updateUser(TableUser user); }
此接口定义了三个方法,分别使用了不同的sql语句
注意查会返回一个对象,使用entity对应的tableuser进行接收
删和改则无返回值,使用void
- 传参
使用/value?参数1&参数2在地址栏中添加参数
/value为controller中使用的方法
参数为@RequestParam("username") String username中对应的参数