SSH框架学习(struts2+hibernate+spring)

SSH框架学习(struts2+hibernate+spring)

虽然struts2和hibernate这两个框架已经很老了,但是老项目中还是存在,通过这篇文章,可以带你快速入门这两个框架。迅速掌握SSH框架,以应对老项目。

Struts2

快速开始

  1. 导包:
<dependency>
       <groupId>org.apache.struts</groupId>
       <artifactId>struts2-core</artifactId>
       <version>2.5.26</version>
</dependency>
  1. 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>
  1. 编写Action:
package com.botao.ts.action;


import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport {
    public String a() {
        return SUCCESS;
    }
}
  1. 编写配置文件:
<?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>
  1. 访问127.0.0.1:8080/helloWord 即可看到对应的jsp页面

Struts2核心配置

  1. 常量配置
<?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

  1. 通过ActionContext访问(推荐)
ActionContext context = ActionContext.getContext();
  1. 通过特定接口访问
    • ServletRequestAware
    • ServletResponseAware
    • SessionAware
    • ServletContextAware
  2. 通过ServletActionContext访问
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
ServletContext servletContext = ServletActionContext.getServletContext();

Action处理请求参数

  1. 字段驱动(属性驱动)

  2. 模型驱动

拦截器

  1. 实现Interceptor的方法,return actionInvocation.invoke();//表示放行
  2. 代码:
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表达式

  1. 值栈

域,其实就是Request的一个属性

ActionContext context = ActionContext.getContext();
ValueStack valueStack = context.getValueStack();
valueStack.set("msg","ONGL");
<s:property value="user"/>
  1. 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();
  1. save

    session.save(new User(null, "admin", "12345"));
    
  2. update

    session.update(new User(1L,"admin","admin"));
    
  3. get

    User user = session.get(User.class, 1L);
    
  4. 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>

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&amp;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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页
评论

打赏作者

星时代曹波涛

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值