springMVC学习笔记--上传图片、JSON转对象、校验、全局异常、拦截器

 

一:srping的介绍

1.spring的体系结构


2.spring资源

a、spring-framework-3.2.0.RELEASESpring Framework的官方发行包


b、spring-framework-3.0.2.RELEASE-dependencies:依赖的第三方jar包

二:如何搭建spring的核心开发环境

1.导入spring核心开发的jar包


位置: spring-framework-3.2.0.RELEASE\libs

jar包


2.导入核心依赖的jar包(日志输出),可以使用 commons-loggingLog4J
a、jar包位置:

spring-framework-3.0.2.RELEASE-dependencies\org.apache.commons\com.springsource.org.apache.commons.logging\1.1.1

b、jar包


3.配置spring核心配置文件

三:spring中的IOC(控制反转)

1.入门程序
a、创建java工程,导入jar包

b、编写dao,service
dao
[java]  view plain  copy
  1. package com.spring.ioc;  
  2.   
  3. public interface IocDao {  
  4.   
  5.     public void save();  
  6. }  

[java]  view plain  copy
  1. package com.spring.ioc;  
  2.   
  3. public class IocDaoImpl implements IocDao {  
  4.   
  5.     public void save() {  
  6.         System.out.println("save...");  
  7.     }  
  8.   
  9. }  

service
[java]  view plain  copy
  1. package com.spring.ioc;  
  2.   
  3. public interface IocService {  
  4.   
  5.     public void save();  
  6. }  

[java]  view plain  copy
  1. package com.spring.ioc;  
  2.   
  3. public class IocServiceImpl implements IocService {  
  4.   
  5.     private IocDao iocDao;  
  6.   
  7.     public void setIocDao(IocDao iocDao) {  
  8.         this.iocDao = iocDao;  
  9.     }  
  10.   
  11.     public void save() {  
  12.         iocDao.save();  
  13.     }  
  14.   
  15. }  
