- 首先,看下 ssm 的目录结构
对应的文件代码
dao , entity 和 mapping文件夹中的文件通过反射自动生成
- UserController
@Controller
@RequestMapping("userController")
public class UserController {
@Autowired //帮助创建一个对象
private UserService userService;
@RequestMapping("index")
public String index(Model model, HttpServletRequest request){
User user= userService.findById(1);
model.addAttribute("user",user);
return "user/userList";
}
}
UserService 接口
public interface UserService {
User findById(Integer id);
}
UserServiceImpl 类 实现UserService 接口
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findById(Integer id) {
User user = userMapper.selectByPrimaryKey(id);
return user;
}
}
userList.jsp
<form action="index">
<input type="text" name="account" value="${user.account}" />
<input type="text" name="pwd" value="${user.pwd}" />
<input type="submit" value="提交" />
</form>
1. 在浏览器的 URL 框中输入 http://localhost:8080/testssm/userController/index
- testssm 本地的项目名称
- userController 自己设置的URL请求
- index 也是自己设置的 URL 请求
2. 根据URL中的请求地址,找到对应的文件
- 首先根据URL寻找到 userController 下的 index 请求
- 开始执行 index 方法, ( 可以看见 UserService 对象调用了 findById()方法) ,进而可以寻找findById() 方法,( 发现在接口类 UserService 中定义了findById() 方法, 而在 UserServiceImpl 类中实现了接口中的方法; 其中有在方法中调用了 UserMapper 对象中的 selectByPrimaryKey() 方法).
- 开始寻找 UserMapper 类中的 selectByPrimaryKey() 方法,并将结果赋值给 user 对象.( 可以发现 selectByPrimaryKey 在 UserMapper.xml 文件中,得出通过输入的 id 可以查出对应数据库中的数据)
- 将在从数据库中查到的数据,返回给 user 从而又回到 UserController 类中,将user对象数据传给 model 对象下的 addAttribute() 方法,最后在浏览器显示数据库查出的数据
注: model.addAttribute()往前台传数据,可以传对象,可以传List,通过el表达式 ${}可以获取到,
类似于request.setAttribute(“user”,user)效果一样。