SMM框架简单用户增删改查
作者:互联网
用户增删改查
先导入jar包:
编写User实体类:
public class User {
private Integer id;
private String name;
private String sex;
private Integer age;
private String address;
@Override
public String toString() {
return "\nUser{" +
"id=" + id +
", name='" + name + '\'' +
", sex=" + sex +
", age=" + age +
", address='" + address + '\'' +
'}';
}
//省略get set 构造方法
编写DAO接口:
public interface UserMapper {
//查询所有用户
public List<User> list();
//添加用户
int addUser(User user);
//根据Id查询指定用户
User getUserById(int id);
//更改用户
int updateUser(User user);
//删除用户
int delUser(Integer id);
}
编写SQL映射文件:
命名空间必须为接口完全限定类名,id值必须与接口方法名一致,
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.user.dao.UserMapper">
<resultMap id="BaseresultMap" type="user">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
</resultMap>
<select id="list" resultMap="BaseresultMap">
select * from user
</select>
<insert id="addUser" parameterType="user">
insert into user(name,sex,age,address) values (#{name},#{sex},#{age},#{address})
</insert>
<select id="getUserById" parameterType="int" resultMap="BaseresultMap">
select * from user where id=#{id}
</select>
<update id="updateUser" parameterType="user">
update user set name=#{name},sex=#{sex},age=#{age},address=#{address} where id=#{id}
</update>
<delete id="delUser" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper>
编写MyBatis配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--设置别名-->
<typeAliases>
<package name="cn.user.pojo"/>
</typeAliases>
<mappers>
<!--加载SQL映射文件-->
<mapper resource="cn/user/dao/mapper/UserMapper.xml"/>
</mappers>
</configuration>
编写Service业务层:
UserService及实现类:
public interface UserService {
public List<User> list();//查询
int addUser(User user);//添加
User getUserById(int id);//根据id查询
int updateUser(User user);修改
int delUser(Integer id);//删除
}
实现类:别忘了给类加注解,交给Spring容器管理
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
//注解方式为mapper赋值
@Resource(name = "userMapper")
private UserMapper mapper;
@Override
public List<User> list() {
return mapper.list();
}
@Override
public int addUser(User user) {
return mapper.addUser(user);
}
@Override
public User getUserById(int id) {
return mapper.getUserById(id);
}
@Override
public int updateUser(User user) {
return mapper.updateUser(user);
}
@Override
public int delUser(Integer id) {
return mapper.delUser(id);
}
}
编写Spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="cn.user.dao,cn.user.service"/>
<!--配置数据源-->
<context:property-placeholder location="classpath:database.properties"/>
<bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!--配置SqlSessionFactoryBean-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<!--扫描dao接口自动生成实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="cn.user.dao"/>
</bean>
<!--配置事务处理对象-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--注解方式开启事务管理-->
<mvc:annotation-driven transaction-manager="transactionManager"/>
</beans>
编写Controller控制器类:同样别忘了加注解。
@Controller
@RequestMapping("/user")
public class UserController {
@Resource(name = "userService")//注解方法注入UserService实现类
private UserService userService;
@RequestMapping("/list")
public String listUser(Model model){
List<User> list = userService.list();
model.addAttribute("users",list);
return "main";
}
@GetMapping("/add")
public String toAdd(@ModelAttribute("user") User user){
return "add";
}
@PostMapping("/add")
public void add(User user, HttpServletResponse response) throws IOException {
int re = userService.addUser(user);
response.getWriter().print(re);
}
@GetMapping("/update/{id}")
public String toUpdate(@PathVariable("id") int id,Model model){
User user = userService.getUserById(id);
model.addAttribute("user",user);
return "update";
}
@PostMapping("/update")
public void update(User user, HttpServletResponse response) throws IOException {
int re = userService.updateUser(user);
response.getWriter().print(re);
}
//删除
@GetMapping("/del/{id}")
public String del(@PathVariable("id") Integer id){
int re = userService.delUser(id);
return "redirect:/user/list";
}
}
编写SpringMVC配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启组件扫描扫描controller包-->
<context:component-scan base-package="cn.user.controller"/>
<!--开启映射注解-->
<mvc:annotation-driven/>
<!--定义视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--加载nvc配置文件时一同加载spring的配置文件-->
<import resource="classpath:application.xml"/>
</beans>
在web.xml中定义前端控制器,以及乱码处理等。。。。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--定义前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--处理中文乱码-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--静态资源处理-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.html</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
</web-app>
编写页面开始测试:
main.jsp页面:查询所有用户
<head>
<title>所有用户</title>
<script type="text/javascript" src="${pageContext.servletContext.contextPath}/static/js/jquery-1.12.4.js"></script>
</head>
<body>
<a href="${pageContext.servletContext.contextPath}/user/add">添加用户</a>
<table border="1px" width="700px">
<tr>
<td>序号</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>地址</td>
<td>操作</td>
</tr>
<c:forEach items="${requestScope.users}" varStatus="i" var="user">
<tr>
<td>${i.count}</td>
<td>${user.name}</td>
<td>${user.sex}</td>
<td>${user.age}</td>
<td>${user.address}</td>
<%--REST风格从页面到controller传递数据--%>
<td><a href="${pageContext.servletContext.contextPath}/user/update/${user.id}">修改</a>
<a href="${pageContext.servletContext.contextPath}/user/del/${user.id}">删除</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
点击添加进入到user/add方法Get请求:
@GetMapping("/add")
public String toAdd(@ModelAttribute("user") User user){
return "add";
}
准备好user对象跳转到add.jsp添加页面:
<html>
<head>
<title>添加用户</title>
<script type="text/javascript" src="${pageContext.servletContext.contextPath}/static/js/jquery-1.12.4.js"></script>
</head>
<body>
<fm:form id="addfrom" modelAttribute="user">
姓名:<fm:input path="name"/><br>
性别:<fm:radiobutton path="sex" value="男" checked="checked"/>男<fm:radiobutton path="sex" value="女"/>女<br>
年龄:<fm:input path="age"/><br>
地址:<fm:input path="address"/><br>
<input type="button" value="添加" id="tianjia">
</fm:form>
<script type="text/javascript">
$(function () {
$("#tianjia").click(function () {
/*序列化表单中的数据*/
var input = $("#addfrom").serialize();
$.post("${pageContext.servletContext.contextPath}/user/add",input,function (data) {
if (data!=-1){
alert("添加成功");
window.location.href="${pageContext.servletContext.contextPath}/user/list";
}else{
alert("添加失败");
}
});
});
});
</script>
</body>
</html>
异步方式添加用户,点击添加按钮跳转到user/add方法Post请求方式:然后返回结果data,添加成功跳转到user/list方法,然后在跳转到main.jsp页面
@PostMapping("/add")
public void add(User user, HttpServletResponse response) throws IOException {
int re = userService.addUser(user);
//返回执行结果
response.getWriter().print(re);
}
点击修改超链接传入当前用户ID跳转到user/update方法Get请求:
@GetMapping("/update/{id}")
public String toUpdate(@PathVariable("id") int id,Model model){
//根据id查出要修改的用户对象
User user = userService.getUserById(id);
把用户存入model中在jsp页面中显示
model.addAttribute("user",user);
//跳转到update.jsp页面
return "update";
}
update.jsp页面:异步方式修改用户信息
<html>
<head>
<title>修改用户</title>
<script type="text/javascript" src="${pageContext.servletContext.contextPath}/static/js/jquery-1.12.4.js"></script>
</head>
<body>
<fm:form id="updatefrom" modelAttribute="user">
<fm:hidden path="id"/>
姓名:<fm:input path="name"/><br>
性别:<fm:radiobutton path="sex" value="男" checked="checked"/>男<fm:radiobutton path="sex" value="女"/>女<br>
年龄:<fm:input path="age"/><br>
地址:<fm:input path="address"/><br>
<input type="button" value="修改" id="xiugai">
</fm:form>
<script type="text/javascript">
$(function () {
$("#xiugai").click(function () {
/*序列化表单中的数据*/
var input = $("#updatefrom").serialize();
$.post("${pageContext.servletContext.contextPath}/user/update",input,function (data) {
if (data!=-1){
alert("修改成功");
window.location.href="${pageContext.servletContext.contextPath}/user/list";
}else{
alert("修改失败");
}
});
});
});
</script>
</body>
</html>
点击修改跳转到user/update方法POST请求方式:返回然后返回执行结果data修改成功后跳转到user./list方法跳转到main.jsp页面。
@PostMapping("/update")
public void update(User user, HttpServletResponse response) throws IOException {
int re = userService.updateUser(user);
//返回给update.jsp页面执行结果
response.getWriter().print(re);
}
点击删除传入当前用户id并跳转到/user/del方法中get请求:
//删除
@GetMapping("/del/{id}")
//接受用户的id值
public String del(@PathVariable("id") Integer id){
int re = userService.delUser(id);
return "redirect:/user/list";
}
删除成功后重定向到user/list方法然后跳转到main.jsp页面
标签:int,list,改查,id,SMM,user,增删,public,User 来源: https://blog.csdn.net/yananye/article/details/118252819