SSM 从浏览器到数据库访问过程

本文详细介绍了SSM框架从浏览器输入URL开始,如何经过控制器、服务、接口实现、Mapper映射文件,最终到达数据库并返回数据的过程。在URL请求后,依次找到对应的UserController、UserService、UserServiceImpl和UserMapper,通过反射自动生成的文件执行数据库查询操作,将查询结果传递给前端展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

- 首先,看下 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)效果一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值