Spring4.2+springmvc4.2+hibernate4.2整合

1 篇文章 0 订阅
2 篇文章 0 订阅

在前两篇的ssh(spring4.2+struts2.3.29+hibernate4.2)博客(ssh(上)ssh(下))的基础上做一个小小的改动,把struts替换成springmvc。源码在github上。

[springmvc的视频是在网上找后下在手机里,这学期上毛概课时看的大笑]


1.给jar包减肥,即去掉struts2.3.29的jar包,把struts开头的jar删除即可。

jar包下载地址:http://download.csdn.net/detail/change_on/9565150

2.具体的项目架构就不展示,都是在前两篇的博客的基础上,基本不改动,就把struts2部分换成springmvc

具体的改动如下:

3.web.xml:把struts2的过滤器去掉,添加springmvc的中央处理器:

<!--?xml version="1.0" encoding="UTF-8"?-->  
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  <display-name></display-name>   
     
  <!-- 添加对spring的支持 -->  
  <context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>classpath:applicationContext.xml</param-value>  
  </context-param>  
     
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    
    <!-- 中央处理器 -->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- struts习惯使用/*,springmvc不管用 -->
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
       
  
  <!-- 该过滤器作用类似于取消懒加载,会在需要关联时向数据库发送请求 -->
   <filter>  
    <filter-name>openSessionInViewFilter</filter-name>  
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
    <init-param>  
      <param-name>singleSession</param-name>  
      <param-value>true</param-value>  
    </init-param>  
  </filter>  
     
   <filter-mapping>  
    <filter-name>openSessionInViewFilter</filter-name>  
    <url-pattern>*.do</url-pattern>  
  </filter-mapping>  
     
  <welcome-file-list>  
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
</web-app>  

4.去掉struts.xml,在applicationContext.xml上添加springmvc的视图解析器和上传文件的配置:

<?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:p="http://www.springframework.org/schema/p"  
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jee="http://www.springframework.org/schema/jee"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd    
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.hsp" />
    <!-- springmvc配置开始 -->
    <!-- 前缀+viewname+后缀(视图解析器) -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 从WebRoot到某一指定的文件夹目录 -->
    <property name="prefix" value="/WEB-INF/"></property>
    <!-- 视图名称的后缀 -->
    <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- id="multipartResolver"必须是multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- maxUploadSize文件上传最大值以byte为单位 -->
    <property name="maxUploadSize" value="1024000"></property>
    </bean>
    <!-- springmvc配置结束 -->
    <!-- 导入资源文件 -->  
    <context:property-placeholder location="classpath:db.properties" />  
   
   <!-- 配置c3p0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
    <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>   
    <!-- 配置Hibernate的SessionFactory实例:通过Spring提供的LocalSessionFactoryBean 进行配置-->
    <bean id="sessionFactory"  
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
        <property name="dataSource">  
            <ref bean="dataSource" />  
        </property>  
        <!-- 配置hibernate映射文件的位置名称 -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>  
         <!-- 使用hibernateProperties属性来配置Hibernate的原生属性 -->
        <!-- <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="mappingLocations" 
        value="classpath:com/hsp/domain/*.hbm.xml"></property>
    </bean>  
   
   <!-- 配置Spring的声明式事务 -->
    <!-- 1.配置事务管理器 -->
    <bean id="transactionManager"  
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory" />  
    </bean>  
   
    <!-- 2.配置事务属性,需要事务管理器 --> 
    <tx:advice id="txAdvice" transaction-manager="transactionManager">  
        <!-- 定义事务传播属性 -->  
        <tx:attributes>  
            <tx:method name="insert*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="edit*" propagation="REQUIRED" />  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="add*" propagation="REQUIRED" />  
            <tx:method name="new*" propagation="REQUIRED" />  
            <tx:method name="set*" propagation="REQUIRED" />  
            <tx:method name="remove*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="change*" propagation="REQUIRED" />  
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="load*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="*" propagation="REQUIRED" read-only="true" />  
        </tx:attributes>  
    </tx:advice>  
      
    <!-- 3.配置事务切点,并把切点和事务属性关联起来 -->
    <aop:config>  
        <aop:pointcut id="txPointcut" expression="execution(* com.hsp.service..*.*(..))" />  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />  
    </aop:config>  
</beans>  

5.com.hsp.action的LoginAction.java改动成springmvc的风格:

package com.hsp.action;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hsp.domain.User;
import com.hsp.service.Inter.UserService;
import com.hsp.utils.LoadPhoto;

@Controller//用来标注当前类是springmvc控制类
//@RequestMapping("/user")//如果要加上就相当与struts的namespace
public class LoginAction{
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login.do")
	public String login(User user,HttpServletRequest request){
		user=userService.checkUser(user);
		if(user!=null)
		{
			request.setAttribute("message","恭喜你,登录成功!");
			return "success";
		}
		else
		{
			request.setAttribute("message","密码或用户名有误!");
			return "login";
		}
	}
		
}


6.com.hsp.utils的LoadPhoto.java修改如下:

package com.hsp.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class LoadPhoto {
	
	public String uploadFengmian(String fileFileName,HttpServletRequest request){
		
		//转换request
		MultipartHttpServletRequest rm=(MultipartHttpServletRequest)request;
		//获得文件
		CommonsMultipartFile cfile=(CommonsMultipartFile)rm.getFile(fileFileName);
		//获得文件的字节数组
		byte[] bfile=cfile.getBytes();
		String filename="";
		//获得当前时间
		SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmssSSS");
		filename=format.format(new Date());
		Random random=new Random();
		//获得三位随机数
		for(int i=0;i<3;i++)
		{
		     filename =filename+random.nextInt(9);
		}
		//获取原始文件名
		String origFileName=cfile.getOriginalFilename();
		//xxx.jsp/png/...
	    String suffix=origFileName.substring(origFileName.lastIndexOf("."));
		//拿到项目的部署路径
		String path=request.getSession().getServletContext().getRealPath("/");
		OutputStream out=null;
		try {
			out=new FileOutputStream(new File(path+"/upload/"+filename+suffix));
			out.write(bfile);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return filename+suffix;
	}

}


7.这样就可以了。
其实从springmvc的写法上可以看出它与servlet有点像,两者也都是默认原型(prototype)模式的,而struts默认是单例(singleton)模式。经历过struts1的都知道struts获取数据是通过setter 和getter,而servlet、springmvc是直接有参数把值从前台带到后台。


  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:创作都市 设计师:CSDN官方博客 返回首页

打赏作者

J_小浩子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值