spring 5.1.5版本(五)

spring 5.1.5版本(一)

spring 5.1.5版本(二)

spring 5.1.5版本(三)

spring 5.1.5版本(四)

spring 5.1.5版本(五)

demo地址:https://gitee.com/gwlCode/springDemo

导包

hibernate

hibernate必要包 lib/required

d74f28871b90fe28f57dec626c024d5712a.jpg

hibernate jpa包 lib/jpa-metamodel-generator

06022c665e055b62fe837b0d4270d3cbe38.jpg

数据库驱动包

ce20c70d833ddc60735e0b8b66995ced597.jpg

struts2

核心包 Essential Dependencies Only/struts-2.5.20-min-lib.zip/lib

af15e69ba74c867c47fb04f456594e8aec3.jpg

struts2整合spring插件包 All Dependencies/struts-2.5.20-lib.zip/lib/struts2-spring-plugin-2.5.20.jar

f3111ad7dc0b676b2b05eb22834192dedfd.jpg

spring

基本

d383eefe7acfbaca072e66722b78aea57a9.jpg

整合web

f5e9c39a08fa3fb4f3f5a27939b06023674.jpg

整合aop

84d02907fa42ace7daf538e9617b5d11299.jpg

整合hibernate和事务

193fd2f53e70521da3908b1b6e5d0ef472d.jpg

整合junit测试

997cd9e4f5a32493be26382220c7e58bf41.jpg

日记包

37216529039e154bccce7360cee0f229609.jpg

c3p0

e59d82bef731a7cea2d804f2880badc3a50.jpg

jstl

f72ee41ea40151b0b41ed2b302729a6d07f.jpg

annotations-api.jar

e0bdc0b0d6e85b287da758567e79ff9d518.jpg

整合spring到web

创建配置文件 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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       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/aop http://www.springframework.org/schema/aop/spring-aop.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 ">

</beans>

配置spring随项目启动 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">
    
    <!--让spring随web启动而创建的监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!--配置spring配置文件位置参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
</web-app>

启动Tomcat测试

3c180bd9ab204c44a4238ece742965f48cc.jpg

361cbc4386d09f1f11a028183f74ae5c6a8.jpg

整合struts2到web

配置struts2主配置文件 struts.xml

<?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="ssh" namespace="/" extends="struts-default">
        <global-allowed-methods>regex:.*</global-allowed-methods>

        <action name="UserAction_*" class="com.company.web.action.UserAction" method="{1}" >
            <result name="success">/success.jsp</result>
        </action>
    </package>

</struts>

配置struts2核心过滤器 web.xml

    <!--struts2核心过滤器-->
    <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>

整合struts2到spring

配置常量 struts.xml

<?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>

    <!--将action的创建交给spring容器
    spring负责装配Action依赖属性(默认打开)
    <constant name="struts.objectFactory.spring.autoWire" value="name"></constant>
    -->
    <constant name="struts.objectFactory" value="spring"></constant>

    <package name="ssh" namespace="/" extends="struts-default">
        <global-allowed-methods>regex:.*</global-allowed-methods>

        <!-- class属性上填写applicationContext.xml配置中action对象的beanName
             完全由spring管理action生命周期,包括action的创建
             需要手动组装依赖属性
        -->
        <action name="UserAction_*" class="userAction" method="{1}" >
            <result name="success">/success.jsp</result>
        </action>
    </package>

</struts>

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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       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/aop http://www.springframework.org/schema/aop/spring-aop.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 ">

    <!-- 注意action对象作用范围一定是多例的,这样才符合struts2架构 -->
    <bean name="userAction" class="com.company.ssh.UserAction" scope="prototype">
        <property name="userService" ref="userService"></property>
    </bean>

    <bean name="userService" class="com.company.ssh.UserServiceImpl"></bean>

</beans>

整合hibernate与spring

配置applicationContext.xml

    <!-- 将SessionFactory配置到spring容器
         加载配置方法一:使用 applicationContext.xml配置信息(不推荐)
    <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean>
    -->

    <!-- 将SessionFactory配置到spring容器
         加载配置方法二:在spring配置中放置hibernate配置信息 -->
    <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

        <!-- 配置hibernate基本信息 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase?characterEncoding=utf8
                </prop>
                <prop key="hibernate.connection.username">root</prop>
                <prop key="hibernate.connection.password">root123</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>

                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
        <property name="mappingDirectoryLocations" value="classpath:com/company/domain"></property>

    </bean>

c3p0连接池

配置db.properties

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/mydatabase?characterEncoding=utf8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root123

引入连接池到spring

    <!-- 读取db.properties文件 -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!-- 配置c3p0连接池 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

将连接池注入给SessionFactory

    <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

        <!-- 将连接池注入到sessionFactory,hibernate会通过连接池获得连接 -->
        <property name="dataSource" ref="dataSource"></property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>

                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <property name="mappingDirectoryLocations" value="classpath:com/company/domain"></property>

    </bean>

HibernateTemplate模板操作数据库

UserDaoImpl

package com.company.dao.impl;

import com.company.dao.UserDao;
import com.company.domain.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

    @Override
    public User getByUserName(String name) {

       //HQL
       return getHibernateTemplate().execute(new HibernateCallback<User>() {
            @Override
            public User doInHibernate(Session session) throws HibernateException {

                String hql = "from User where name = ?0 ";
                Query query = session.createQuery(hql);
                query.setParameter(0, name);
                User user = (User) query.uniqueResult();
                return user;
            }
        });


        /*
        //Criteria
        DetachedCriteria dc = DetachedCriteria.forClass(User.class);
        dc.add(Restrictions.eq("id",id));
        List<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc);

        if (list!=null && list.size()>0) {
            return  list.get(0);
        }
        return null;
        */

    }
}

spring中配置dao注入sessionFactory   applicationContext.xml

    <!-- dao -->
    <bean name="userDao" class="com.company.dao.impl.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

aop事务

配置核心事务管理器 applicationContext.xml

    <!-- 核心事务管理器 -->
    <bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

xml配置aop事务

配置通知

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

配置将通知织入目标对象

    <aop:config>
        <aop:pointcut expression="execution(* com.company.service.impl.*ServiceImpl.*(..))" id="txPc"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
    </aop:config>

注解配置aop事务

开启注解事务

    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

 @Transactional

package com.company.service.impl;

import com.company.dao.UserDao;
import com.company.domain.User;
import com.company.service.UserService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Override
    public User getUserByPassword(User user) {
        return null;
    }

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)
    public void saveUser(User user) {
        userDao.save(user);
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

扩大session作用范围

为了避免使用懒加载时出现no-session问题,需要扩大session的作用范围

<?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">

    <!--让spring随web启动而创建的监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置spring配置文件位置参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- 扩大session作用范围 
    注意:openSessionInView一定要在struts的filter之前调用
         任何filter一定要在struts的filter之前调用
    -->
    <filter>
        <filter-name>openSessionInView</filter-name>
        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
    </filter>
    
    <!--struts2核心过滤器-->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>openSessionInView</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    
</web-app>

 

转载于:https://my.oschina.net/gwlCode/blog/3027122

ERROR 5436 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/back/comment_list.html]")] with root cause org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'list' cannot be found on null at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE] at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE] at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:51) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE] at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:406) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE] at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:90) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE] at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:109) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE] at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:328) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE] at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:263) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值