注册 登录
重磅消息:开通VIP会员,获取平台所有项目,永久使用,详细请咨询QQ:3376762016
远程服务部署安装,售后服务,请加QQ1:3376762016,QQ2:3597230140(即将满员),QQ3:1399491757(已满)
查看: 747|回复: 0
打印 上一主题 下一主题

Spring MVC框架学习与使用

[复制链接]

该用户从未签到

3518

主题

3532

帖子

66万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
668970
QQ
跳转到指定楼层
楼主
发表于 2016-5-28 16:54:57 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
Spring  MVC 背景介绍
Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架。通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer PagesJSP)技术、VelocityTilesiText POISpring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
常见MVC框架比较
运行性能上:
        Jsp+servlet>struts1>spring mvc>struts2+freemarker>>struts2,ognl,值栈。
开发效率上,基本正好相反。值得强调的是,spring mvc开发效率和struts2不相上下。
Struts2的性能低的原因是因为OGNL和值栈造成的。所以,如果你的系统并发量高,可以使用freemaker进行显示,而不是采用OGNL和值栈。这样,在性能上会有相当大得提高。
基于spring2.5注解实现的spring MVC项目
我们采用sprng MVC开发项目时,通常都会采用注解的方式,这样可以大大提高我们的开发效率。实现零配置。下面我们从零开始重新做一个spring MVC的配置。这个项目完全采用注解的方式开发。同时,我们以后的spring MVC项目也都会采用注解的方式。
1. 建立web项目
2. 导入jar(spring.jar, spring-webmvc.jar, commons-logging.jar。其他jar包为hibernate相关jar)
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>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>
4. springmvc-servlet.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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    ">
   
   
    <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <context:component-scan base-package="com.xz"/>
    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
    <!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/"
         p:suffix=".jsp"/>
   
   
    <!-- 配置dataSource 和sessionFactory -->
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>/WEB-INF/properties/jdbc.properties</value>
            </list>
        </property>
    </bean>
        <bean id="dataSource"
                class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
                <property name="driverClassName"
                        value="${driverClassName}">
                </property>
                <property name="url">
                        <value>${url}</value>
                </property>
                <property name="username" value="${username}"></property>
                <property name="password" value="${password}"></property>
        </bean>
        <bean id="sessionFactory"
                class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
                <property name="dataSource">
                        <ref local="dataSource"></ref>
                </property>
                <property name="mappingResources">
                        <list>
                                <value>com/xz/user/bean/User.hbm.xml</value>
                        </list>
                </property>
                <property name="hibernateProperties">
                        <value>
                                    hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
                                        hibernate.hbm2ddl.auto=update
                                        hibernate.show_sql=true
                                        hibernate.format_sql=false  <!-- 数据库出现异常时 是否格式化sql语句 -->
                                        hibernate.cache.use_second_level_cache=true <!-- 开启二级缓存 -->
                                    hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider     <!-- 这是用哪一种缓存的jar文件 -->
                                          hibernate.cache.use_query_cache=false  <!-- 对hql语句的缓存 -->
                           </value>
                </property>
        </bean>
        <!--  配置事务  -->
        <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
           <property name="sessionFactory" ref="sessionFactory"/>
        </bean>
        <!-- 使用基于注解方式配置事务 -->
    <tx:annotation-driven transaction-manager="txManager"/>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
        <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>
   
   
    </beans>
5. WEB-INF下建立jsp文件夹,并且将index.jsp放入该文件夹下。Index.jsp的内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">   
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
  </head>
  
  <body>
   <h1>**********${params.uname}</h1>
   <h1>**********${requestScope.u}</h1>
   <h1>**********${requestScope.user}</h1>
  </body>
