1.新建Maven项目,在pom.xml文件添加ssh框架所需依赖jar包的代码
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<packaging>warpackaging>
<name>foundSSHname>
<groupId>foundSSHgroupId>
<artifactId>foundSSHartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<struts.version>2.5.10struts.version>
<spring.version>4.3.8.RELEASEspring.version>
<hibernate.version>5.1.7.Finalhibernate.version>
properties>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jettygroupId>
<artifactId>maven-jetty-pluginartifactId>
<version>6.1.7version>
<configuration>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8888port>
<maxIdleTime>30000maxIdleTime>
connector>
connectors>
<webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}webAppSourceDirectory>
<contextPath>/contextPath>
configuration>
plugin>
plugins>
<resources>
<resource>
<directory>${basedir}/src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
includes>
resource>
resources>
build>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-coreartifactId>
<version>${struts.version}version>
dependency>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-spring-pluginartifactId>
<version>${struts.version}version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-coreartifactId>
<version>${hibernate.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.42version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.10version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.25version>
dependency>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>7.0version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.9.1version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-apiartifactId>
<version>2.9.1version>
dependency>
dependencies>
project>
2.将项目的包建好,如下图
3.在resources文件目录下创建spring配置文件applicationContext.xml
<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="edu.njxz.found.*"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">trueprop>
<prop key="hibernate.hbm2ddl.auto">updateprop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialectprop>
props>
property>
<property name="mappingLocations"
value="classpath:hbm/*.hbm.xml">
property>
bean>
<bean id="userDao" class="edu.njxz.found.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory">property>
bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* edu.njxz.found.service.*+.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
aop:config>
beans>
4.在resources目录下创建struts的配置文件struts.xml
<struts>
<package name="default" extends="struts-default" namespace="/">
<default-action-ref name="default" />
<action name="default">
<result>index.jspresult>
action>
package>
<package name="product" extends="struts-default" namespace="/"
strict-method-invocation="false">
<action name="usertest" class="userAction" >
<result name="success">success.jspresult>
action>
package>
struts>
5.在resources目录下创建jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/lostandfound?useSSL=true&characterEncoding=UTF-8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=Root
6.在resources目录下创建日志配置文件log4j2.xml
<configuration status="error">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
Console>
<File name="log" fileName="target/test.log" append="false">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
File>
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
<SizeBasedTriggeringPolicy size="500 MB" />
RollingFile>
appenders>
<loggers>
<root level="trace">
<appender-ref ref="RollingFile"/>
<appender-ref ref="Console"/>
root>
loggers>
configuration>
7.配置web.xml文件
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
web-app>
8.在entity包下创建一个实体类User
package edu.njxz.found.entity;
public class User {
private int userId; //用户id
private String userName;//用户名
private String userPassword;//密码
private String userEmail; //邮箱
private String userPhoto; //头像地址
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPhoto() {
return userPhoto;
}
public void setUserPhoto(String userPhoto) {
this.userPhoto = userPhoto;
}
}
9.创建Hibernate的映射文件User.hbm.xml(这里要注意,因为本项目使用Maven构建,所有User.hbm.xml文件如果放在跟User.java文件同一个包entity下,最后运行会报找不到User.hbm.xml文件的错误,我们将User.hbm.xml放在资源文件resources目录下)
<hibernate-mapping>
<class name="edu.njxz.found.entity.User" table="lf_user" lazy="false">
<id name="userId" column="user_id">
<generator class="increment"/>
id>
<property name="userName" type="java.lang.String">
<column name="user_name" length="30"/>
property>
<property name="userPassword" type="java.lang.String">
<column name="user_password"/>
property>
<property name="userEmail" type="java.lang.String">
<column name="user_email"/>
property>
<property name="userPhoto" type="java.lang.String">
<column name="user_photo"/>
property>
class>
hibernate-mapping>
10.在dao包下创建UserDao
package edu.njxz.found.dao;
import edu.njxz.found.entity.User;
public interface UserDao {
void saveUser(User user);
}
11.在dao包的子包impl包下创建UserDaoImpl
package edu.njxz.found.dao.impl;
import edu.njxz.found.dao.UserDao;
import edu.njxz.found.entity.User;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
public void saveUser(User user) {
this.getHibernateTemplate().save(user);
}
}
12.在service包下创建UserService接口
package edu.njxz.found.service;
import edu.njxz.found.entity.User;
public interface UserService {
void saveUser(User user);
}
13.在service的子包impl下创建UserServiceImpl
package edu.njxz.found.service.impl;
import edu.njxz.found.dao.UserDao;
import edu.njxz.found.entity.User;
import edu.njxz.found.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public void saveUser(User user) {
userDao.saveUser(user);
}
}
14.在action包下创建UserAction
package edu.njxz.found.action;
import com.opensymphony.xwork2.ActionSupport;
import edu.njxz.found.entity.User;
import edu.njxz.found.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport {
private Logger logger = Logger.getLogger(this.getClass());
@Autowired
private UserService userService;
private String userName;
private String password;
//重写execute方法
@Override
public String execute() throws Exception {
User user=new User();
user.setUserName("哈哈哈");
user.setUserPassword("123456");
userService.saveUser(user);
logger.info("保存成功");
return SUCCESS;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
}
15.在webapp目录下创建index.jsp 和success.jsp
<%--
Created by IntelliJ IDEA.
User: yangxuechen
Date: 2018/12/11
Time: 10:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
首页
16.success.jsp
<%--
Created by IntelliJ IDEA.
User: yangxuechen
Date: 2018/12/11
Time: 10:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
success
success
17.测试运行,往数据库中存储了一条记录
18.获取项目源码https://github.com/yangxuechen/ssh-learning-example/tree/master/foundSSH