springMVC3.0(文件上传,@RequestMapping加參数,@SessionAttributes,@ModelAttribute,转发,重定向,数值获取,传參,ajax,拦截器)

1.项目包结构例如以下:

2.       spring配置文件springMVC.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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 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/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-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/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
 
 <!-- 处理文件上传 -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="defaultEncoding" value="utf-8"></property>
  <property name="maxInMemorySize" value="10240"></property>
  <property name="uploadTempDir" value="/upload/"></property>
  <property name="maxUploadSize" value="-1"></property>
 </bean>
 
 <!-- 配置内部资源视图解析器 -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/"></property>
  <property name="suffix" value=".jsp"></property>
 </bean>
</beans>

 

3.       spring配置文件beans.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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 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/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-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/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
 <!-- 注解驱动 -->
 <mvc:annotation-driven/>
 <!-- 组件扫描 -->
 <context:component-scan base-package="com.sxt.web"></context:component-scan>
 
 <!-- 定义数据源 -->
 <bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springmvc"></property>
  <property name="user" value="root"></property>
  <property name="password" value="123456"></property>
  <property name="initialPoolSize" value="10"></property>
  <property name="maxPoolSize" value="50"></property>
  <property name="minPoolSize" value="10"></property>
 </bean>
 
 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="ds"></property>
  
  <!-- hibernate映射文件的位置 -->
  <property name="mappingDirectoryLocations">
   <value>classpath:com/sxt/domain/</value>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.Dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
   </props>
  </property>
 </bean>
 
 <!-- 配置事物管理器 -->
 <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"/>
 </bean>
 
 <!-- 配置事物的传播特性 (事物通知)-->
 <tx:advice id="txAdvice" transaction-manager="txManager">
  <tx:attributes>
   <tx:method name="save*" propagation="REQUIRED"/>
   <tx:method name="delete*" propagation="REQUIRED"/>
   <tx:method name="update*" propagation="REQUIRED"/>
   <tx:method name="find*" read-only="true"/>
   <tx:method name="*" read-only="true"/>
  </tx:attributes>
 </tx:advice>
 
 <aop:config>
  <aop:advisor pointcut="execution(* *..*ServiceImpl.*(..))" advice-ref="txAdvice"/>
  <!--
   <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*ServiceImpl.*(..))"/>
   -->
 </aop:config>
</beans>

 

4.       web.xml文件不变

<?

xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
 <!-- 通过上下文參数指定spring配置文件的位置 -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:beans.xml</param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 
 <servlet>
  <servlet-name>action</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:springMVC.xml</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

5.       类的代码不变。

6.       执行,測试。跟上一个项目保持一致。

Spring MVC 3.0 深入

核心原理

1.       用户发送请求给server。

urluser.do

2.       server收到请求。

发现DispatchServlet能够处理。于是调用DispatchServlet

3.       DispatchServlet内部。通过HandleMapping检查这个url有没有相应的Controller

假设有。则调用Controller

4.      Controller開始运行。

5.       Controller运行完成后。假设返回字符串。则ViewResolver将字符串转化成对应的视图对象;假设返回ModelAndView对象,该对象本身就包括了视图对象信息。

6.       DispatchServlet将执视图对象中的数据,输出给server。

7.       server将数据输出给client。

spring3.0中相关jar包的含义

org.springframework.aop-3.0.3.RELEASE.jar

springaop面向切面编程

org.springframework.asm-3.0.3.RELEASE.jar

spring独立的asm字节码生成程序

org.springframework.beans-3.0.3.RELEASE.jar

IOC的基础实现

org.springframework.context-3.0.3.RELEASE.jar

IOC基础上的扩展服务

org.springframework.core-3.0.3.RELEASE.jar

spring的核心包

org.springframework.expression-3.0.3.RELEASE.jar

spring的表达式语言

org.springframework.web-3.0.3.RELEASE.jar

web工具包

org.springframework.web.servlet-3.0.3.RELEASE.jar

mvc工具包

 

 

@Controller控制器定义

Struts1一样,SpringControllerSingleton的。这就意味着会被多个请求线程共享。

因此,我们将控制器设计成无状态类。

 

spring 3.0中,通过@controller标注就可以将class定义为一个controller类。

为使spring能找到定义为controllerbean,须要在spring-context配置文件里添加例如以下定义:

 