</html>
6. 建立整个项目的包结构和相关类。如下图所示:
7. UserUserDaoUserServiceUserController类的代码如下:
package com.xz.po;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;
        private String uname;
        private String pwd;
       
       
        public String getPwd() {
                return pwd;
        }
        public void setPwd(String pwd) {
                this.pwd = pwd;
        }
        public int getId() {
                return id;
        }
        public void setId(int id) {
                this.id = id;
        }
        public String getUname() {
                return uname;
        }
        public void setUname(String uname) {
                this.uname = uname;
        }
       
       
}
package com.xz.dao;
import javax.annotation.Resource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.xz.po.User;
@Repository("userDao")
public class UserDao {
        @Resource
        private HibernateTemplate hibernateTemplate;
       
        public void add(User u){
                System.out.println("UserDao.add()");
                hibernateTemplate.save(u);
        }
        public HibernateTemplate getHibernateTemplate() {
                return hibernateTemplate;
        }
        public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
                this.hibernateTemplate = hibernateTemplate;
        }
       
}
package com.xz.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.xz.dao.UserDao;
import com.xz.po.User;
@Service("userService")
public class UserService {
        @Resource
        private UserDao userDao;
       
        public void add(String uname){
                System.out.println("UserService.add()");
                User u = new User();
                u.setUname(uname);
                userDao.add(u);
        }
        public UserDao getUserDao() {
                return userDao;
        }
        public void setUserDao(UserDao userDao) {
                this.userDao = userDao;
        }
       
}
package com.xz.web;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.xz.po.User;
import com.xz.service.UserService;
@Controller("userController")
@RequestMapping("/user.do")     
public class UserController  {
        @Resource
        private UserService userService;
       
        @RequestMapping(params="method=reg")
        public String reg(String uname) {
                System.out.println("HelloController.handleRequest()");
                userService.add(uname);
                return "index";
        }
       
        public UserService getUserService() {
                return userService;
        }
        public void setUserService(UserService userService) {
                this.userService = userService;
        }
       
}
8. 运行测试:
http://pc-201110291327:8080/springmvc02/user.do?method=reg&uname=gaoqi
则会调用userControllerreg方法,从而将数据内容插入到数据库中。
@Controller控制器定义
Struts1一样,SpringControllerSingleton。这就意味着会被多个请求线程共享。因此,我们将控制器设计成无状态类。
spring 中,通过@controller标注即可将class定义为一个controller类。为使spring能找到定义为controllerbean,需要在spring-context配置文件中增加如下定义
<context:component-scan base-package="com.xz.web"/>
        注:实际上,使用@component,也可以起到@Controller同样的作用。
@RequestMapping
        在类前面定义,则将url和类绑定。
        在方法前面定义,则将url和类的方法绑定,如下所示:
package com.xz.web;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.xz.service.UserService;
@Controller
@RequestMapping("/user.do")
public class UserController  {
        @Resource
        private UserService userService;
       
        //http://localhost:8080/springmvc02/user.do?method=reg&uname=zzzz
        @RequestMapping(params="method=reg")
        public String reg(String uname) {
                System.out.println("HelloController.handleRequest()");
                userService.add(uname);
                return "index";
        }
       
        public UserService getUserService() {
                return userService;
        }
        public void setUserService(UserService userService) {
                this.userService = userService;
        }
       
}
@RequestParam
        一般用于将指定的请求参数付给方法中形参。示例代码如下:
       
@RequestMapping(params="method=reg5")
        public String reg5(@RequestParam("name")String uname,ModelMap map) {
                System.out.println("HelloController.handleRequest()");
                System.out.println(uname);
                return "index";
        }
       
        这样,就会将name参数的值付给uname。当然,如果请求参数名称和形参名称保持一致,则不需要这种写法。
Controller类中方法参数的处理
Controller类中方法返回值的处理
1. 返回string(建议)
a) 根据返回值找对应的显示页面。路径规则为:prefix前缀+返回值+suffix后缀组成
b) 代码如下:
@RequestMapping(params="method=reg4")
        public String reg4(ModelMap map) {
                System.out.println("HelloController.handleRequest()");
                return "index";
        }
前缀为:/WEB-INF/jsp/    后缀是:.jsp
在转发到:/WEB-INF/jsp/index.jsp
2. 也可以返回ModelMapModelAndViewmapListSetObject、无返回值。 一般建议返回字符串!
请求转发和重定向
        代码示例:
       
