JavaEE三大框架的整合
JavaEE三大框架的整合
2019-05-14 14:01:39
注:应用软件为:Eclipse+MySQL;三大框架版本为:Struts2+Spring5+Hibernate5
第一步准备工作
三大框架所用的.jar下载,文件见如下链接:
https://www.cnblogs.com/MrZhangxd/p/10793454.html
整合目录结构:(打马赛克的地方有个人信息,望宝宝们见谅)
第二步 配置SSH三大框架
将以上下载的.jar文件复制粘贴到WebContent/WEB-INF/lib文件夹下
第三步 主要实现业务逻辑代码
注:dao.impl、service.impl包在dao、service包建完并且里面有.java文件后在建,以免发生dao、service包被dao.impl、service.impl包所覆盖。
注:dao.impl、service.impl包在dao、service包建完并且里面有.java文件后在建,以免发生dao、service包被dao.impl、service.impl包所覆盖。
注:dao.impl、service.impl包在dao、service包建完并且里面有.java文件后在建,以免发生dao、service包被dao.impl、service.impl包所覆盖。
(重要的事说三遍)
|--Src
| |--org.xxx.com.action
| | |--LoginAction.java
| | |--RegisterAction.java
| |--org.xxx.com.dao
| | |--UserDao.java(interface)
| |--org.xxx.com.dao.impl(implement)
| | |--UserDaoImpl.java(实现接口类)
| |--org.xxx.com.exception
| | |--AgeException.java
| |--org.xxx.com.po
| | |--User.java
| |--org.xxx.com.service
| | |--UserService.java(interface)
| |--org.xxx.com.service.impl(implement)
|_|_|_UserServiceImpl.java(实现接口类)
主要代码如下:不在多余解释,有啥看不懂可以发我邮箱,有时间会给宝宝们解决的
LoginAction.java
package org.xxx.com.action; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.xxx.com.po.User; import org.xxx.com.service.UserService; @Controller() @Scope("prototype") publicclass LoginAction { @Autowired private UserService userService; private User user; public User getUser() { returnuser; } publicvoid setUser(User user) { this.user = user; } public String login() { List<User> u= userService.login(user); if(u.size()>0) { return"success"; } else{ return"error"; } } } |
RegisterAction.java
package c.action; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.xxx.com.exception.AgeException; import org.xxx.com.po.User; import org.xxx.com.service.UserService; import com.opensymphony.xwork2.ActionContext; @Controller() @Scope("prototype") publicclass RegisterAction { @SuppressWarnings("unused") @Autowired private UserService userService; private User user; public User getUser() { returnuser; } publicvoid setUser(User user) { this.user = user; } public String execute() { if (user.getAge()>100) { thrownew AgeException("年龄不符合要求"); } userService.addUser(user); return"success"; } public String updateUser() {
userService.updateUser(user);
return"success"; } public String deleteUser() {
userService.deleteUser(user);
return"success"; } public String queryUsers() { List<User> lsit= userService.queryUsers(); ActionContext ctx= ActionContext.getContext(); ctx.put("list", lsit); //表示request对象,ctx.getSession(); //这个方法可以得到session的东西,但是没有得到session对象,可以对此进行put,ctx.getSession().get(key)可以获取session中对象 //Map map= return"success"; } public String getById() { User u= userService.getById(user.getId()); ActionContext ctx= ActionContext.getContext(); ctx.put("u", u); //表示request对象,ctx.getSession(); return"success"; } } |
UserDao.java
package org.xxx.com.dao; import java.util.List; import org.xxx.com.po.User; publicinterface UserDao { public Integer insertUser(User user); public List<User> login(User user); publicint updateUser(User user); publicint deleteUser(User user); public List<User> queryUsers(); public User getById(intid); } |
UserDaoImpl.java
package org.xxx.com.dao.impl; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.xxx.com.dao.UserDao; import org.xxx.com.po.User; @Repository("userDao") publicclass UserDaoImpl implements UserDao { @Autowired private SessionFactory SessionFactory ; private Session getSession() { returnSessionFactory.getCurrentSession(); } @Override public Integer insertUser(User user) { getSession().save(user); returnnull; } @Override public List<User> login(User user) { String hql="select distinct u from User u where u.username=?0 and u.password=?1 "; @SuppressWarnings("rawtypes") Query query =getSession().createQuery(hql); query.setParameter(0+"", user.getUsername()); query.setParameter(1+"", user.getPassword()); // query.setFirstResult(1).setMaxResults(1); //System.out.println(query.list().size()); @SuppressWarnings("unchecked") List<User> list= query.list(); returnlist; } @Override publicint updateUser(User user) { String hql="update User u set username=?0,password=?1 ,age=?2 where id=?3 "; @SuppressWarnings("rawtypes") Query query =getSession().createQuery(hql); query.setParameter(0+"", user.getUsername()); query.setParameter(1+"", user.getPassword()); query.setParameter(2+"", user.getAge()); query.setParameter(3+"", user.getId()); intresult = query.executeUpdate(); returnresult; } @Override publicint deleteUser(User user) { String hql="delete from User u where u.id=?0 "; @SuppressWarnings("rawtypes") Query query =getSession().createQuery(hql); query.setParameter(0+"", user.getId());
intresult = query.executeUpdate(); returnresult; } @Override public List<User> queryUsers() { String hql="select distinct u from User u "; @SuppressWarnings("rawtypes") Query query =getSession().createQuery(hql); @SuppressWarnings("unchecked") List<User> list= query.list(); returnlist; } @Override public User getById(intid) { String hql="select distinct u from User u where u.id=?0"; @SuppressWarnings("rawtypes") Query query =getSession().createQuery(hql); query.setParameter(0+"", id); @SuppressWarnings("unchecked") List<User> list_u=query.list(); User list=null; if(list_u.size()>0){ list = list_u.get(0); } returnlist; } } |
AgeException
package org.xxx.com.exception; @SuppressWarnings("serial") publicclass AgeException extends RuntimeException {
public AgeException() { super(); // TODO Auto-generated constructor stub } public AgeException(String message, Throwable cause, booleanenableSuppression, booleanwritableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public AgeException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public AgeException(String message) { super(message); // TODO Auto-generated constructor stub } public AgeException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } } |
User.java
package org.xxx.com.po; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="tb_user") publicclass User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String username; private String password; private Integer age; public Integer getId() { returnid; } publicvoid setId(Integer id) { this.id = id; } public String getUsername() { returnusername; } publicvoid setUsername(String username) { this.username = username; } public String getPassword() { returnpassword; } publicvoid setPassword(String password) { this.password = password; } public Integer getAge() { returnage; } publicvoid setAge(Integer age) { this.age = age; }
public User() { super(); } public User(String username, String password, Integer age) { super(); this.username = username; this.password = password; this.age = age; } } |
UserService.java
package org.xxx.com.service; import java.util.List; import org.xxx.com.po.User; publicinterface UserService { publicvoid addUser(User user); public List<User> login(User user); publicint updateUser(User user); publicint deleteUser(User user); public List<User> queryUsers(); public User getById(intid); } |
UserServiceImpl.java
package org.xxx.com.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.xxx.com.dao.UserDao; import org.xxx.com.po.User; import org.xxx.com.service.UserService; @Service("userService") publicclass UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Transactional publicvoid addUser(User user) { userDao.insertUser(user); } @Transactional(readOnly=true) @Override public List<User> login(User user) { returnuserDao.login(user); } @Transactional @Override publicint updateUser(User user) { returnuserDao.updateUser(user); } @Transactional @Override publicint deleteUser(User user) { return userDao.deleteUser(user); } @Transactional(readOnly=true) @Override public List<User> queryUsers() { // TODO Auto-generated method stub returnuserDao.queryUsers(); } @Transactional(readOnly=true) @Override public User getById(intid) { returnuserDao.getById(id); } } |
第四步 主要是配置文件
web.xml
struts.xml
applicationContext.xml
hibernate.cfg.xml
db.properties
接下来一个一个来配置(配置属性不多解释,有啥看不懂可以发我邮箱,有时间会给宝宝们解决的)
web.xml
<?xmlversion="1.0"encoding="UTF-8"?> <web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID"version="3.1"> <display-name>Project_JavaEE_Lab_04</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 配置 spring配置文件的名称和位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 启动IoC容器的listener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- struts过滤器配置 --> <filter> <filter-name>Struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>Struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
</web-app> |
struts.xml
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEstrutsPUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constantname="struts.enable.DynamicMethodInvocation"value="false"/> <packagename="default"namespace="/"extends="struts-default"> <actionname="registerA" class="org.xxx.com.action.RegisterAction"> <resultname="success">/WEB-INF/content/welcome.jsp</result> </action> <actionname="*"> <result>/WEB-INF/content/register.jsp</result> </action> <actionname="loginAction" class="org.xxx.com.action.LoginAction"method="login"> <resultname="success">/WEB-INF/content/welcome.jsp</result> <resultname="error">/WEB-INF/content/loginForm.jsp</result> </action> <actionname="queryUsersAction"class="org.xxx.com.action.RegisterAction"method="queryUsers"> <resultname="success">/WEB-INF/content/listUser.jsp</result> <resultname="error">/WEB-INF/content/error.jsp</result> </action> <actionname="updateUserAction" class="org.xxx.com.action.RegisterAction"method="updateUser"> <resultname="success"type="redirectAction"> <paramname="actionName">queryUsersAction</param> </result> <resultname="error">/WEB-INF/content/error.jsp</result> </action> <actionname="deleteUserAction" class="org.xxx.com.action.RegisterAction"method="deleteUser"> <resultname="success">/WEB-INF/content/listUser.jsp</result> <resultname="error">/WEB-INF/content/error.jsp</result> </action> <actionname="getByIdAction"class="org.xxx.com.action.RegisterAction"method="getById"> <resultname="success">/WEB-INF/content/updateUser.jsp</result> <resultname="error">/WEB-INF/content/error.jsp</result> </action> </package> </struts> |
applicationContext.xml
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <context:component-scan base-package="org.xxx.com"> </context:component-scan> <context:property-placeholderlocation="classpath:db.properties"/> <beanid="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <propertyname="user"value="${jdbc.user}"></property> <propertyname="password"value="${jdbc.password}"></property> <propertyname="jdbcUrl"value="${jdbc.jdbcUrl}"></property> <propertyname="driverClass"value="${jdbc.driverClass}"></property> <propertyname="initialPoolSize"value="${jdbc.initPoolSize}"></property> <propertyname="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean>
<beanid="sessionFactory"class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <propertyname="dataSource"ref="dataSource"></property> <propertyname="configLocation"value="classpath:hibernate.cfg.xml"></property> </bean>
<!-- 配置事务管理器 --> <beanid="transactionManager"class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <propertyname="dataSource"ref="dataSource"></property> <propertyname="sessionFactory"ref="sessionFactory"></property> </bean> <!-- 启用事务注解 --> <tx:annotation-driventransaction-manager="transactionManager"/> </beans> |
hibernate.cfg.xml
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEhibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <propertyname="show_sql">true</property> <propertyname="hibernate.hbm2ddl.auto">update</property> <propertyname="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<mappingclass="org.xxx.com.po.User"/> </session-factory> </hibernate-configuration> |
db.properties
jdbc.user=数据库用户名 jdbc.password=数据库密码 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql://localhost:3306/db_ssh(数据库) jdbc.initPoolSize=5 jdbc.maxPoolSize=10 |
注db.properties可以以一下代码直接在hibernate.cfg.xml里面配置
<!-- 指定连接数据库所用的驱动 --> <property name="connection.driver_class">com.mysql.jdbc.Driver </property> <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 --> <property name="connection.url">jdbc:mysql://localhost:3306/ssh?useSSL=true </property> <!-- 指定连接数据库的用户名 --> <property name="connection.username">数据库用户名</property> <!-- 指定连接数据库的密码 --> <property name="connection.password">数据库密码</property> <!-- 指定连接池里最大连接数 --> <property name="hibernate.c3p0.max_size">20</property> <!-- 指定连接池里最小连接数 --> <property name="hibernate.c3p0.min_size">1</property> <!-- 指定连接池里连接的超时时长 --> <property name="hibernate.c3p0.timeout">5000</property> <!-- 指定连接池里最大缓存多少个Statement对象 --> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.validate">true</property> <!-- 指定数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect </property> |
第五步 Web前端
Regeister.jsp
LongForm.jsp
Welcome.jsp
ListUser.jsp
UpdataUser.jsp
Error.jsp
接下来一一写jsp页面
Regeister.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="css/styles.css" rel="stylesheet"> <title>Insert title here</title> </head> <body> <div> <div class="hesder"> </div> <div class="center"> <form action="registerA" class=""> <table> <tr> <td>用户名</td> <td><input type="text" name="user.username" /></td> </tr> <tr> <td>密码</td> <td><input type="password" name="user.password" /></td> </tr> <tr> <td>年龄</td> <td><input type="text" name="user.age" /></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value=注册 /></td> </tr> </table> </form> </div> <div class="footer"> <p>CopyRight ©<a href="https://www.cnblogs.com/MrZhangxd/">MrZhangxd</a>版权所有,违者必究!</p> </div> </div> </body> </html>
|
LongForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录</title> </head> <body> <div> <div></div> <div> <form action="loginAction" method="post"> <table> <tr> <td>用户名</td> <td><input type="text" name="user.username" /></td> </tr> <tr> <td>密码</td> <td><input type="password" name="user.password" /></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value=登录 /></td> </tr> </table> </form> </div> <div> <p>CopyRight ©<a href="https://www.cnblogs.com/MrZhangxd/">MrZhangxd</a>版权所有,违者必究!</p> </div> </div> </body> </html>
|
Welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>注册成功!! <br>用户名:<s:property value="user.username"/> <br>密码:<s:property value="user.password"/> <br>年龄:<s:property value="user.age"/> </h1> <br><a href="queryUsersAction">用户一栏表</a> </body> </html>
|
ListUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录</title> </head> <script type="text/javascript"> function update(id){ window.location.href="getByIdAction?user.id="+id; } </script> <body> <center> <table> <tr><td>顺序</td><td>id</td><td>用户名</td><td>密码</td><td>年龄</td></tr> <s:iterator value="list" status="st"> <tr> <td><s:property value="#st.index"/></td> <td><s:property value="id" /></td> <td><s:property value="username" /></td> <td><s:property value="password" /></td> <td><s:property value="age" /></td> <td><button onclick='update(<s:property value="id" />)'>修改</button></td> <td><button onclick='delete(<s:property value="id" />)'>删除</button></td> </tr> </s:iterator> </table> </center> </body> </html>
|
UpdataUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div> <div></div> <div> <form action="updateUserAction"> <table> <tr> <td colspan="2" align="center"><input type="hidden" name="user.id" value="${u.id}"/></td> </tr> <tr> <td>用户名</td> <td><input type="text" name="user.username" value="${u.username}"/></td> </tr> <tr> <td>密码</td> <td><input type="text" name="user.password" value="${u.password}"/></td> </tr> <tr> <td>年龄</td> <td><input type="text" name="user.age" value="${u.age}"/></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" /></td> </tr> </table> </form> </div> <div></div> </div> </body> </html>
|
Error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>访问错误页面</title> </head> <body> <h1>访问错误</h1> </body> |
到此为止ssh三大框架整合完成
第六步 数据操作
创建数据库
Create database db_ssh; |
创建tb_user表
CREATE TABLE `tb_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `password` varchar(255) DEFAULT NULL, `username` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; |
向tb_user表中插入数据
INSERT INTO `tb_user` VALUES ('1', 'xxx', '宝宝们', '永远18岁'); INSERT INTO `tb_user` VALUES ('2', 'xxx', '宝宝们', '永远18岁'); INSERT INTO `tb_user` VALUES ('3', 'xxx', '宝宝们', '永远18岁'); INSERT INTO `tb_user` VALUES ('4', 'xxx', '宝宝们', '永远18岁'); INSERT INTO `tb_user` VALUES ('5', 'xxx', '宝宝们', '永远18岁'); |
个人邮箱
QQ邮箱地址 | 2504900804@qq.com |
outLook邮箱地址 | Mr_Zhangxd@OutLook.com |
163邮箱地址 | 18943008875@163.com |