SSH是java web开发中常见的框架组合,分别是struts2,Spring,Hibernate。
struts2需要配置核心过滤器,Spring需要配置WEB监听器。
实现的业务逻辑比较简单,从表单页面接收数据,通过struts2的模型驱动组装成Student对象,然后存入到数据库中。
项目结构概览:
1. java文件
1.1 PoJo类:
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
private String tel;
public Student() {
super();
}
public Student(String name, String sex, Integer age, String tel) {
super();
this.name = name;
this.sex = sex;
this.age = age;
this.tel = tel;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex
+ ", age=" + age + ", tel=" + tel + "]";
}
}
1.2 PoJo类的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!--Pojo类和表名之间的映射关系 -->
<class name="com.mq.pojo.Student" table="students">
<!--用来将类中的id属性与表中的主键建立映射,id标签就是用来配置主键的 -->
<id name="id" column="id">
<generator class="native"/>
</id>
<!-- 用来将类中的普通属性与表中的字段建立映射 -->
<property name="name" column="name"/>
<property name="sex" column="sex"/>
<property name="age" column="age"/>
<property name="tel" column="tel"/>
</class>
</hibernate-mapping>
1.3web层:Action类
@Controller(value="stuAction")
//Action是多例的,必须配置Scope为prototype
@Scope(value="prototype")
public class StudentAction extends ActionSupport implements ModelDriven<Student> {
@Resource(name="stuService")
private StudentService studentService;
//采用模型驱动的方式从页面获取数据
private Student student=new Student();
public String save() {
studentService.saveStudent(student);
return SUCCESS;
}
@Override
public Student getModel() {
// TODO Auto-generated method stub
return student;
}
}
1.4业务层:Service类
@Service(value="stuService")
//添加事务的注解
@Transactional
public class StudentService {
@Resource(name="stuDao")
private StudentDao studnetDao;
public void saveStudent(Student student) {
studnetDao.saveStudnet(student);
}
}
1.5持久层:Dao类
public class StudentDao extends HibernateDaoSupport {
public void saveStudnet(Student student) {
System.out.println(student);
this.getHibernateTemplate().save(student);
}
}
Dao类继承HibernateDaoSupport
2. 配置文件
2.1 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ssh</display-name>
<!-- 配置Spring框架整合WEB的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 解决延迟加载的问题 -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置Struts2框架的核心的过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.2 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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 先配置C3P0的连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///study"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- LocalSessionFactoryBean加载配置文件 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 先加载连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载方言,加载可选 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 引入hibernate的映射的配置文件 -->
<property name="mappingResources">
<list>
<value>com/mq/pojo/Student.hbm.xml</value>
</list>
</property>
</bean>
<!--开启注解扫描,可以扫描com.mq包下的所有bean -->
<context:component-scan base-package="com.mq"/>
<!-- 先配置平台事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启事务的注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--Dao都需要继承HibernateDaoSupport,注入sessionFactory -->
<bean id="stuDao" class="com.mq.dao.StudentDao">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Pojo类的数据库映射文件需要在applicationContext.xml中配置
2.3 struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 先配置包结构 -->
<package name="crm" extends="struts-default" namespace="/">
<!-- 如果Action由Spring框架来管理,class标签上只需要编写ID值 -->
<action name="student_*" class="stuAction" method="{1}">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
注意:Action的class标签不再是全路径,而是在Spring中配置的Id值。
2.4 log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
3. 表单页面
<%@ 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>Insert title here</title>
</head>
<body>
<form action="student_save" method="post">
username: <input type="text" name="name"><br>
sex: <input type="text" name="sex"><br>
age: <input type="text" name="age"><br>
电话号码: <input type="text" name="tel"><br>
<input type="submit" value="保存">
</form><br/><br/>
</body>
</html>