package com.xz.web;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
@Controller
@RequestMapping("/user.do")
public class UserController  {
       
        @RequestMapping(params="method=reg4")
        public String reg4(ModelMap map) {
                System.out.println("HelloController.handleRequest()");
//                return "forward:index.jsp";
//                return "forward:user.do?method=reg5"; //转发
//                return "redirect:user.do?method=reg5";  //重定向
                return "redirect:http://www.baidu.com";  //重定向
        }
       
        @RequestMapping(params="method=reg5")
        public String reg5(String uname,ModelMap map) {
                System.out.println("HelloController.handleRequest()");
                System.out.println(uname);
                return "index";
        }
       
}
       
        访问reg4方法,既可以看到效果。
获得request对象、session对象
普通的Controller类,示例代码如下:
@Controller
@RequestMapping("/user.do")
public class UserController  {
       
        @RequestMapping(params="method=reg2")
        public String reg2(String uname,HttpServletRequest req,ModelMap map){
                req.setAttribute("a", "aa");
                req.getSession().setAttribute("b", "bb");
                return "index";
        }
}
ModelMap
        是map的实现,可以在其中存放属性,作用域同request。下面这个示例,我们可以在modelMap中放入数据,然后在forward的页面上显示这些数据。通过el表达式、JSTLjava代码均可。代码如下:
       
package com.xz.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
@Controller
@RequestMapping("/user.do")
public class UserController extends MultiActionController  {
       
        @RequestMapping(params="method=reg")
        public String reg(String uname,ModelMap map){
                map.put("a", "aaa");
                return "index";
        }
}
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head></head>
  <body>
           <h1>${requestScope.a}</h1>
           <cut value="${requestScope.a}"></cut>
  </body>
