引言
ssh框架的整合
目录结构
实现代码
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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>./WEB-INF/applicationContext.xml</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
<absolute-ordering />
</web-app>
applicationContext.xml
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:component-scan base-package="com.Service"></context:component-scan>
<!--dataSource的配置-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/sshlogin?serverTimezone=GMT" />
<property name="username" value="root" />
<property name="password" value="123" />
</bean>
<!-- sessionFactory的配置 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" lazy-init="false">
<!-- 注入datasource,给sessionfactoryBean内setdatasource提供数据源 -->
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<!-- //加载实体类的映射文件位置及名称 -->
</bean>
<!-- 配置Spring声明式事务 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事务传播特性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 所有以'get'开头的方法是read-only的 -->
<tx:method name="get*" read-only="true"/>
<!-- 所有以'query'开头的方法是read-only的 -->
<tx:method name="login*" read-only="true"/>
<!-- 其他方法使用默认的事务设置 -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置参与事务的类 -->
<aop:config>
<aop:pointcut id="serviceMethod" expression="execution(* com.Dao.*.*(..))" />
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
</aop:config>
<bean id="userDaoImpl" class="com.Dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" ></property>
</bean>
<bean id="userServiceImpl" class="com.Service.UserServiceImpl">
</bean>
<bean id="login" class="com.Action.LoginActionModel">
<property name="userService" ref="userServiceImpl"/>
</bean>
<bean id="addUser" class="com.Action.AdduserAction">
<property name="userService" ref="userServiceImpl"/>
</bean>
</beans>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<action name="loginActionModel" class="login">
<result name="success">/message.jsp</result>
</action>
<action name="adduser" class="addUser">
<result name="success">/message.jsp</result>
</action>
</package>
</struts>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--指定数据库方言-->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- DB schema will be updated if needed -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--在控制台显示SQL语句-->
<property name="show_sql">true</property>
<!--将SQL脚本中语句格式化在输出-->
<property name="hibernate.format_sql">true</property>
<!--罗列所有的持久化类-->
<mapping class="com.Entity.User"/>
</session-factory>
</hibernate-configuration>
addUser.jap
<%@ taglib prefix="S" uri="/struts-tags" %>
<%--
Created by IntelliJ IDEA.
User: gao
Date: 2020/4/10
Time: 19:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<S:form action="adduser">
<S:textfield name="id" label="id"></S:textfield>
<S:textfield name="userName" label="Username"></S:textfield>
<S:password name="password" label="Password"></S:password>
<S:submit></S:submit>
</S:form>
</body>
</html>
login.jsp
<%@ taglib prefix="S" uri="/struts-tags" %>
<%--
Created by IntelliJ IDEA.
User: gao
Date: 2020/4/10
Time: 17:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
<S:form action="loginActionModel">
<S:textfield name="userName" label="Username"></S:textfield>
<S:password name="password" label="Password"></S:password>
<S:submit></S:submit>
</S:form>
<S:a href="adduser.jsp">注册</S:a>
</body>
</html>
message.jsp
<%@ taglib prefix="S" uri="/struts-tags" %>
<%--
Created by IntelliJ IDEA.
User: gao
Date: 2020/4/10
Time: 17:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${
message}
</body>
</html>
AdduserAction.java
package com.Action;
import com.Entity.User;
import com.Service.UserService;
import com.Service.UserServiceImpl;
import com.opensymphony.xwork2.Action;
public class AdduserAction implements Action {
private int id;
private static String userName;
private static String password;
private UserService userService;
public int getId() {
return id;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserService getUserService() {
return userService;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
private String message;
public static String getUserName() {
return userName;
}
public void setUserName(String userName) {
AdduserAction.userName = userName;
}
public static String getPassword() {
return password;
}
public void setPassword(String password) {
AdduserAction.password = password;
}
@Override
public String execute() throws Exception {
getUserService().add(new User(getId(),getUserName(),getPassword()));
message="添加成功";
return SUCCESS;
}
}
LoginActionModel.java
package com.Action;
import com.Service.UserService;
import com.opensymphony.xwork2.Action;
public class LoginActionModel implements Action {
private String userName;
private String password;
private String message;
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String getMessage() {
return message;
}
@Override
public String execute() {
if(getUserService().login(Integer.valueOf(getUserName()),getPassword())){
message="登陆成功";
return "success";
}else{
message="登陆失败";
return "success";
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserDao
package com.Dao;
import com.Entity.User;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface UserDao {
public boolean login(int id,String password);
public void add(User user);
}
UserDaoImpl.java
package com.Dao;
import com.Entity.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public class UserDaoImpl implements UserDao{
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session getSession()
{
return getSessionFactory().getCurrentSession();
}
public boolean login(int id, String password) {
String hql= "from com.Entity.User where id=?0 and password=?1";
Query q = getSession().createQuery(hql);
q.setParameter(0,id);
q.setParameter(1,password);
Object obj = q.uniqueResult();
if(obj!=null){
return true;
}else{
System.out.println("失败");
return false;
}
}
@Override
public void add(User user) {
getSession().save(user);
}
}
User.java
package com.Entity;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "user", schema = "sshlogin")
public class User {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String password;
public User() {
}
@Id
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public User(int id,String name,String password) {
this.name=name;
this.id=id;
this.password=password;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "name", nullable = false, length = 255)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "password", nullable = false, length = 255)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User that = (User) o;
return id == that.id &&
Objects.equals(name, that.name) &&
Objects.equals(password, that.password);
}
@Override
public int hashCode() {
return Objects.hash(id, name, password);
}
}
UserService .java
package com.Service;
import com.Entity.User;
import org.springframework.transaction.annotation.Transactional;
public interface UserService {
public boolean login(int id,String password);
public void add(User user) ;
}
UserServiceImpl.java
package com.Service;
import com.Dao.UserDao;
import com.Dao.UserDaoImpl;
import com.Entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public boolean login(int id, String password) {
return userDao.login(id,password);
}
@Override
public void add(User user) {
userDao.add(user);
}
}
运行结果
最初
添加数据
登录