c、编写配置文件
[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="  
  5.         http://www.springframework.org/schema/beans   
  6.         http://www.springframework.org/schema/beans/spring-beans.xsd">  
  7.   
  8.     <!-- 让spring容器实例化并管理bena  
  9.         以下的操作相当于:  IocDao iocDao = new IocDaoImpl();  
  10.      -->  
  11.      <bean id="iocDao" class="com.spring.ioc.IocDaoImpl"></bean>  
  12.      <bean id="iocService" class="com.spring.ioc.IocServiceImpl">  
  13.         <!-- 调用setter方法注入需要的资源 -->  
  14.         <property name="iocDao" ref="iocDao"></property>  
  15.      </bean>  
  16. </beans>  
d、spring容器的初始化和资源的获取
[java]  view plain  copy
  1. package com.spring.ioc;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class IocDemo {  
  7.   
  8.     public static void main(String[] args) {  
  9.         //spring容器的初始化,参数为核心配置文件相对路径  
  10.         ApplicationContext ac = new ClassPathXmlApplicationContext("com/spring/ioc/bean.xml");  
  11.           
  12.         //获取资源,参数为核心配置文件中<bean>标签id属性值  
  13.         IocService iocService = (IocService)ac.getBean("iocService");  
  14.           
  15.         iocService.save();  
  16.     }  
  17. }  

四:springAPI的体系结构

1.体系结构图
2.分析
a、两个实现类
FileSystemXmlApplicationContext :用于加载本地磁盘上的配置文件
ClassPathXmlApplicationContext :用于加载在classpath下的配置文件
b、BeanFactory和ApplicationContext的区别
ApplicationContext不仅仅实现了BeanFactory,还实现了很多其他的接口,功能较为强大,且ApplicationContext的getBean()方法是在加载配置文件的时候就创建对象,是立即加载。
BeanFactory延时实例化Bean,用到的时候才创建对象


一:springmvc+spring+mybatis整合

1.创建动态web项目,导入jar包


2.在web.xml中配置spring监听器以及springmvc核心控制器

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     id="WebApp_ID" version="2.5">  
  6.     <display-name>ssm-Demo</display-name>  
  7.     <welcome-file-list>  
  8.         <welcome-file>index.html</welcome-file>  
  9.         <welcome-file>index.htm</welcome-file>  
  10.         <welcome-file>index.jsp</welcome-file>  
  11.         <welcome-file>default.html</welcome-file>  
  12.         <welcome-file>default.htm</welcome-file>  
  13.         <welcome-file>default.jsp</welcome-file>  
  14.     </welcome-file-list>  
  15.   
  16.     <!-- 初始化spring容器,配置spring核心配置文件位置 -->  
  17.     <context-param>  
  18.         <param-name>contextConfigLocation</param-name>  
  19.         <param-value>classpath:application-context.xml</param-value>  
  20.     </context-param>  
  21.     <listener>  
  22.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  23.     </listener>  
  24.       
  25.     <!-- 解决POST提交中文时的乱码问题 -->  
  26.     <filter>  
  27.         <filter-name>characterEncoding</filter-name>  
  28.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  29.         <init-param>  
  30.             <param-name>encoding</param-name>  
  31.             <param-value>UTF-8</param-value>  
  32.         </init-param>  
  33.     </filter>  
  34.     <filter-mapping>  
  35.         <filter-name>characterEncoding</filter-name>  
  36.         <url-pattern>*.do</url-pattern>  
  37.     </filter-mapping>  
  38.       
  39.     <!-- 配置springmvc核心控制器 -->  
  40.     <servlet>  
  41.         <servlet-name>springmvc</servlet-name>  
  42.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  43.         <init-param>  
  44.             <param-name>contextConfigLocation</param-name>  
  45.             <param-value>classpath:springmvc-config.xml</param-value>  
  46.         </init-param>  
  47.         <!-- 配置使读取配置文件时实例化springmvc -->  
  48.         <load-on-startup>1</load-on-startup>  
  49.     </servlet>  
  50.     <servlet-mapping>  
  51.         <servlet-name>springmvc</servlet-name>  
  52.         <url-pattern>*.do</url-pattern>  
  53.     </servlet-mapping>  
  54.       
  55. </web-app>  


3.创建包,配置其他配置文件


a、配置mybatis核心配置文件 -- mybatis-config.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration  
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  5. <configuration>  
  6.     <!-- 配置包下自动别名 -->  
  7.     <typeAliases>  
  8.         <package name="com.ssm.pojo"/>  
  9.     </typeAliases>  
  10.       
  11. </configuration>  

b、配置springmvc核心配置文件 -- springmvc-config.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"    
  4.     xmlns:context="http://www.springframework.org/schema/context"    
  5.     xmlns:aop="http://www.springframework.org/schema/aop"     
  6.     xmlns:tx="http://www.springframework.org/schema/tx"    
  7.     xmlns:task="http://www.springframework.org/schema/task"    
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans     
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
  10.         http://www.springframework.org/schema/mvc     
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd     
  12.         http://www.springframework.org/schema/context     
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd     
  14.         http://www.springframework.org/schema/aop     
  15.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd     
  16.         http://www.springframework.org/schema/tx     
  17.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
  18.         http://www.springframework.org/schema/task    
  19.         http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  20.   
  21.     <!-- 配置开启扫描注解 -->  
  22.     <context:component-scan base-package="com.ssm" use-default-filters="false">  
  23.         <!-- springmvc的配置文件,因此,配置为只扫描Controller中的注解 -->  
  24.         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  25.     </context:component-scan>  
  26.   
  27.     <!-- 配置处理器映射器,处理器适配器,  
  28.         使用该配置可以替代处理器适配器、处理器映射器的配置 -->  
  29.     <mvc:annotation-driven/>  
  30.       
  31.     <!-- 配置处理器映射器,当使用上面的mvc标签时,可以不用配置处理器映射器和处理器适配器   
  32.     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>  
  33.         -->  
  34.     <!-- 配置处理器适配器   
  35.     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>  
  36.         -->  
  37.       
  38.     <!-- 配置视图解析器 -->  
  39.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  40.         <!-- 前缀 -->  
  41.         <property name="prefix" value="/WEB-INF/jsp/items" />  
  42.         <!-- 后缀 -->  
  43.         <property name="suffix" value=".jsp" />  
  44.     </bean>  
  45. </beans>  

c、配置spring核心配置文件 -- application-context.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"   
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xmlns:task="http://www.springframework.org/schema/task"  
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10.         http://www.springframework.org/schema/mvc   
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.         http://www.springframework.org/schema/aop   
  15.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  16.         http://www.springframework.org/schema/tx   
  17.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  18.         http://www.springframework.org/schema/task  
  19.         http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  20.   
  21.     <!-- 导入所有配置文件 -->  
  22.     <import resource="config/*.xml"/>  
  23. </beans>  
d、配置数据库连接属性 -- jdbc.properties

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. driverClass=com.mysql.jdbc.Driver  
  2. jdbcUrl=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8  
  3. user=root  
  4. password=root  
e、配置数据源、事务、注解、读取properties文件、mybatis工厂等
(1)、jdbc.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"   
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xmlns:task="http://www.springframework.org/schema/task"  
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10.         http://www.springframework.org/schema/mvc   
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.         http://www.springframework.org/schema/aop   
  15.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  16.         http://www.springframework.org/schema/tx   
  17.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  18.         http://www.springframework.org/schema/task  
  19.         http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  20.       
  21.     <!-- 配置数据源 -->  
  22.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
  23.         <property name="driverClass" value="${driverClass}"/>  
  24.         <property name="jdbcUrl" value="${jdbcUrl}"/>  
  25.         <property name="user" value="${user}"/>  
  26.         <property name="password" value="${password}"/>  
  27.     </bean>  
  28.       
  29.       
  30.       
  31. </beans>  
(2)、transaction.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"   
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xmlns:task="http://www.springframework.org/schema/task"  
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10.         http://www.springframework.org/schema/mvc   
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.         http://www.springframework.org/schema/aop   
  15.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  16.         http://www.springframework.org/schema/tx   
  17.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  18.         http://www.springframework.org/schema/task  
  19.         http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  20.   
  21.     <!-- 配置数据源的事务,事务管理类 -->  
  22.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  23.         <!-- 注入数据源 -->  
  24.         <property name="dataSource" ref="dataSource"/>  
  25.     </bean>  
  26.       
  27.     <!-- 开启扫描事务的注解 -->  
  28.     <tx:annotation-driven transaction-manager="transactionManager"/>    
  29.       
  30. </beans>  
(3)、anontation.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"   
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xmlns:task="http://www.springframework.org/schema/task"  
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10.         http://www.springframework.org/schema/mvc   
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.         http://www.springframework.org/schema/aop   
  15.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  16.         http://www.springframework.org/schema/tx   
  17.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  18.         http://www.springframework.org/schema/task  
  19.         http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  20.   
  21.     <!-- 配置开启扫描spring注解 -->  
  22.     <context:component-scan base-package="com.ssm">  
  23.         <!-- 选择过滤的注解,即 @Controller -->  
  24.         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  25.     </context:component-scan>  
  26. </beans>  
(4)、mybatis.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"   
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xmlns:task="http://www.springframework.org/schema/task"  
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10.         http://www.springframework.org/schema/mvc   
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.         http://www.springframework.org/schema/aop   
  15.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  16.         http://www.springframework.org/schema/tx   
  17.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  18.         http://www.springframework.org/schema/task  
  19.         http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  20.       
  21.     <!-- 配置sqlSessionFactory工厂 -->  
  22.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  23.         <!-- 注入数据源 -->  
  24.         <property name="dataSource" ref="dataSource"/>  
  25.         <!-- 配置mybatis核心配置文件位置 -->  
  26.         <property name="configLocation" value="classpath:mybatis-config.xml"/>  
  27.     </bean>  
  28.       
  29.     <!-- 配置扫描mapper的基本包 -->  
  30.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  31.         <property name="basePackage" value="com.ssm.dao"/>  
  32.     </bean>  
  33.   
  34. </beans>  
(5)、properties.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"   
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xmlns:task="http://www.springframework.org/schema/task"  
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10.         http://www.springframework.org/schema/mvc   
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.         http://www.springframework.org/schema/aop   
  15.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  16.         http://www.springframework.org/schema/tx   
  17.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  18.         http://www.springframework.org/schema/task  
  19.         http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  20.   
  21.     <!-- 配置读取properties配置文件 -->  
  22.     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  23.         <property name="locations">  
  24.             <list>  
  25.                 <value>classpath:jdbc.properties</value>  
  26.             </list>  
  27.         </property>  
  28.     </bean>  
  29.   
  30. </beans>  


一:参数绑定

1.基础类型的参数绑定
要求:
页面上字段的name属性的值要和方法中参数的名称相同
@RequestParam标签的使用

当页面传递的字段name值和controller中方法中的参数名称不相同时,使用@RequestParam将页面上的字段值绑定到方法中的参数上,但是使用该注解时要求参数一定有值,如果想让其没有值时也可以,需加上:required=false,此时也可以设置传递的值为null时的默认值,使用defaultValue属性

[java]  view plain  copy
  1. @RequestMapping(value="editItems.do")  
  2. //@RequestParam注解将页面上name值为 pid 的字段的值绑定到id参数上  
  3. public String edit(@RequestParam(value="pid",required=false,defaultValue="1") Integer id){  
  4.     return "toEdit";  
  5. }  
2.Boolean类型的参数绑定

后台传递 0 或者 false  则自动转为 false

后台传递 1 或者  true  则自动转为 true

3.参数类型为包装类

如果参数类型为包装类,即类A中有另一个类B为该类A的属性,则在页面中传递值时的写法为name="B.属性"

例如:

POJO

[java]  view plain  copy
  1. public class QueryVo {  
  2.   
  3.     private User user;  
  4.       
  5.     private Boolean isDel;  
  6.       
  7.     private Items items;  
Controller

[java]  view plain  copy
  1. @RequestMapping(value="/items/toEdit.do")  
  2. public String toEdit(QueryVo vo, Model model){  
  3.     return "toEdit";  
  4. }  

jsp页面

[html]  view plain  copy
  1. <tr>  
  2.                     <td width="20%" class="pn-flabel pn-flabel-h">  
  3.                         商品生产日期:</td><td width="80%" class="pn-fcontent">  
  4.                         <input type="text" class="required" name="items.createtime"   
  5.                         value="<fmt:formatDate value="${items.createtime }" pattern="yyyy-MM-dd HH:mm:ss"/>maxlength="80"/>  
  6.                     </td>  
  7.                 </tr>  
  8.                 <tr>  
  9.                     <td width="20%" class="pn-flabel pn-flabel-h">  
  10.                         商品描述:</td><td width="80%" class="pn-fcontent">  
  11.                         <input type="text" class="required" name="items.detail" maxlength="80" value="${items.detail }"  size="60"/>  
  12.                     </td>  
  13.                 </tr>  
  14.                 <tr>  
  15.                     <td width="20%" class="pn-flabel pn-flabel-h">  
  16.                         是否可用:</td><td width="80%" class="pn-fcontent">  
  17.                         <input type="text" class="required" name="isDel" maxlength="80" size="60"/>  
  18.                     </td>  
  19.                 </tr>  

4.参数类型为集合时
参数为list时不能直接放在controller方法中的参数上,而时应该放在包装类中进行接收

a、参数为Map

POJO

[java]  view plain  copy
  1. public class QueryVo {  
  2.   
  3.       
  4.     private Map<String , String> map;  
JSP

[html]  view plain  copy
  1. <tr>  
  2.     <td width="20%" class="pn-flabel pn-flabel-h">  
  3.          数组:</td><td width="80%" class="pn-fcontent">  
  4.         <input type="text" class="required" name="map['color']" maxlength="80" size="60"/>  
  5.         <input type="text" class="required" name="map['size']" maxlength="80" size="60"/>  
  6.     </td>  
  7. </tr>  

b、参数为List,泛型为String

POJO

[java]  view plain  copy
  1. public class QueryVo {  
  2.   
  3.       
  4.     private List<String> list;  
  5.       

JSP

[html]  view plain  copy
  1. <tr>  
  2.     <td width="20%" class="pn-flabel pn-flabel-h">  
  3.          list:</td><td width="80%" class="pn-fcontent">  
  4.         <input type="text" class="required" name="list" maxlength="80" size="60"/>  
  5.         <input type="text" class="required" name="list" maxlength="80" size="60"/>  
  6.     </td>  
  7. </tr>  

c、参数为List,泛型为类

POJO

[java]  view plain  copy
  1. public class QueryVo {  
  2.   
  3.       
  4.     private List<User> users;  
  5.       

JSP

[html]  view plain  copy
  1. <tr>  
  2.     <td width="20%" class="pn-flabel pn-flabel-h">  
  3.          list==User1:</td><td width="80%" class="pn-fcontent">  
  4.         <input type="text" class="required" name="users[0].username" maxlength="80" size="60"/>  
  5.         <input type="text" class="required" name="users[0].address" maxlength="80" size="60"/>  
  6.     </td>  
  7. </tr>  
  8. <tr>  
  9.     <td width="20%" class="pn-flabel pn-flabel-h">  
  10.          list==User2:</td><td width="80%" class="pn-fcontent">  
  11.         <input type="text" class="required" name="users[1].username" maxlength="80" size="60"/>  
  12.         <input type="text" class="required" name="users[1].address" maxlength="80" size="60"/>  
  13.     </td>  
  14. </tr>  

d、参数类型为日期

由于日期类型的格式不确定,因此在进行参数绑定之前需要使用转换器对日期的格式进行转换

(1)、编写转换器类

[java]  view plain  copy
  1. package com.ssm.common.convertion;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. import org.springframework.core.convert.converter.Converter;  
  7.   
  8. /** 
  9.  * 自定义日期转换类,实现Converter接口 
  10.  * Converter<S, T>   其中:S 是页面传递的参数类型    T 是需要转换为的类型 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. public class DateConvertor implements Converter<String, Date> {  
  15.   
  16.     @Override  
  17.     public Date convert(String source) {  
  18.         try {  
  19.             if(source != null){  
  20.                 return new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").parse(source);  
  21.             }  
  22.         } catch (Exception e) {  
  23.             // TODO: handle exception  
  24.         }  
  25.         return null;  
  26.     }  
  27.   
  28. }  

(2)、在springmvc核心配置文件中添加转换器

[html]  view plain  copy
  1. <!-- 处理器映射器,处理器适配器   
  2.     使用该配置可以替代处理器适配器和处理器映射器的配置-->  
  3. <mvc:annotation-driven conversion-service="conversionService" />  
  4.   
  5. <!-- 配置自定义转换器 -->  
  6. <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">  
  7.     <property name="converters">  
  8.         <list>  
  9.             <bean class="com.ssm.common.convertion.DateConvertor"></bean>  
  10.         </list>  
  11.     </property>  
  12. </bean>  

e、接收的参数类型为数组

springmvc默认会将具有同名框的一组值使用",  "隔开,即使用逗号+空格进行分割放入数组中 





一:使用springmvc上传图片
1.导入文件上传需要的jar包

2.分析当上传图片时,选中图片以后点击"打开"按钮触发的事件是什么?

onchange事件

a、编写jsp页面中的上传图片框

[html]  view plain  copy
  1. <body>  
  2.     <div class="body-box" style="float: right">  
  3.         <form id="jvForm" action="edit.do" method="post">  
  4.             <tr>  
  5.                 <td width="20%" class="pn-flabel pn-flabel-h">  
  6.                     <span class="pn-frequired">*</span>   
  7.                     上传商品图片(90x150尺寸):  
  8.                 </td>  
  9.                 <td width="80%" class="pn-fcontent">注:该尺寸图片必须为90x150。  
  10.                 </td>  
  11.             </tr>  
  12.             <tr>  
  13.                 <td width="20%" class="pn-flabel pn-flabel-h">  
  14.                 </td>  
  15.                 <td width="80%" class="pn-fcontent">  
  16.                     <img width="100" height="100" id="allUrl" src="/res/img/pic/ppp.jpg" />   
  17.                     <input type="file" name="pic" onchange="uploadPic()" />  
  18.                 </td>  
  19.             </tr>  
  20.         </form>  
  21.     </div>  
  22. </body>  

b、引入jquery.js和jquery.form.js插件

[html]  view plain  copy
  1. <!-- 引入jquery.js和jquery.form.js插件 -->  
  2. <script src="${pageContext.request.contextPath}/res/common/js/jquery.js" type="text/javascript"></script>  
  3. <script src="${pageContext.request.contextPath}/res/common/js/jquery.form.js" type="text/javascript"></script>  

c、编写上传的function
[html]  view plain  copy
  1. <script type="text/javascript">  
  2.   
  3.      //上传图片  
  4.     function uploadPic(){  
  5.         var options = {  
  6.                 url : "${pageContext.request.contextPath}/upload/uploadPic.do",  
  7.                 type : "post",  
  8.                 dataType : "text",  
  9.                 success : function(data){  
  10.                     //图片的路径  
  11.                     $("#allUrl").attr("src", data);  
  12.                 }  
  13.         }  
  14.         //使用jquery.form.js插件模拟一个form进行提交  
  15.         $("#jvForm").ajaxSubmit(options);  
  16.     }   
  17. </script>  
d、JSP整体页面
[html]  view plain  copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>上传图片</title>  
  8. <link href="${pageContext.request.contextPath}/res/itcast/css/admin.css" rel="stylesheet" type="text/css"/>  
  9. <link href="${pageContext.request.contextPath}/res/common/css/theme.css" rel="stylesheet" type="text/css"/>  
  10. <link href="${pageContext.request.contextPath}/res/common/css/jquery.validate.css" rel="stylesheet" type="text/css"/>  
  11. <link href="${pageContext.request.contextPath}/res/common/css/jquery.treeview.css" rel="stylesheet" type="text/css"/>  
  12. <link href="${pageContext.request.contextPath}/res/common/css/jquery.ui.css" rel="stylesheet" type="text/css"/>  
  13.   
  14. <!-- 引入jquery.js和jquery.form.js插件 -->  
  15. <script src="${pageContext.request.contextPath}/res/common/js/jquery.js" type="text/javascript"></script>  
  16. <script src="${pageContext.request.contextPath}/res/common/js/jquery.form.js" type="text/javascript"></script>  
  17. <script type="text/javascript">  
  18.   
  19.      //上传图片  
  20.     function uploadPic(){  
  21.         var options = {  
  22.                 url : "${pageContext.request.contextPath}/upload/uploadPic.do",  
  23.                 type : "post",  
  24.                 dataType : "text",  
  25.                 success : function(data){  
  26.                     //图片的路径  
  27.                     $("#allUrl").attr("src", data);  
  28.                 }  
  29.         }  
  30.         //使用jquery.form.js插件模拟一个form进行提交  
  31.         $("#jvForm").ajaxSubmit(options);  
  32.     }   
  33. </script>  
  34. </head>  
  35. <body>  
  36.     <div class="body-box" style="float: right">  
  37.         <form id="jvForm" action="edit.do" method="post">  
  38.             <tr>  
  39.                 <td width="20%" class="pn-flabel pn-flabel-h">  
  40.                     <span class="pn-frequired">*</span>   
  41.                     上传商品图片(90x150尺寸):  
  42.                 </td>  
  43.                 <td width="80%" class="pn-fcontent">注:该尺寸图片必须为90x150。  
  44.                 </td>  
  45.             </tr>  
  46.             <tr>  
  47.                 <td width="20%" class="pn-flabel pn-flabel-h">  
  48.                 </td>  
  49.                 <td width="80%" class="pn-fcontent">  
  50.                     <img width="100" height="100" id="allUrl" src="/res/img/pic/ppp.jpg" />   
  51.                     <input type="file" name="pic" onchange="uploadPic()" />  
  52.                 </td>  
  53.             </tr>  
  54.         </form>  
  55.     </div>  
  56. </body>  
  57. </html>  
e、在springmvc的核心配置文件中配置上传图片

[html]  view plain  copy
  1. <!-- 配置上传图片  
  2.     id 的名称必须为 multipartResolver : 通过此名称才能找到MultiparFile接口的实现类  
  3.  -->  
  4. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  5.     <!-- 设置上传图片的大小  默认单位为 B -->  
  6.     <property name="maxUploadSize" value="1048576"/>  
  7. </bean>  

f、编写Controller类
[java]  view plain  copy
  1. package com.ssm.controller;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.text.DateFormat;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8. import java.util.Random;  
  9.   
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. import org.apache.commons.io.FilenameUtils;  
  14. import org.springframework.stereotype.Controller;  
  15. import org.springframework.web.bind.annotation.RequestMapping;  
  16. import org.springframework.web.bind.annotation.RequestParam;  
  17. import org.springframework.web.multipart.MultipartFile;  
  18.   
  19. /** 
  20.  * 上传图片的Controller 
  21.  * @author Administrator 
  22.  * 
  23.  */  
  24. @Controller  
  25. @RequestMapping(value = "/upload")  
  26. public class UploadController {  
  27.   
  28.     //跳转到上传图片页面  
  29.     @RequestMapping(value="/upload.do")  
  30.     public String up(){  
  31.         return "upload";  
  32.     }  
  33.       
  34.     //上传图片  
  35.     @RequestMapping(value = "/uploadPic.do")  
  36.     public void uploadPid(@RequestParam(required = false) MultipartFile pic, HttpServletRequest request  
  37.             ,HttpServletResponse response) throws Exception{  
  38.         System.out.println(pic.getOriginalFilename());  
  39.         //图片名称生成策略:精确到毫秒+3位随机数  
  40.         //生成时间  
  41.         DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");  
  42.         String name = df.format(new Date());  
  43.         //生成三位随机数  
  44.         Random r = new Random();  
  45.         for (int i = 0; i < 3; i ++) {  
  46.             int a = r.nextInt(10);//生成10以内的随机数  
  47.             name += a;  
  48.         }  
  49.         //获取文件扩展名  
  50.         String extName = FilenameUtils.getExtension(pic.getOriginalFilename());  
  51.         //获取项目路径  
  52.         String url = request.getSession().getServletContext().getRealPath("/");  
  53.         //图片的相对与项目的路径  
  54.         String path = "/upload/" + name + "." + extName;  
  55.         //执行保存图片的方法,后面是文件夹  
  56.         pic.transferTo(new File(url + path));  
  57.         //图片显示的路径,需要在页面上图片的src属性使用  
  58.         String p = request.getContextPath() + path;  
  59.         response.setContentType("application/json;charset=UTF-8");  
  60.         response.getWriter().write(p);  
  61.           
  62.     }  
  63. }  

二:JSON和对象之间的相互转化

1.导入json支持包

注意:
当在springmvc核心配置文件中使用<mvc:annotation-driven/>标签替代处理器映射器和处理器适配器时就不需要再配置json支持,否则还需要在导入jar包后进行配置
2. 编写jsp页面中的JavaScript,发送ajax数据,接收返回数据并显示
[javascript]  view plain  copy
  1. <script type="text/javascript">  
  2.     //页面加载完成后执行的函数  
  3.     $(function(){  
  4.         var url = "${pageContext.request.contextPath}/json/text.do"  
  5.         var params = '{"username":"熊大","address":"森林"}';  
  6.         //post提交ajax  
  7.         $.ajax({  
  8.             url : url,  
  9.             type : "post",//提交方式  
  10.             contentType : "application/json;charset=UTF-8",//设置发送的数据类型为json格式,ajax默认发送key:value格式的数据  
  11.             dataType : "json",//设置接收的数据类型为json格式  
  12.             data : params,  
  13.             success : function(data){  
  14.                 alert(data.sex);  
  15.             }  
  16.               
  17.         });  
  18.     });  

3.编写Controller层代码
[java]  view plain  copy
  1. package com.ssm.controller;  
  2.   
  3. import org.springframework.stereotype.Controller;  
  4. import org.springframework.web.bind.annotation.RequestBody;  
  5. import org.springframework.web.bind.annotation.RequestMapping;  
  6. import org.springframework.web.bind.annotation.ResponseBody;  
  7.   
  8. import com.ssm.pojo.User;  
  9.   
  10. /** 
  11.  * JSON和对象的相互转化 
  12.  * @author Administrator 
  13.  * 
  14.  */  
  15. @Controller  
  16. @RequestMapping(value = "/json")  
  17. public class JsonController {  
  18.   
  19.     /** 
  20.      * JSON与对象的相互转化需要用到两个标签 
  21.      * @RequestBody     将传入的JSON格式的字符串转化为对象 
  22.      * @ResponseBody    将传出的对象转化为JSON格式的字符串 
  23.      */  
  24.     @RequestMapping(value = "/text.do")  
  25.     public @ResponseBody User //将User转换成JSON字符串并传递到jsp页面  
  26.         jsonToObject(@RequestBody User user){//将页面传递的json字符串自动对应User中的属性封装到User中  
  27.           
  28.         System.out.println(user);  
  29.           
  30.         user.setSex("雄");  
  31.         return user;  
  32.     }  
  33. }  

4.控制台打印数据

5.jsp页面弹出数据

三:springmvc的校验

1.导入jar包

springmvc校验使用的是Hibernate的校验方式,因此需要导入hibernate的校验支持包


2.在springmvc核心配置文件中配置校验器
[html]  view plain  copy
  1. <!-- 处理器映射器,处理器适配器   
  2.     使用该配置可以替代处理器适配器和处理器映射器的配置-->  
  3. <mvc:annotation-driven validator="validator" />  
  4.   
  5. <!-- 配置校验器 -->  
  6. <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">  
  7.     <!-- 使用hibernate的校验器 -->  
  8.     <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>  
  9.     <!-- 指定校验结果的中文存放的properties文件位置 -->  
  10.     <property name="validationMessageSource" ref="messageSource"/>  
  11. </bean>  
  12.   
  13. <!-- 校验错误信息的配置文件 -->  
  14. <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
  15.     <!-- 资源文件名 -->  
  16.     <property name="basenames">  
  17.         <list>  
  18.             <!-- 存放中文校验结果的properties文件 -->  
  19.             <value>classpath:message</value>  
  20.         </list>  
  21.     </property>  
  22.     <!-- 资源文件的编码格式 -->  
  23.     <property name="fileEncodings" value="utf-8" />  
  24.     <!-- 对资源文件内容的缓存时间,单位是 s -->  
  25.     <property name="cacheSeconds" value="120"/>  
  26. </bean>  

3.在需要校验的类的属性字段上添加校验条件 -- 此处以商品为例 Items

[java]  view plain  copy
  1. public class Items {  
  2.     private Integer id;  
  3.   
  4.     @Size(min=1,max=5,message="{itemsNameSize}")//设置最小长度,最大长度以及错误提示  
  5.     @NotNull(message="{itemsName}")  
  6.     private String name;  
  7.   
  8.     private Float price;  
  9.   
  10.     private String pic;  

4.编写properties文件存放错误信息

5.在controller层需要校验参数的前面加上@Validated注解,并且绑定结果
[java]  view plain  copy
  1. @RequestMapping(value="/items/edit.do")  
  2. public String toEdit(@Validated Items items,BindingResult result, Model model){//设置给Items进行校验,并且绑定结果  
  3.     //获取错误集  
  4.     List<ObjectError> allErrors = result.getAllErrors();  
  5.     for (ObjectError objectError : allErrors) {  
  6.         System.out.println(objectError.getDefaultMessage());  
  7.     }  
  8.       
  9.     return "redirect:/items/list.do";  
  10. }  


四:全局异常处理

1.在springmvc核心配置文件中自定义异常处理类

[html]  view plain  copy
  1. <!-- 自定义全局异常处理类 -->  
  2. <bean class="com.ssm.common.exception.GlobalException"></bean>  

2.编写自定义异常处理类

[java]  view plain  copy
  1. package com.ssm.common.exception;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.springframework.web.servlet.HandlerExceptionResolver;  
  7. import org.springframework.web.servlet.ModelAndView;  
  8.   
  9. /** 
  10.  * 自定义全局异常处理类 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. public class GlobalException implements HandlerExceptionResolver {  
  15.   
  16.     @Override  
  17.     public ModelAndView resolveException(HttpServletRequest request,  
  18.             HttpServletResponse response, Object obj, Exception exception) {  
  19.         ModelAndView modelAndView = new ModelAndView();  
  20.         modelAndView.addObject("error","异常");  
  21.         //设置错误跳转页面位置  
  22.         modelAndView.setViewName("error/error");  
  23.         return modelAndView;  
  24.     }  
  25.   
  26. }  

3.在controller方法中必须要有异常throws

[java]  view plain  copy
  1. @RequestMapping(value="items.do")  
  2. public String listItems(Model model) throws Exception {  
  3.     int i = 1 / 0;  
  4.     List<Items> list = itemService.list();  
  5.     model.addAttribute("list", list);  
  6.     return "list";  
  7. }  

五:拦截器的使用

1.首先说明:配置多个拦截器时拦截器的执行顺序

preHandle按拦截器定义顺序调用   1    2

postHandler按拦截器定义逆序调用  2  1

afterCompletion按拦截器定义逆序调用 2   1

 

postHandler在拦截器链内所有拦截器返成功调用

afterCompletion只有preHandle返回true才调用

2.编写自定义拦截器的类

[java]  view plain  copy
  1. package com.ssm.common.interceptor;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.springframework.web.servlet.HandlerInterceptor;  
  7. import org.springframework.web.servlet.ModelAndView;  
  8.   
  9. /** 
  10.  * 自定义拦截器类 
  11.  *  
  12.  * @author Administrator 
  13.  * 
  14.  */  
  15. public class CustomInterceptor implements HandlerInterceptor {  
  16.   
  17.     /** 
  18.      * 页面渲染之后执行的方法 
  19.      */  
  20.     @Override  
  21.     public void afterCompletion(HttpServletRequest arg0,  
  22.             HttpServletResponse arg1, Object arg2, Exception arg3)  
  23.             throws Exception {  
  24.         // TODO Auto-generated method stub  
  25.   
  26.     }  
  27.   
  28.     /** 
  29.      * 执行handler之后的方法 
  30.      */  
  31.     @Override  
  32.     public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,  
  33.             Object arg2, ModelAndView arg3) throws Exception {  
  34.   
  35.     }  
  36.   
  37.     /** 
  38.      * 执行Handler之前执行的方法 
  39.      */  
  40.     @Override  
  41.     public boolean preHandle(HttpServletRequest request,  
  42.             HttpServletResponse response, Object obj) throws Exception {  
  43.         // 设置路径为 /login.do的不拦截  
  44.         String uri = request.getRequestURI();  
  45.         if(uri.indexOf("login") != -1){  
  46.             return true;  
  47.         }else{  
  48.             //判断用户是否登录  
  49.             Object obje = request.getSession().getAttribute("USER_NAME");  
  50.             if(obje != null){  
  51.                 return true;  
  52.             }else{  
  53.                 //重定向到登录页面  
  54.                 response.sendRedirect(request.getContextPath() + "/login.do");  
  55.                 return false;  
  56.             }  
  57.         }  
  58.     }  
  59.   
  60. }  

3.在springmvc核心配置文件中配置拦截器

[html]  view plain  copy
  1. <!-- 配置springmvc拦截器 -->  
  2. <mvc:interceptors>  
  3.     <!-- 可配置多个拦截器 -->  
  4.     <mvc:interceptor>  
  5.         <!-- 配置当前拦截器的拦截规则   /*/** 表示拦截WEB-INF下的所有文件下的所有扩展名的文件 -->  
  6.         <mvc:mapping path="/*/**"/>  
  7.         <!-- 执行拦截方法的类 -->  
  8.         <bean class="com.ssm.common.interceptor.CustomInterceptor"></bean>  
  9.     </mvc:interceptor>  
  10. </mvc:interceptors>  

4.编写登录的Controller层代码

[java]  view plain  copy
  1. package com.ssm.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8.   
  9. /** 
  10.  * 登录控制层 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. @Controller  
  15. public class LoginController {  
  16.   
  17.     //去登录页面  
  18.     @RequestMapping(value = "/login.do", method = RequestMethod.GET)  
  19.     public String toLogin(){  
  20.         return "login";  
  21.     }  
  22.       
  23.     //提交登录的方法  
  24.     @RequestMapping(value = "/login.do", method = RequestMethod.POST)  
  25.     public String login(HttpServletRequest request){  
  26.         request.getSession().setAttribute("USER_NAME""已登录");  
  27.           
  28.         return "redirect:/items.do";  
  29.     }  
  30. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值