</html>
ModelAndView模型视图类
见名知意,从名字上我们可以知道ModelAndView中的Model代表模型,View代表视图。即,这个类把要显示的数据存储到了Model属性中,要跳转的视图信息存储到了view属性。我们看一下ModelAndView的部分源码,即可知其中关系:
public class ModelAndView {
        /** View instance or view name String */
        private Object view;
        /** Model Map */
        private ModelMap model;
        /**
         * Indicates whether or not this instance has been cleared with a call to {@link #clear()}.
         */
        private boolean cleared = false;
        /**
         * Default constructor for bean-style usage: populating bean
         * properties instead of passing in constructor arguments.
         * @see #setView(View)
         * @see #setViewName(String)
         */
        public ModelAndView() {
        }
        /**
         * Convenient constructor when there is no model data to expose.
         * Can also be used in conjunction with <code>addObject</code>.
         * @param viewName name of the View to render, to be resolved
         * by the DispatcherServlet's ViewResolver
         * @see #addObject
         */
        public ModelAndView(String viewName) {
                this.view = viewName;
        }
        /**
         * Convenient constructor when there is no model data to expose.
         * Can also be used in conjunction with <code>addObject</code>.
         * @param view View object to render
         * @see #addObject
         */
        public ModelAndView(View view) {
                this.view = view;
        }
        /**
         * Creates new ModelAndView given a view name and a model.
         * @param viewName name of the View to render, to be resolved
         * by the DispatcherServlet's ViewResolver
         * @param model Map of model names (Strings) to model objects
         * (Objects). Model entries may not be <code>null</code>, but the
         * model Map may be <code>null</code> if there is no model data.
         */
        public ModelAndView(String viewName, Map<String, ?> model) {
                this.view = viewName;
                if (model != null) {
                        getModelMap().addAllAttributes(model);
                }
        }
        /**
         * Creates new ModelAndView given a View object and a model.
         * <emphasis>Note: the supplied model data is copied into the internal
         * storage of this class. You should not consider to modify the supplied
         * Map after supplying it to this class</emphasis>
         * @param view View object to render
         * @param model Map of model names (Strings) to model objects
         * (Objects). Model entries may not be <code>null</code>, but the
         * model Map may be <code>null</code> if there is no model data.
         */
        public ModelAndView(View view, Map<String, ?> model) {
                this.view = view;
                if (model != null) {
                        getModelMap().addAllAttributes(model);
                }
        }
        /**
         * Convenient constructor to take a single model object.
         * @param viewName name of the View to render, to be resolved
         * by the DispatcherServlet's ViewResolver
         * @param modelName name of the single entry in the model
         * @param modelObject the single model object
         */
        public ModelAndView(String viewName, String modelName, Object modelObject) {
                this.view = viewName;
                addObject(modelName, modelObject);
        }
        /**
         * Convenient constructor to take a single model object.
         * @param view View object to render
         * @param modelName name of the single entry in the model
         * @param modelObject the single model object
         */
        public ModelAndView(View view, String modelName, Object modelObject) {
                this.view = view;
                addObject(modelName, modelObject);
        }
        /**
         * Set a view name for this ModelAndView, to be resolved by the
         * DispatcherServlet via a ViewResolver. Will override any
         * pre-existing view name or View.
         */
        public void setViewName(String viewName) {
                this.view = viewName;
        }
        /**
         * Return the view name to be resolved by the DispatcherServlet
         * via a ViewResolver, or <code>null</code> if we are using a View object.
         */
        public String getViewName() {
                return (this.view instanceof String ? (String) this.view : null);
        }
        /**
         * Set a View object for this ModelAndView. Will override any
         * pre-existing view name or View.
         */
        public void setView(View view) {
                this.view = view;
        }
        /**
         * Return the View object, or <code>null</code> if we are using a view name
         * to be resolved by the DispatcherServlet via a ViewResolver.
         */
        public View getView() {
                return (this.view instanceof View ? (View) this.view : null);
        }
        /**
         * Indicate whether or not this <code>ModelAndView</code> has a view, either
         * as a view name or as a direct {@link View} instance.
         */
        public boolean hasView() {
                return (this.view != null);
        }
        /**
         * Return whether we use a view reference, i.e. <code>true</code>
         * if the view has been specified via a name to be resolved by the
         * DispatcherServlet via a ViewResolver.
         */
        public boolean isReference() {
                return (this.view instanceof String);
        }
        /**
         * Return the model map. May return <code>null</code>.
         * Called by DispatcherServlet for evaluation of the model.
         */
        protected Map<String, Object> getModelInternal() {
                return this.model;
        }
        /**
         * Return the underlying <code>ModelMap</code> instance (never <code>null</code>).
         */
        public ModelMap getModelMap() {
                if (this.model == null) {
                        this.model = new ModelMap();
                }
                return this.model;
        }
        /**
         * Return the model map. Never returns <code>null</code>.
         * To be called by application code for modifying the model.
         */
        public Map<String, Object> getModel() {
                return getModelMap();
        }
        /**
         * Add an attribute to the model.
         * @param attributeName name of the object to add to the model
         * @param attributeValue object to add to the model (never <code>null</code>)
         * @see ModelMap#addAttribute(String, Object)
         * @see #getModelMap()
         */
        public ModelAndView addObject(String attributeName, Object attributeValue) {
                getModelMap().addAttribute(attributeName, attributeValue);
                return this;
        }
        /**
         * Add an attribute to the model using parameter name generation.
         * @param attributeValue the object to add to the model (never <code>null</code>)
         * @see ModelMap#addAttribute(Object)
         * @see #getModelMap()
         */
        public ModelAndView addObject(Object attributeValue) {
                getModelMap().addAttribute(attributeValue);
                return this;
        }
        /**
         * Add all attributes contained in the provided Map to the model.
         * @param modelMap a Map of attributeName -> attributeValue pairs
         * @see ModelMap#addAllAttributes(Map)
         * @see #getModelMap()
         */
        public ModelAndView addAllObjects(Map<String, ?> modelMap) {
                getModelMap().addAllAttributes(modelMap);
                return this;
        }
        /**
         * Clear the state of this ModelAndView object.
         * The object will be empty afterwards.
         * <p>Can be used to suppress rendering of a given ModelAndView object
         * in the <code>postHandle</code> method of a HandlerInterceptor.
         * @see #isEmpty()
         * @see HandlerInterceptor#postHandle
         */
        public void clear() {
                this.view = null;
                this.model = null;
                this.cleared = true;
        }
        /**
         * Return whether this ModelAndView object is empty,
         * i.e. whether it does not hold any view and does not contain a model.
         */
        public boolean isEmpty() {
                return (this.view == null && CollectionUtils.isEmpty(this.model));
        }
        /**
         * Return whether this ModelAndView object is empty as a result of a call to {@link #clear}
         * i.e. whether it does not hold any view and does not contain a model.
         * <p>Returns <code>false</code> if any additional state was added to the instance
         * <strong>after</strong> the call to {@link #clear}.
         * @see #clear()
         */
        public boolean wasCleared() {
                return (this.cleared && isEmpty());
        }
        /**
         * Return diagnostic information about this model and view.
         */
        @Override
        public String toString() {
                StringBuilder sb = new StringBuilder("ModelAndView: ");
                if (isReference()) {
                        sb.append("reference to view with name '").append(this.view).append("'");
                }
                else {
                        sb.append("materialized View is [").append(this.view).append(']');
                }
                sb.append("; model is ").append(this.model);
                return sb.toString();
        }
}
测试代码如下:
package com.xz.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.xz.po.User;
@Controller
@RequestMapping("/user.do")
public class UserController extends MultiActionController  {
       
