SSM框架结构
controller:获得参数,返回响应
dao:和数据库之间交互
entity:存储与数据库相关的类 例如:User类 Blog类
service:完成业务逻辑
webapp:新建jsp文件
程序:
项目结构:
userList.jsp代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action = "index">
姓名:<input type="text" name="account" value = "${user.account}"/>
年龄:<input type="text" name="pwd" value = "${user.pwd}"/>
<input type = "submit" value="提交"/>
</form>
</body>
</html>
UserController.java代码:
import javax.servlet.http.HttpServletRequest;
@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.java代码:
package com.qcby.service;
import com.qcby.entity.User;
public interface UserService {
User findById(Integer id);
}
UserServiceImpl.java代码:
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findById(Integer id) {
User user = userMapper.selectByPrimaryKey(String.valueOf((long) id));
return user;
}
}
通过 点击m(mybatis反向生成命令) 输入mybatis-generator:generate
会逆向生成dao(UserMapper) entity(User) mapping(UserMapper.xml)文件,Blog也会生成。
UserMapper.java代码:
public interface UserMapper {
int deleteByPrimaryKey(String id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
运行流程:
- 运行tomcat服务器后,输入网址http://localhost:8080/testssm/userController/index
进入界面, - 点击提交后,通过form表单action=“index”进入到UserController.java文件
- 调用index方法,通过userService.findById(1),访问到UserService.java文件中
- 调用findById方法,通过这个接口跳到UserServiceImpl.java文件
- 运行findById方法会调用userMapper.java文件中的User selectByPrimaryKey(string id) 方法
- 这个方法会调用UserMapper.xml文件中的id为selectByPrimaryKey的方法,
<mapper namespace="com.qcby.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.qcby.entity.User">
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="account" jdbcType="VARCHAR" property="account" />
<result column="pwd" jdbcType="VARCHAR" property="pwd" />
</resultMap>
<sql id="Base_Column_List">
id, account, pwd
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=VARCHAR}
</select>
- 读取到数据库数据后return到UserServiceImpl.java文件中赋给对象user
- 再return user到UserController.java文件中赋值给user对象
- 再将user添加到model对象中
- 再return “user/userList”返回到userList.jsp中通过el表达式
${user.account} ${user.pwd}
取到数据库数据并显示。