SSH框架学习(struts2+hibernate+spring)
虽然struts2和hibernate这两个框架已经很老了,但是老项目中还是存在,通过这篇文章,可以带你快速入门这两个框架。迅速掌握SSH框架,以应对老项目。
Struts2
快速开始
- 导包:
复制代码
1
2
3
4
5
6<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.26</version> </dependency>
- web.xml:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<?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"> <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>
- 编写Action:
复制代码
1
2
3
4
5
6
7
8
9
10
11package com.botao.ts.action; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport { public String a() { return SUCCESS; } }
- 编写配置文件:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13<?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> <package name="hello" namespace="/" extends="struts-default"> <action name="helloWord" class="com.botao.ts.action.BaseAction" method="a"> <result name="success">/success.jsp</result> </action> </package> </struts>
- 访问127.0.0.1:8080/helloWord 即可看到对应的jsp页面
Struts2核心配置
- 常量配置
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21<?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> <!--编码为UTF-8--> <constant name="struts.i18n.encoding" value="UTF-8"/> <!--开发模式--> <constant name="struts.devMode" value="true"/> <!--后缀为.action或者啥也不设置--> <constant name="struts.action.extension" value="do,action,,"/> <!--关闭动态方法调用--> <constant name="struts.enable.DynamicMethodInvocation" value="false"/> <package name="hello" namespace="/" extends="struts-default"> <action name="helloWord" class="com.botao.ts.action.BaseAction" method="a"> <result name="success">/success.jsp</result> </action> </package> </struts>
获取ServletApi
- 通过ActionContext访问(推荐)
复制代码
1
2ActionContext context = ActionContext.getContext();
- 通过特定接口访问
- ServletRequestAware
- ServletResponseAware
- SessionAware
- ServletContextAware
- 通过ServletActionContext访问
复制代码
1
2
3
4
5HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); HttpSession session = request.getSession(); ServletContext servletContext = ServletActionContext.getServletContext();
Action处理请求参数
-
字段驱动(属性驱动)
-
模型驱动
拦截器
- 实现Interceptor的方法,return actionInvocation.invoke();//表示放行
- 代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37package com.botao.ts.interceptor; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletResponse; import java.util.Map; public class LoginInterceptor implements Interceptor { @Override public void destroy() { } @Override public void init() { } @Override public String intercept(ActionInvocation actionInvocation) throws Exception { System.out.println("拦截器开始"); Map<String, Object> session = ActionContext.getContext().getSession(); if (session.containsKey("user")){ return actionInvocation.invoke(); }else{ HttpServletResponse response = ServletActionContext.getResponse(); response.setStatus(403); return null; } } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14<package name="admin" namespace="/admin" extends="struts-default"> <interceptors> <interceptor name="login" class="com.botao.ts.interceptor.LoginInterceptor"/> <interceptor-stack name="login"> <interceptor-ref name="login"/> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors> <action name="index" class="com.botao.ts.action.AdminAction" method="index"> <interceptor-ref name="login"/> <result name="success">/admin.jsp</result> </action> </package>
defaultStack是默认的拦截器栈,用了自定义的拦截器必须显示调用,否则就会造成请求参数获取不到。
标签库
复制代码
1
2<%@ taglib prefix="s" uri="/struts-tags" %>
控制标签
用法示例:
复制代码
1
2
3
4
5
6<s:if test='1==2'>true</s:if> <s:else>false</s:else> <s:iterator var="i" value="{'java','php','python'}"> <s:property value="i" escapeHtml="false"/> </s:iterator>
数据标签
再说吧~
值栈和ONGL表达式
- 值栈
域,其实就是Request的一个属性
复制代码
1
2
3
4ActionContext context = ActionContext.getContext(); ValueStack valueStack = context.getValueStack(); valueStack.set("msg","ONGL");
复制代码
1
2<s:property value="user"/>
- ONGL表达式
ActionContext中的application、session、parameters等对象都是非根对象,在OGNL表达式中要访问他们,需要在表达式前面加上#前缀!
复制代码
1
2
3
4
5
6
7
8
9
10属性的引用例如:user.name 变量的引用例如:#name 静态变量的访问使用 @class@field 静态方法的调用使用 @class@method(args), 如果没有指定 class 那么默认就使用 java.lang.Math. 构造函数的调用例如:new java.util.ArrayList();
Hibernate
快速入门
导入依赖:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13<!-- hibernate--> <dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-core</artifactId> <version>6.0.0.Alpha7</version> </dependency> <!-- mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency>
编写核心配置文件hibernate.cfg.xml:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23<?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="hibernate.connection.url">jdbc:mysql:///hibernate8</property> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <!--方言--> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!--打印sql--> <property name="hibernate.show_sql">true</property> <!--sql格式化--> <property name="hibernate.format_sql">true</property> <!--自动生成数据表的策略--> <property name="hibernate.hbm2ddl.auto">update</property> <mapping resource="User.hbm.xml"/> </session-factory> </hibernate-configuration>
编写映射文件User.hbm.xml:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12<?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> <class name="com.botao.hb.User" table="user"> <id name="id" column="id"><generator class="native" /></id> <property name="username" column="username" /> <property name="password" column="password" /> </class> </hibernate-mapping>
CURD
基本步骤
复制代码
1
2
3
4
5
6
7
8Configuration configure = new Configuration().configure(); SessionFactory sessionFactory = configure.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); //具体业务 transaction.commit(); sessionFactory.close();
-
save
复制代码1
2session.save(new User(null, "admin", "12345"));
-
update
复制代码1
2session.update(new User(1L,"admin","admin"));
-
get
复制代码1
2User user = session.get(User.class, 1L);
-
delete
复制代码1
2
3User user = session.get(User.class, 1L); session.delete(user);
核心配置文件hibernate.cfg.xml
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24<?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="hibernate.connection.url">jdbc:mysql:///hibernate8</property> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <!--方言--> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!--打印sql--> <property name="hibernate.show_sql">true</property> <!--sql格式化--> <property name="hibernate.format_sql">true</property> <!--自动生成数据表的策略--> <property name="hibernate.hbm2ddl.auto">update</property> <mapping resource="User.hbm.xml"/> <mapping class="com.botao.hb.User"/> </session-factory> </hibernate-configuration>
SSH整合
依赖
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95<properties> <!-- 统一源码的编码方式 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 统一各个框架版本 --> <struts.version>2.5.26</struts.version> <spring.version>5.3.5</spring.version> <hibernate.version>6.0.0.Alpha7</hibernate.version> </properties> <dependencies> <!-- Junit依赖 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- Spring 核心依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring web依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring 核心依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring整合ORM框架依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!-- Struts2 核心依赖 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts.version}</version> </dependency> <!-- Struts2和Spring整合依赖 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts.version}</version> </dependency> <!-- Hibernate 核心依赖 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- MySQL 依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <!-- C3P0 依赖 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5</version> </dependency> <!-- AspectJ依赖 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency> <!-- 导入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> <scope>compile</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
JPA注解映射
表名
复制代码
1
2
3@Entity @Table(name = "user")
主键
复制代码
1
2
3
4@Id @GenericGenerator(name="inc50",strategy="increment") @GeneratedValue(generator="inc50")
列
复制代码
1
2
3@Column(name = "username",length = 50) private String username;
忽略字段
复制代码
1
2
3@Transient private String test;//不会持久化到数据库
spring整合hibernate
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56<?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: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="com.botao.hb.ts"/> <!-- 配置C3P0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 数据库连接相关信息 --> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernate8?useSSL=true&characterEncoding=UTF-8"/> <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/> <property name="user" value="root"/> <property name="password" value="123456"/> </bean> <!-- 配置Hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 注入连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置Hibernate属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop><!-- 是否展示SQL --> <prop key="hibernate.hbm2ddl.auto">update</prop><!-- 是否自动创建表结构 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop> </props> </property> <!-- 扫描并加载注解过的实体类 --> <property name="packagesToScan"> <list> <value>com.botao.hb.ts.entity</value> </list> </property> <!--<property name="mappingLocations" value="classpath:mp/*.xml"/>--> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <!-- 注入SessionFactory --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <aop:aspectj-autoproxy/> </beans>
spring整合struts2
复制代码
1
2
3
4
5
6
7
8
9
10
11
12@Component @Scope("prototype") public class AddAction extends ActionSupport { @Autowired private UserDao userDao;//演示直接调用Dao @Override public String execute() throws Exception { userDao.save(); return SUCCESS; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13<?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> <package name="default" namespace="/" extends="struts-default"> <action name="helloWord" class="AddAction" method="a"> <result name="success">/success.jsp</result> </action> </package> </struts>
这里的aciotn的class也可以写全限定名,让struts2自己创建
log4j配置文件
复制代码
1
2
3
4
5
6
7
8
9
10
11log4j.rootLogger=DEBUG,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout #%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t] {%c}-%m%n log4j.appender.stdout.layout.ConversionPattern=[%-5p] %l %d %rms:%m%n # file log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=./log.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t] {%c}-%m%n
最后
以上就是靓丽嚓茶最近收集整理的关于SSH框架学习(struts2+hibernate+spring)的全部内容,更多相关SSH框架学习(struts2+hibernate+spring)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复