        @RequestMapping(params="method=reg")
        public ModelAndView reg(String uname){
                ModelAndView mv = new ModelAndView();
                mv.setViewName("index");
//                mv.setView(new RedirectView("index"));
               
                User u = new User();
                u.setUname("高淇");
                mv.addObject(u);   //查看源代码,得知,直接放入对象。属性名为”首字母小写的类名”。 一般建议手动增加属性名称。
                mv.addObject("a", "aaaa");
                return mv;
        }
}
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
           <h1>${requestScope.a}</h1>
           <h1>${requestScope.user.uname}</h1>
  </body>
</html>
结果为:
file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml\wps7E5F.tmp.jpg
基于spring mvc 框架的文件上传实现
1. spring使用了apache-commons下得上传组件,因此,我们需要引入两个jar包:
1. apache-commons-fileupload.jar
2. apache-commons-io.jar
2.  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>
3.  建立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>
4. 建立控制器,代码如下:
       
package com.xz.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;
       
        @Override
        public void setServletContext(ServletContext context) {
                this.servletContext  = context;
        }
       
        @RequestMapping(value="/upload.do", method = RequestMethod.POST)
        public String handleUploadData(String name,@RequestParam("file")CommonsMultipartFile file){
                if (!file.isEmpty()) {
                           String path = this.servletContext.getRealPath("/tmp/");  //获取本地存储路径
                           System.out.println(path);
                           String fileName = file.getOriginalFilename();
                           String fileType = fileName.substring(fileName.lastIndexOf("."));
                           System.out.println(fileType);
                           File file2 = new File(path,new Date().getTime() + fileType); //新建一个文件
                           try {
                                    file.getFileItem().write(file2); //将上传的文件写入新建的文件中
                           } catch (Exception e) {
                                    e.printStackTrace();
                           }
                           return "redirect:upload_ok.jsp";
                        }else{
                                return "redirect:upload_error.jsp";
                        }
        }
}
5. 建立upload_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>
6. 建立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>
1. 发布项目,运行测试:http://localhost:8080/springmvc03/upload.jsp
   进入项目发布后的目录,发现文件上传成功:

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
java无忧网(http://www.javawyw.com),专业提供Java大作业,小作业,课程设计,毕业设计源码,答辩辅导,作业排错,bug修复,专业解答,远程部署运行项目等服务
本网站所有源码,保证能运行!
QQ:1399491757
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回列表 返回顶部