<context:component-scan base-package="com.sxt.web"/>

 

        注:实际上,使用@component,也能够起到@Controller相同的作用。

 

@RequestMapping

 

    在类前面定义。则将url和类绑定。

      在方法前面定义。则将url和类的方法绑定,例如以下所看到的:

package com.sxt.web;

 

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import com.sxt.service.UserService;

 

@Controller

@RequestMapping("/user.do")

publicclass UserController {

 

    @Resource

    private UserServiceuserService;

   

    //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() {

       returnuserService;

    }

    publicvoid 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);

        //通过ModelMap传參

        map.put("name", uname);     

        return"index";

    }

        

         这样,就会将name參数的值付给uname。当然。假设请求參数名称和形參名称保持一致,则不须要这样的写法。

@SessionAttributes

    ModelMap中指定的属性放到session中。

演示样例代码例如以下:

   

@Controller

@RequestMapping("/user.do")

@SessionAttributes({"u","a"})  //ModelMap中属性名字为ua的再放入session中。这样。requestsession中都有了。

publicclass UserController {

    @RequestMapping(params="method=reg4")

    public String reg4(ModelMap map) {        System.out.println("HelloController.handleRequest()");

       map.addAttribute("u","uuuu"); //u放入request作用域中。这样转发页面也能够取到这个数据。

       return"index";

    }

}

  <body>

   <h1>**********${requestScope.u.uname}</h1>

   <h1>**********${sessionScope.u.uname}</h1>

  </body>

   

    注:名字为”user”的属性再结合使用注解@SessionAttributes可能会报错。

 

@ModelAttribute

     这个注解能够跟@SessionAttributes配合在一起用。能够将ModelMap中属性的值通过该注解自己主动赋给指定变量。

    演示样例代码例如以下:

package com.sxt.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")

@SessionAttributes({"u","a"}) 

publicclass UserController {

   

    @RequestMapping(params="method=reg4")

    public String reg4(ModelMap map) {

       System.out.println("HelloController.handleRequest()");

       map.addAttribute("u","尚学堂高淇");

       return"index";

    }

   

    @RequestMapping(params="method=reg5")

public String reg5(@ModelAttribute("u")String uname ,ModelMap map) {

       System.out.println("HelloController.handleRequest()");

       System.out.println(uname);

        return"index";

    }

   

}

 

先调用reg4方法,再调用reg5方法。我们发现控制台打印出来:尚学堂高淇

 

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.sxt.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")

publicclass 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")

publicclass 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.sxt.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")

publicclass UserControllerextends 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="utf-8"%>

<%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head></head>

  <body>

       <h1>${requestScope.a}</h1>

       <c:out value="${requestScope.a}"></c:out>

  </body>

</html>

 

ModelAndView模型视图类

见名知意,从名字上我们能够知道ModelAndView中的Model代表模型,View代表视图。即,这个类把要显示的数据存储到了Model属性中,要跳转的视图信息存储到了view属性。

我们看一下ModelAndView的部分源代码。就可以知当中关系:

publicclassModelAndView {

 

    /** View instance or view name String */

    private Objectview;

 

    /** Model Map */

    private ModelMapmodel;

 

    /**

     * Indicates whether or not this instance has been cleared with a call to{@link #clear()}.

     */

    privatebooleancleared =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.

     */

    publicvoid 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.viewinstanceof String ? (String) this.view :null);

    }

 

    /**

     * Set a View object for this ModelAndView. Will override any

     * pre-existing view name or View.

     */

    publicvoid 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.viewinstanceof 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.

     */

    publicboolean 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.

     */

    publicboolean isReference() {

       return (this.viewinstanceof String);

    }

 

    /**

     * Return the model map. May return<code>null</code>.

     * Called by DispatcherServlet for evaluation of the model.

     */

    protected Map<String, Object> getModelInternal() {

       returnthis.model;

    }

 

    /**

     * Return the underlying <code>ModelMap</code> instance (never<code>null</code>).

     */

    public ModelMap getModelMap() {

       if (this.model == null) {

           this.model =new ModelMap();

       }

       returnthis.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()

     */

    publicModelAndView addObject(String attributeName, Object attributeValue) {

       getModelMap().addAttribute(attributeName, attributeValue);

       returnthis;

    }

 

    /**

     * 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()

     */

    publicModelAndView addObject(Object attributeValue) {

       getModelMap().addAttribute(attributeValue);

       returnthis;

    }

 

    /**

     * 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()

     */

    publicModelAndView addAllObjects(Map<String, ?> modelMap) {

       getModelMap().addAllAttributes(modelMap);

       returnthis;

    }

 

 

    /**

     * 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

     */

    publicvoid 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.

     */

    publicboolean 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()

     */

    publicboolean 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.sxt.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.sxt.po.User;

 

@Controller

@RequestMapping("/user.do")

publicclass UserControllerextends 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");

       returnmv;

    }

 

}

