SSH框架整合
SSH框架
Struts2
快速开始
- 导包:
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.26</version>
</dependency>
- 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">
<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:
package com.botao.ts.action;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport {
public String a() {
return SUCCESS;
}
}
- 编写配置文件:
<?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核心配置
- 常量配置
<?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访问(推荐)
ActionContext context = ActionContext.getContext();
- 通过特定接口访问
- ServletRequestAware
- ServletResponseAware
- SessionAware
- ServletContextAware
- 通过ServletActionContext访问
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
ServletContext servletContext = ServletActionContext.getServletContext();
Action处理请求参数
-
字段驱动(属性驱动)
-
模型驱动
拦截器
- 实现Interceptor的方法,return actionInvocation.invoke();//表示放行
- 代码:
package 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;
}
}
}
<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是默认的拦截器栈,用了自定义的拦截器必须显示调用,否则就会造成请求参数获取不到。
标签库
<%@ taglib prefix="s" uri="/struts-tags" %>
控制标签
用法示例:
<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的一个属性
ActionContext context = ActionContext.getContext();
ValueStack valueStack = context.getValueStack();
valueStack.set("msg","ONGL");
<s:property value="user"/>
- ONGL表达式
ActionContext中的application、session、parameters等对象都是非根对象,在OGNL表达式中要访问他们,需要在表达式前面加上#前缀!
属性的引用例如:user.name
变量的引用例如:#name
静态变量的访问使用 @class@field
静态方法的调用使用 @class@method(args), 如果没有指定 class 那么默认就使用 java.lang.Math.
构造函数的调用例如:new java.util.ArrayList();
Hibernate
快速入门
导入依赖:
<!-- 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:
<?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:
<?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
基本步骤
Configuration configure = new Configuration().configure();
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
//具体业务
transaction.commit();
sessionFactory.close();
-
save
session.save(new User(null, "admin", "12345"));
-
update
session.update(new User(1L,"admin","admin"));
-
get
User user = session.get(User.class, 1L);
-
delete
User user = session.get(User.class, 1L); session.delete(user);
核心配置文件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="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>
如果不写hbm.xml映射文件,想用JPA的注解配置映射的话
直接指定累就行
SSH整合
依赖
<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注解映射
表名
@Entity
@Table(name = "user")
主键
@Id
@GenericGenerator(name="inc50",strategy="increment")
@GeneratedValue(generator="inc50")
列
@Column(name = "username",length = 50)
private String username;
忽略字段
@Transient
private String test;//不会持久化到数据库
spring整合hibernate
<?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
@Component
@Scope("prototype")
public class AddAction extends ActionSupport {
@Autowired
private UserDao userDao;//演示直接调用Dao
@Override
public String execute() throws Exception {
userDao.save();
return SUCCESS;
}
}
<?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配置文件
log4j.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