看世界12326的gravatar头像
看世界12326 2014-10-23 16:04:57

spring 3.0+spring MVC+Hibernate框架搭建教程(附:springMVC文件上传功能)

SpringMVC的好处不用多说,下面简单总结下:

Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架。通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer Pages(JSP)技术、Velocity、Tiles、iText 和 POI。Spring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

常见MVC框架比较

运行性能上:

Jsp+servlet>struts1>spring mvc>struts2+freemarker>>struts2,ognl,值栈。

开发效率上,基本正好相反。值得强调的是,spring mvc开发效率和struts2不相上下。

Struts2的性能低的原因是因为OGNL和值栈造成的。所以,如果你的系统并发量高,可以使用freemaker进行显示,而不是采用OGNL和值栈。这样,在性能上会有相当大得提高。

一上午活少,顺便看了下springMVC,仔细过程如下:

1、建立web project项目

2、导入jar包(spring.jar, spring-webmvc.jar, commons-logging.jar。其他jar包为hibernate相关jar包)

spring 3.0+spring MVC+Hibernate框架搭建教程(附:springMVC文件上传功能)

3、修改web.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
	<servlet>
        <servlet-name>hellomvc30</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/hib-config.xml,/WEB-INF/springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>hellomvc30</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

4、在WEB-INF下增加springmvc-servlet.xml(这里包含service层类的相关配置)

<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd    
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

	<!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
	<context:component-scan base-package="com.hello.web" />

	<mvc:annotation-driven />  <!-- 支持spring3.0新的mvc注解 -->

	<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
	<!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/user/" p:suffix=".jsp">
		<!-- 如果使用jstl的话,配置下面的属性 -->
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
	</bean>
</beans>

5.在WEB-INF下增加hib-config.xml(这里包含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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<context:component-scan base-package="com.hello" />
	<!-- 支持aop注解 -->
	<aop:aspectj-autoproxy/>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/myhibnt?useUnicode=true&amp;characterEncoding=utf8"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<!-- key的名字前面都要加hibernate. -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">create</prop>
			</props>
		</property>
		<property name="packagesToScan">
			<value>com.hello.entity</value>
		</property>
	</bean>

	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory"><ref bean="sessionFactory"/></property>
	</bean>

	<!--配置一个JdbcTemplate实例-->
	<!--<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</bean>-->
	<!-- 配置事务管理 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<tx:annotation-driven transaction-manager="txManager" />
	<aop:config>
		<aop:pointcut id="businessService" expression="execution(public * com.hello.web.impl.*.*(..))"  />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />
	</aop:config>
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			
			<tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" />
			<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED" />
			<tx:method name="search*" read-only="true" propagation="NOT_SUPPORTED" />
			<tx:method name="query*" read-only="true" propagation="NOT_SUPPORTED" />
			<!-- get开头的方法不需要在事务中运行,有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->
			<tx:method name="*" />    <!-- 其他方法在事务中运行 -->
		</tx:attributes>
	</tx:advice>
</beans>

6、建立相关类和包结构,如下图所示:

spring 3.0+spring MVC+Hibernate框架搭建教程(附:springMVC文件上传功能)

7、部署Tomcat6,测试:直接在浏览器地址栏输入

  • http://localhost:8080/hellomvc30/user.do?method=register&nickname=xrhou&password=88888888

结果:数据库中增加xrhou的记录。

页面跳转到index.jsp上,显示:

spring 3.0+spring MVC+Hibernate框架搭建教程(附:springMVC文件上传功能)

7、各个代码在压缩文件代码下,下载查看。。。。

8、下面补充下springMVC的文件上传功能。

        spring使用了apache-commons下得上传组件,因此,我们需要引入两个jar包:

         apache-commons-fileupload.jar apache-commons-io.jar

8.1、在springmvc-servlet.xml配置文件中,增加CommonsMultipartResoler配置:

<!-- 处理文件上传 -->
<bean id="multipartResolver"  
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  
    <property name="defaultEncoding" value="gbk"/> <!-- 默认编码 (ISO-8859-1) -->  
    <property name="maxInMemorySize" value="10240"/> <!-- 最大内存大小 (10240)-->  
    <property name="uploadTempDir" value="/upload/"/> <!-- 上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->  
    <property name="maxUploadSize" value="-1"/> <!-- 最大文件大小,-1为无限止(-1) -->  
</bean>

8.2、建立upload.jsp,upload_ok.jsp,upload_error.jsp页面,内容如下:

a.upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>测试springmvc中上传的实现</title>
	</head>
	<body>
<form action="upload.do"  method="post" enctype="multipart/form-data">
			<input type="text" name="name" />
			<input type="file" name="file" />
			<input type="submit" />
		</form>
	</body>
</html>

b.load_ok.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
	   <h1>上传成功!</h1>
  </body>
</html>

c.upload_error.jsp

 <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
	   <h1>上传失败!</h1>
  </body>
</html>

8.4、上传主代码:

package com.hello.web;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class FileUploadController implements ServletContextAware {

	private ServletContext servletContext;

	public void setServletContext(ServletContext context) {
		this.servletContext=context;
	}
	public ServletContext getServletContext() {
		return servletContext;
	}
	
	@RequestMapping(value="/upload.do",method=RequestMethod.POST)
	public String handlerUploadDate(String name,@RequestParam("file")CommonsMultipartFile file){
		if(!file.isEmpty()){
			String path=this.servletContext.getRealPath("/upload/"); //获取本地存储路径
			String fileName=file.getOriginalFilename();
			String fileType=fileName.substring(fileName.lastIndexOf("."));
			File file2=new File(path, new Date().getTime()+fileType); //新建一个文件
			System.out.println(fileType);
			try {
				file.getFileItem().write(file2);//将上传的文件写入新建的文件中
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("姓名:"+name+"文件名:"+fileName+"本地存储路径为:"+path);
			return "redirect:upload_ok.jsp";
		} else{
			return "redirect:upload_error.jsp";
		}
	}

}

 


最代码官方编辑于2014-12-24 18:31:05


打赏

文件名:hellomvc30.zip,文件大小:15656.067K 下载
最代码最近下载分享源代码列表最近下载
mudingc木钉  LV30 2021年6月11日
15281682932  LV9 2021年4月9日
alphastar  LV6 2020年1月2日
三生石sh1  LV13 2019年1月8日
dingdehong  LV10 2018年12月27日
wang512237140  LV20 2018年12月20日
牧羊犬  LV6 2018年11月22日
luomazkf  LV15 2018年8月28日
李佳恒  LV8 2018年6月23日
xk9587  LV16 2018年6月11日
最代码最近浏览分享源代码列表最近浏览
WBelong  LV7 2023年12月11日
flygrass  LV12 2023年12月7日
星辰xc  LV2 2023年5月7日
1642172710  LV2 2022年12月13日
getset  LV8 2022年12月4日
sharon_taozi  LV1 2021年11月5日
gshnbb  LV9 2021年6月16日
mudingc木钉  LV30 2021年6月11日
1973356987  LV13 2021年6月9日
Vera.Wu  LV2 2021年5月30日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友