struts与mybatis整合小项目

2020年12月21日 7点热度 0条评论 来源: 落尘曦

struts与mybatis整合小项目

实现功能:

a.添加用户

b.查看所有用户

c.删除用户

d.更新用户信息

项目源码下载

具体实现步骤

创建表结构

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `u_id` varchar(255) NOT NULL,
  `u_name` varchar(255) DEFAULT NULL,
  `u_type` varchar(255) DEFAULT NULL,
  `u_pass` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`u_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('a', 'a', 'a', 'a');
INSERT INTO `users` VALUES ('b', 'b', 'b', 'b');
INSERT INTO `users` VALUES ('c', 'c', 'c', 'c');
INSERT INTO `users` VALUES ('e', 'e', 'eee', 'e');

1.新建一个web项目  导入必须的jar包

commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
freemarker-2.3.15.jar
mybatis-3.2.3.jar
mysql-connector-java-5.1.7-bin.jar
ognl-2.7.3.jar
struts2-core-2.1.8.1.jar
xwork-core-2.1.6.jar

2.在WebRoot/WEB-INF/web.xml  配置struts核心过滤器

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>	
  
  <filter>
  	   <filter-name>struts</filter-name>
	   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
		<filter-name>struts</filter-name>
		<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.创建包结构

com.jsx.action
com.jsx.dao
com.jsx.entity
com.jsx.service
com.jsx.util

4.创建mybatis.cfg.xml  mybatis配置文件

mybatis.cfg.xml

<?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>
    <!-- mybatis别名定义 -->
    <typeAliases> 
        <typeAlias alias="User" type="com.jsx.entity.User"/> 
    </typeAliases> 
    <environments default="development">
        <environment id="development">
        <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/test" />
            <property name="username" value="root"/>
            <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!-- mybatis的mapper文件,每个xml配置文件对应一个接口 -->
    <mappers>
        <mapper resource="com/jsx/entity/User.xml"/>
    </mappers>
</configuration>

5.在util包下创建Mybatis工具类 MybatisUtil

MybatisUtil.java

package com.jsx.util;

import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {
	private static SqlSessionFactory SqlSessionFactory;
	private static Reader reader;
	static {
		try {
			reader = Resources.getResourceAsReader("mybatis.cfg.xml");
			SqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static SqlSessionFactory getSessionFactoty() {
		return SqlSessionFactory;
	}
}

6.在entity下创建User实体类

User.java

package com.jsx.entity;

public class User {
	private String id;
	private String username;
	private String usertype;
	private String userpwd;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getUsertype() {
		return usertype;
	}
	public void setUsertype(String usertype) {
		this.usertype = usertype;
	}
	public String getUserpwd() {
		return userpwd;
	}
	public void setUserpwd(String userpwd) {
		this.userpwd = userpwd;
	}

}

7.创建User.xml定义实体类要实现的功能 (其中定义你的功能,对应要对数据库进行的那些操作)

User.xml

<?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="com.jsx.dao.UserDao">
	 <resultMap type="com.jsx.entity.User" id="UserMap">
	 <!-- property是实体类的属性 ,column 是数据库表中的字段 -->
	  <id property="id" column="u_id"/>
	  <result property="username" column="u_name"/>
	  <result property="usertype" column="u_type"/>
	  <result property="userpwd" column="u_pass"/>
</resultMap>
<!-- 下面的根据namespace中的路径找到接口 实现的sql语句 -->
<!-- 这里的id 对应的是 接口的方法  parameterType 就是参数类型 *首字母不需要大写  resultMap 中是写上面配置好的结果类型-->
<!-- 通过ID查询数据 -->
<select id="selectUserById" parameterType="com.jsx.entity.User" resultMap="UserMap">
 	select * from users where u_id=#{id}
</select>
<!-- 查询所有数据 -->
<select id="selectAllusers" resultMap="UserMap">
 	select * from users
</select>
<!--添加数据  -->
<insert id="addUser" parameterType="com.jsx.entity.User" useGeneratedKeys="true" keyProperty="id">
  insert into users(u_id,u_name,u_type,u_pass)
  values(#{id},#{username},#{usertype},#{userpwd})
</insert>
<!-- 修改数据 -->
<update  id="updateUser" parameterType="User" >
  	 update users set u_Name=#{username},u_Type=#{usertype},u_pass=#{userpwd} where u_ID=#{id}
</update>
<!-- 删除 数据-->
<delete id="delUser" parameterType="com.jsx.entity.User">
	 delete from users where u_ID=#{id}
</delete>

</mapper>

8.在dao创建UserDao接口将User.xml中的操作按照id映射成Java函数。

UserDao.java

package com.jsx.dao;

import java.util.List;

import com.jsx.entity.User;

public interface UserDao {
		// 通过id 查询
		public User selectUserById(String id);
		// 添加用户
		public void addUser(User users);
		// 删除用户
		public void delUser(String id);
		// 修改用户
		public void updateUser(User users);
		// 查询所有
		public List<User> selectAllusers();
}

9.在dao创建UserDaoImpl实现类

UserDaoImpl.java

package com.jsx.dao;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.jsx.entity.User;
import com.jsx.util.MybatisUtil;

public class UserDaoImpl  implements UserDao{
	// 添加
		public void addUser(User users) {
			// 首先得到session
			SqlSession session = MybatisUtil.getSessionFactoty().openSession();
			try {
				// 调用接口 到 users.xml文件中去
				UserDao usersDao = session.getMapper(UserDao.class);
				usersDao.addUser(users);
				session.commit();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				session.close();

			}
		}

		// 删除
		public void delUser(String id) {
			SqlSession session = MybatisUtil.getSessionFactoty().openSession();
			try {
				UserDao usersDao = session.getMapper(UserDao.class);
				usersDao.delUser(id);
				// 提交
				session.commit();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				session.close();
			}

		}

		// 通过id查询数据
		public User selectUserById(String id) {
			SqlSession session = MybatisUtil.getSessionFactoty().openSession();
			User user = null;
			try {
				UserDao usersDao = session.getMapper(UserDao.class);
				user = usersDao.selectUserById(id);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				session.close();
			}
			return user;
		}

		// 查询所有数据
		public List<User> selectAllusers() {
			SqlSession session = MybatisUtil.getSessionFactoty().openSession();
			List<User> uList = null;
			try {
				UserDao usersDao = session.getMapper(UserDao.class);
				uList = usersDao.selectAllusers();

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			} finally {
				System.out.println(uList.size());
				session.close();
			}
			return uList;

		}

		// 修改
		public void updateUser(User users) {
			SqlSession session = MybatisUtil.getSessionFactoty().openSession();
			try {
				UserDao usersDao = session.getMapper(UserDao.class);
				usersDao.updateUser(users);
				session.commit();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				session.close();
			}
		}

	}

10.在service下创建UserService接口和对应的实现类UserServiceImpl

UserService.java

package com.jsx.service;

import java.util.List;

import com.jsx.entity.User;

public interface UserService {
		// 通过id 查询
		public User selectUserById(String id);
		// 添加用户
		public void addUser(User users);
		// 删除用户
		public void delUser(String id);
		// 修改用户
		public void updateUser(User users);
		// 查询所有
		public List<User> selectAllusers();
}

UserServiceImpl.java

package com.jsx.service;

import java.util.List;

import com.jsx.dao.UserDao;
import com.jsx.dao.UserDaoImpl;
import com.jsx.entity.User;

public class UserServiceImpl implements UserService{
	UserDao userDao = new UserDaoImpl();

	public void addUser(User users) {
		userDao.addUser(users);
	}
	public void delUser(String id) {
		userDao.delUser(id);
	}
	public User selectUserById(String id){
		return userDao.selectUserById(id);
	}

	public List<User> selectAllusers() {
		return userDao.selectAllusers();
	}

	public void updateUser(User users) {
		userDao.updateUser(users);
	}

}

11.在action下创建UserAction并实现对应的方法

UserAction.java

package com.jsx.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.jsx.entity.User;
import com.jsx.service.UserService;
import com.jsx.service.UserServiceImpl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<User> {
	private User users = new User();
	public User getModel() {
		return users;
	}
	private UserService userService = new UserServiceImpl();
	HttpServletRequest request = ServletActionContext.getRequest();//一种获取request方法 (不建议用)
	
	public String toIndex() {
		System.out.println("=========selAll============");
		List<User> userList = userService.selectAllusers();
		ActionContext.getContext().getSession().put("user_List", userList);
		return SUCCESS;
	}
	public String toUpdate() {
		System.out.println("=========selByid============");
		User u = null;
		u = userService.selectUserById(users.getId());
		ActionContext.getContext().getValueStack().push(u); //存放对象最好用值栈
		return "toUpdate";
	}
	public String delete() {
		System.out.println("=========del byid============");
		try {
			userService.delUser(users.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toIndex";
	}
	public String update() {
		System.out.println("=========update============");
		try {
			System.out.println(users.getUsername());
			userService.updateUser(users);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toIndex";
	}
	public String toAdd(){
		return "toAdd";
	}
	public String add() {
		System.out.println("=========add============");
		try {
			userService.addUser(users);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toIndex";
	}
}

12.创建struts.xml配置文件和struts-user.xml配置文件

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<!-- jsp样式使用自己的样式 -->
	<constant name="struts.ui.theme" value="simple" />
	<!-- 开发模式 -->
	<constant name="struts.devMode" value="true"></constant>
	<!-- <constant name="struts.action.extension" value="action,do"></constant> -->
	
	<package name="default" namespace="/" extends="struts-default">
	   
	</package>
	<include file="struts/struts-user.xml"></include>
</struts>



struts-user.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="user" namespace="/user" extends="default">
	    <action name="UserAction_*" class="com.jsx.action.UserAction" method="{1}">
				<result name="success">/index.jsp</result>
				<result name="toUpdate">/update.jsp</result>
				<result name="toAdd">/add.jsp</result>
				<result name="toIndex" type="redirect">UserAction_toIndex</result>
	    </action>
	</package>
</struts>



13.创建jsp

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
<style type="text/css">
body {
	margin: auto;
	width: 1080px;
}

table {
	width: 980px;
}
td {
	border: 1px solid ;
	width: 320px;
}
a:link{text-decoration: none;}
a:visited {
	text-decoration: none;
	color: blue;
}
a:hover {
	text-decoration: none;
	color: red;
}
h1 {
	text-align: center;
	border-bottom-style: dashed;
	width: 980px;
}
</style>
<body>
		<h1>myBatis+Struts2+jsp</h1>
		
		<table >
		<s:url action="UserAction_toUpdate" namespace="/user" var="toUpd"></s:url>
		<s:url action="UserAction_delete" namespace="/user" var="del"></s:url>
		<tr align="center">
			<td >姓名</td>
			<td>密码</td>
			<td >职位</td>
			<td >操作</td>
		</tr>
		<c:forEach items="${sessionScope.user_List}" var="user" varStatus="status">
			<tr align="center">
				<td>${user.username}</td>
				<td>${user.userpwd}</td>
				<td>${user.usertype}</td>
				<td> 
					【<a href="${toUpd}?id=${user.id}">修改</a>】  
					【<a href="${del}?id=${user.id}">删除</a>】
				</td>
			</tr>
		</c:forEach>
		</table>
		<s:url action="UserAction_toAdd" namespace="/user" var="toAdd"></s:url>
		<a href="${toAdd}">新增用户</a>
  </body>
</html>

add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"  %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'add.jsp' starting page</title>
<style type="text/css">
body {
	margin: auto;
	width: 1080px;
}
table {
	width: 980px;
}
td {
	border: 1px solid ;
	width: 320px;
}
a:link{text-decoration: none;}
a:visited {
	text-decoration: none;
	color: blue;
}
a:hover {
	text-decoration: none;
	color: red;
}
h1 {
	text-align: center;
	border-bottom-style: dashed;
	width: 980px;
}
</style>
  </head>
  <body>
    		<h1>新增用户</h1>
		    <s:form action="UserAction_add" namespace="/user" method="post">
				      id:<s:textfield name="id" />
					      姓名:<s:textfield name="username" />
					      密码:<s:textfield name="userpwd" />
					      职位:<s:textfield name="usertype" />
				      <s:submit value="提交"/>
		    </s:form>
  </body>
</html>

update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"  %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'add.jsp' starting page</title>
   <style type="text/css">
body {
	margin: auto;
	width: 1080px;
}

table {
	width: 980px;
}

td {
	border: 1px solid ;
	width: 320px;
}


a:link{text-decoration: none;}
a:visited {
	text-decoration: none;
	color: blue;
}

a:hover {
	text-decoration: none;
	color: red;
}


h1 {
	text-align: center;
	border-bottom-style: dashed;
	width: 980px;
}
</style>
  </head>
  <body>
		    <h1>修改用户信息</h1>
		    <s:form action="UserAction_update" namespace="/user" method="post">
			      id:  <s:textfield name="id" readonly="true"/>
				      姓名:<s:textfield name="username" />
				      密码:<s:textfield name="userpwd" />
				      职位:<s:textfield name="usertype" />
				      <s:submit value="提交"/>
		    </s:form>
  </body>
</html>

    原文作者:落尘曦
    原文地址: https://blog.csdn.net/qq_23994787/article/details/73826173
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。