1.各个层的作用
- controller层:获得参数,返回响应
- service层:完成业务逻辑
- dao层:用于和数据库之间的交互
- entity层:与数据库相关的实体类
2.程序例子
1.controller
@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";
}
}
2.service
service由接口和接口实现类组成
(1)接口
public interface UserService
{
User findById(Integer id);
}
(2)接口实现类
@Serice("userService")
public class UserServiceImpl implement UserService{
@Autowired
private UserMapper userMapper;
@Override
public User findById(Integer id) {
User user = userMapper.selectByPrimaryKey(id);
return user;
}
}
3.dao
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
UserMapper .xml
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
4.entity
public class User {
private Integer id;
private String username;
private Integer password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public Integer getPassword() {
return password;
}
public void setPassword(Integer password) {
this.password = password;
}
}
5.webapp下的jsp文件
<form action="index">
<input type="text" name="name" value="${user.username}">
<input type="text" name="age" value="${user.password}">
<input type="submit" value="提交">
</form>
3.程序的运行流程
1.在程序部署好tomcat后,在网页输入网址http://localhost:8080/项目名/userController/index
2.程序根据提供的网址进入controller层,因为在这一层使用了注解@RequestMapping("userController"),在根据index注解进入index方法.
3.在index方法中根据userService.findById(1)的方法调用,进入service层.
4.在service实现类中调用findById方法会调用dao里面的userMapper中的User selectByPrimaryKey(Integer id);方法.
5.这个方法会调用UserMapper.xml文件中的id为selectByPrimaryKey的方法来读取到数据库后将数据返回给service层中UserServiceImpl的user对象
6.再将数据返回给controller层中的user对象,最后将数据添加到model中,并通过return方法将数据传递到userlist.jsp文件中