<%@ page language="java"import="java.util.*"pageEncoding="gbk"%>

<%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

  </head>

  <body>

       <h1>${requestScope.a}</h1>

       <h1>${requestScope.user.uname}</h1>

  </body>

</html>

地址栏输入:http://localhost:8080/springmvc03/user.do?method=reg

结果为:

 

 

基于spring 3.0mvc 框架的文件上传实现

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

1.       apache-commons-fileupload.jar

2.       apache-commons-io.jar

 

2.  springmvc-servlet.xml配置文件里,添加CommonsMultipartResoler配置:

<!--处理文件上传 -->

<beanid="multipartResolver" 

    class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 

    <propertyname="defaultEncoding"value="gbk"/><!--默认编码 (ISO-8859-1) --> 

    <propertyname="maxInMemorySize"value="10240"/><!--最大内存大小 (10240)--> 

    <propertyname="uploadTempDir"value="/upload/"/><!--上传后的文件夹名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE),这个程序中的WebRoot下要有uploadtmp包。否则会报错 --> 

    <propertyname="maxUploadSize"value="-1"/><!--最大文件大小,-1为无限止(-1) --> 

</bean>

 

3.  建立upload.jsp页面,内容例如以下:

        

<%@ page language="java"import="java.util.*"pageEncoding="gbk"%>

<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

       <title>測试springmvc中上传的实现</title>

    </head>

    <body>

<formaction="upload.do" method="post"enctype="multipart/form-data">

           <inputtype="text"name="name"/>

           <inputtype="file"name="file"/>

           <inputtype="submit"/>

       </form>

    </body>

</html>

 

4. 建立控制器,代码例如以下:

        

package com.sxt.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")[微软用户2] 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"%>

<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

  </head>

  <body>

       <h1>上传成功!</h1>

  </body>

</html>

 

6. 建立upload_error.jsp页面

  <%@pagelanguage="java"import="java.util.*"pageEncoding="gbk"%>

<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

  </head>

  <body>

       <h1>上传失败!</h1>

  </body>

</html>

 

7.       公布项目,执行測试:http://localhost:8080/springmvc03/upload.jsp

   进入项目公布后的文件夹,发现文件上传成功:

 

处理ajax请求

spring使用了jackson类库。帮助我们在java对象和jsonxml数据之间的互相转换。他能够将控制器返回的对象直接转换成json数据,供client使用。client也能够传送json数据到server进行直接转换。

使用过程例如以下:

 

1.  项目中须要引入例如以下两个jar包:

                  jackson-core-asl-1.7.2jar

                   jackson-mapper-asl-1.7.2jar

2.  spring配置文件里改动:

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

    <!--启动Spring MVC的注解功能。完毕请求和注解POJO的映射 -->

      <beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 

        <propertyname="cacheSeconds"value="0"/> 

        <propertyname="messageConverters"> 

            <list> 

                <beanclass="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> 

            </list> 

        </property>

    </bean> 

 

3.       client代码a.jsp例如以下:

<%@pagelanguage="java"import="java.util.*"pageEncoding="gbk"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <basehref="<%=basePath%>">

   

    <title>My JSP 'index.jsp' starting page</title>

    <metahttp-equiv="pragma"content="no-cache">

    <metahttp-equiv="cache-control"content="no-cache">

    <metahttp-equiv="expires"content="0">   

    <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

    <metahttp-equiv="description"content="This is my page">

    <script>

       function createAjaxObj(){

           var req;

           if(window.XMLHttpRequest){

              req = new XMLHttpRequest();

           }else{

              req = new ActiveXObject("Msxml2.XMLHTTP"); //ie

           }

           return req;

       }

      

       function sendAjaxReq(){

           var req = createAjaxObj();

           req.open("get","myajax.do?

method=test2&uname=张三");

           req.setRequestHeader("accept","application/json");

           req.onreadystatechange  =function(){

              eval("var result="+req.responseText);

              document.getElementById("div1").innerHTML=result[0].uname;

           }

           req.send(null);

       }

    </script>

  </head>

 

  <body>

    <ahref="javascript:void(0);"onclick="sendAjaxReq();">測试</a>

    <divid="div1"></div>

  </body>

</html>

 

 

4.       server端代码例如以下:

        

package com.sxt.web;

 

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

 

import com.sxt.po.User;

 

@Controller

@RequestMapping("myajax.do")

public class MyAjaxController {

        

         @RequestMapping(params="method=test1",method=RequestMethod.GET)

         public @ResponseBody List<User> test1(String uname) throws Exception{

                   String uname2 = new String(uname.getBytes("iso8859-1"),"gbk");

                   System.out.println(uname2);

                   System.out.println("MyAjaxController.test1()");

                   List<User> list = new ArrayList<User>();

                   list.add(new User("高淇","123"));

                   list.add(new User("马士兵","456"));

                  

                   return list;

         }

        

}

 

 

5.       測试。

a)         启动server。

输入:http://localhost:8080/springmvc03/a.jsp

 

Spring中的拦截器

定义spring拦截器两种基本方式

1.       实现接口:org.springframework.web.servlet.HandlerInterceptor

接口中有例如以下方法须要重写:

注意:參数中的Object handler是下一个拦截器。

a)         publicboolean preHandle
(HttpServletRequest request,HttpServletResponse response,
Object handler)
throws Exception

该方法在action运行前运行,能够实现对数据的预处理,比方:编码、安全控制等。

假设方法返回true。则继续运行action

b)         publicvoid postHandle
(HttpServletRequest request,HttpServletResponse response,
Object handler,  
ModelAndView modelAndView) throws Exception

该方法在action运行后,生成视图前运行。

在这里,我们有机会改动视图层数据。

c)         publicvoid afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)   throws Exception

最后运行,通经常使用于释放资源,处理异常。

我们能够依据ex是否为空。来进行相关的异常处理。由于我们在平时处理异常时,都是从底层向上抛出异常。最后到了spring框架从而到了这种方法中。

2.       继承适配器:
org.springframework.web.servlet.handler.HandlerInterceptorAdapter

这个适配器实现了HandlerInterceptor接口。提供了这个接口中全部方法的空实现。

 

例如以下我们写出两个拦截器的演示样例代码,仅供大家參考:

package com.sxt.interceptor;

 

importjavax.interceptor.Interceptors;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

 

 

publicclass MyInterceptorimplements HandlerInterceptor {

 

    @Override

    publicvoid afterCompletion(HttpServletRequest request,   HttpServletResponse response, Object handler, Exception ex)    throws Exception {

       System.out.println("最后运行。!!一般用于释放资源!

");

      

    }

 

    @Override

    publicvoid postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,   ModelAndView modelAndView) throws Exception {

       System.out.println("Action运行之后,生成视图之前运行。!

");

    }

 

    @Override

    publicboolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler)throws Exception {

       System.out.println("action之前运行!!。");

       returntrue//继续运行action

    }

 

}

 

package com.sxt.interceptor;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

 

 

publicclass MyInterceptor2extends HandlerInterceptorAdapter {

 

    @Override

    publicboolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler)throws Exception {

       System.out.println("MyInterceptor2.preHandle()");

       returntrue//继续运行action

    }

}

 

3.       XML中怎样配置。

例如以下为演示样例代码:

   <mvc:interceptors>

       <beanclass="com.sxt.interceptor.MyInterceptor"></bean><!--拦截全部springmvcurl -->

       <mvc:interceptor>

           <mvc:mappingpath="/user.do"/>

           <!--<mvc:mapping path="/test/*" />-->

           <beanclass="com.sxt.interceptor.MyInterceptor2"></bean>

       </mvc:interceptor>

    </mvc:interceptors>

 

posted @ 2017-06-05 13:07  cxchanpin  阅读(178)  评论(0编辑  收藏  举报