SpringMVC ,Spring Security,Hibernate4,Freemarker 整合笔记

来源:互联网 发布:ios蜂窝移动数据开关 编辑:程序博客网 时间:2024/06/05 17:27

我用的是Maven控制jar包,在此先上配置,里边涵盖了项目所有的包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.bdcbus</groupId><artifactId>bdcbus</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>bdcbus Maven Webapp</name><url>http://maven.apache.org</url><dependencies><!-- test --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><dependency><groupId>org.hamcrest</groupId><artifactId>hamcrest-all</artifactId><version>1.3</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>3.1.2.RELEASE</version><scope>test</scope></dependency><!-- http --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.2.1</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.1</version><classifier>jdk15</classifier></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.1.32</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.4</version><scope>provided</scope></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.2.1</version><scope>test</scope></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.2.5</version></dependency><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency><!--commons --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dependency><dependency><groupId>commons-beanutils</groupId><artifactId>commons-beanutils</artifactId><version>1.8.3</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>3.2.1</version></dependency><dependency><groupId>commons-validator</groupId><artifactId>commons-validator</artifactId><version>1.4.0</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.0</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1.3</version></dependency><!-- logger --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.6.6</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.6.6</version></dependency><!--hibernate --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>4.1.7.Final</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-ehcache</artifactId><version>4.1.7.Final</version></dependency><dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache-core</artifactId><version>2.6.0</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-proxool</artifactId><version>4.1.7.Final</version></dependency><dependency><groupId>proxool</groupId><artifactId>proxool</artifactId><version>0.9.1</version></dependency><dependency><groupId>proxool</groupId><artifactId>proxool-cglib</artifactId><version>0.9.1</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>4.3.0.Final</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator-annotation-processor</artifactId><version>4.3.0.Final</version></dependency><dependency><groupId>net.sf.ezmorph</groupId><artifactId>ezmorph</artifactId><version>1.0.6</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.22</version></dependency><!--spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.0.0.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>4.0.0.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>3.1.2.RELEASE</version></dependency><dependency><groupId>aopalliance</groupId><artifactId>aopalliance</artifactId><version>1.0</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.7.0</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.7.0</version></dependency><dependency><groupId>cglib</groupId><artifactId>cglib-nodep</artifactId><version>2.2.2</version></dependency><dependency><groupId>com.fasterxml</groupId><artifactId>classmate</artifactId><version>0.8.0</version></dependency><dependency><groupId>quartz</groupId><artifactId>quartz</artifactId><version>1.5.2</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>3.1.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>3.1.2.RELEASE</version></dependency><!-- spring mvc --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.2.6.RELEASE</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3</version></dependency><!-- spring security --><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-core</artifactId><version>3.1.4.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId><version>3.1.2.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>3.1.4.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-ldap</artifactId><version>3.1.4.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-acl</artifactId><version>3.1.4.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-openid</artifactId><version>3.1.2.RELEASE</version></dependency><!-- freemarker --><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.20</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>3.2.4.RELEASE</version></dependency></dependencies><build><finalName>bdcbus</finalName></build></project>

第一步,配置Web.xml

首先说明一下,web.xml 的加载顺序:

ServletContext -> context-param -> listener -> filter -> servlet ,而同个类型之间的实际程序调用的时候的顺序是根据对应的 mapping 的顺序进行调用的。

注意:opensessionView尽量关闭,对于放在公网上的网站来讲,会影响网站性能,解决LAZY方法:尽量在service层输出完整对象。

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><welcome-file-list><welcome-file>/index.jsp</welcome-file></welcome-file-list><session-config><!-- 在用户最近访问HttpSession对象180分钟后,HttpSession对象默认为无效: --><session-timeout>180</session-timeout></session-config><!--配置spring --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring.xmlclasspath:spring-security.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 配置springmvc --><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 配置SpringSecurity --><filter><filter-name>springSecurityFilterChain</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping><filter-name>springSecurityFilterChain</filter-name><url-pattern>/</url-pattern></filter-mapping></web-app>

第二步,配置spring.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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd       "><!-- 扫描注解Bean --><context:component-scan base-package="com.bdcbus"><!-- 将Controller的注解排除掉,Controller由springmvc配置进行注解 --><context:exclude-filter type="annotation"expression="org.springframework.stereotype.Controller" /></context:component-scan><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><!-- 从配置文件中读取,记得在目录下添加 resources.properties --><value>classpath:resources.properties</value></list></property></bean><bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"><property name="alias" value="proxoolDataSource" /><property name="driver" value="${connection.driver_class}" /><property name="driverUrl" value="${connection.url}" /><property name="user" value="${connection.username}" /><property name="password" value="${connection.password}" /><property name="maximumConnectionCount" value="${proxool.maximum.connection.count}" /><property name="minimumConnectionCount" value="${proxool.minimum.connection.count}" /><property name="statistics" value="${proxool.statistics}" /><property name="simultaneousBuildThrottle" value="${proxool.simultaneous.build.throttle}" /></bean><bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="packagesToScan"><list><value>com.bdcbus</value></list></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">${hibernate.dialect}</prop><prop key="hibernate.show_sql">${hibernate.show_sql}</prop><prop key="hibernate.format_sql">true</prop><prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop><prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop><prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop><prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop><prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop><prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop><prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop><prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop><prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop><prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</prop><prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}</prop></props></property></bean><bean id="beanFetcher" class="com.bdcbus.util.BeanFetcher"><!--这里不需要对beanFactory进行注入,因为类BeanFactoryHelper实现了BeanFactoryAware, 所以只要BeanFactoryHelper归spring管理,就会自动注入BeanFactory --></bean><!-- 开启AOP监听 只对当前配置文件有效 --><aop:aspectj-autoproxy expose-proxy="true" /><!-- 开启注解事务 只对当前配置文件有效 --><tx:annotation-driven transaction-manager="txManager" /><bean id="txManager"class="org.springframework.orm.hibernate4.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="add*" propagation="REQUIRED" /><tx:method name="create*" propagation="REQUIRED" /><tx:method name="insert*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="merge*" propagation="REQUIRED" /><tx:method name="del*" propagation="REQUIRED" /><tx:method name="remove*" propagation="REQUIRED" /><tx:method name="put*" propagation="REQUIRED" /><tx:method name="use*" propagation="REQUIRED" /><tx:method name="change*" propagation="REQUIRED" /><!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --><tx:method name="query*" propagation="REQUIRED" read-only="true" /><tx:method name="post*" propagation="REQUIRED" read-only="false" /><tx:method name="get*" propagation="REQUIRED" read-only="true" /><tx:method name="count*" propagation="REQUIRED" read-only="true" /><tx:method name="find*" propagation="REQUIRED" read-only="true" /><tx:method name="list*" propagation="REQUIRED" read-only="true" /><tx:method name="*" propagation="REQUIRED" read-only="true" /></tx:attributes></tx:advice><aop:config expose-proxy="true"><!-- 只对业务逻辑层实施事务 --><aop:pointcut id="txPointcut"expression="execution(* com.bdcbus.service.*.*(..))" /><aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /></aop:config></beans>

第三步,配置spring-mvc.xml

Spring的web框架围绕DispatcherServlet设计。 DispatcherServlet的作用是将请求分发到不同的处理器

DispatcherServlet类似Struts2的中央处理器,SpringMVC框架是被用来取代Struts2的,SpringMVC里面的Controller类似Struts2中Action

spring-mvc.xml的配置如下:

<?xml version="1.0" encoding="UTF-8"?><!-- 注意下面不要忘记导入mvc、context的schema --><beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- 开启自动扫描包 --><context:component-scan base-package="com.bdcbus" /><!-- 开启注解驱动 --><mvc:annotation-driven /><!-- 在地址栏访问 "网站根路径 + /404",所跳转到的页面404.ftl --><mvc:view-controller path="/404" view-name="404" /><mvc:view-controller path="/500" view-name="500" /><!-- 配置不用DispatcherServlet拦截的路径(例如:图片、CSS样式、js文件...): 路径可以自己设置,这里面我用static(WebRoot中的文件夹); 其中的"**"代表路径及其子路径 --><mvc:resources location="/static/" mapping="/3.0/**" /><!-- freemarker的基本配置 --><bean id="freemarkerConfig"class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"><!-- 这里配置你的ftl的目录 --><property name="templateLoaderPath" value="/3.0/webpage/test/" /><property name="freemarkerSettings"><props><prop key="template_update_delay">0</prop><prop key="default_encoding">UTF-8</prop><!-- 编码类型 --><prop key="number_format">0.##########</prop><prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop><prop key="classic_compatible">true</prop><prop key="template_exception_handler">ignore</prop></props></property></bean><!-- 配置freemarker视图解析器 --><bean id="viewResolver"class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"><property name="cache" value="true" /><!-- 上面的配置是固定的,下面两个配置意思是:如果你要访问index视图, 它会自动 prefix(前缀) + index + suffix(后缀),生成/WEB-INF/views/index.ftl --><property name="prefix" value="" /><!-- 路径已经在 freemarkerConfig配置,此处无需再配置,否则会出现找不到的错误 --><property name="suffix" value=".ftl" /><property name="contentType" value="text/html;charset=UTF-8"></property><property name="requestContextAttribute" value="request" /><property name="exposeSpringMacroHelpers" value="true" /><property name="exposeRequestAttributes" value="true" /><property name="exposeSessionAttributes" value="true" /></bean><!-- 配置文件上传解析器 --><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 上面配置是固定的,下面是配置上传文件的最大大小 --><property name="maxUploadSize" value="1000000" /></bean><!-- 关闭openSessionView,提高性能  <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <ref bean="openSessionInView" /> </list> </property> </bean> --><!-- 将OpenSessionInView 打开 <bean id="openSessionInView" class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> --></beans>

第四步:目录底下配置resources.properties

hibernate.dialect=org.hibernate.dialect.MySQL5Dialecthibernate.hbm2ddl.auto=updatehibernate.show_sql=falsehibernate.query.substitutions=true 1, false 0 hibernate.default_batch_fetch_size=16hibernate.max_fetch_depth=2hibernate.bytecode.use_reflection_optimizer=truehibernate.cache.use_second_level_cache=falsehibernate.cache.use_query_cache=falsehibernate.cache.region.factory_class=org.hibernate.cache.EhCacheRegionFactorynet.sf.ehcache.configurationResourceName=/ehcache_hibernate.xmlhibernate.cache.use_structured_entries=falsehibernate.generate_statistics=trueconnection.driver_class=com.mysql.jdbc.Driverconnection.url=jdbc:mysql://127.0.0.1:3306/nboss?characterEncoding=UTF-8connection.username=rootconnection.password=098732proxool.maximum.connection.count=40proxool.minimum.connection.count=5proxool.statistics=1m,15m,1h,1dproxool.simultaneous.build.throttle=30


第五步,配置spring-security.xml,项目还没做完,后续补上


Controller类用法

1>新建一个Controller类

a.我们新建一个Controller类(类似Struts2中的Action类):AppController.java

 

Java代码  收藏代码
  1. package com.kaishengit.web;  
  2.   
  3.   
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8. import org.springframework.web.servlet.ModelAndView;  
  9.   
  10. import com.kaishengit.service.UserService;  
  11.   
  12.   
  13. @Controller//1.标记一个Controller  
  14. public class AppController {  
  15.       
  16.     /** 
  17.      * Service...:和以前注入方式一样 
  18.      */  
  19.     private UserService userService;  
  20.       
  21.     //2.标记一个请求路径(URL:http://xxx/index.html),请求方式设置为GET(如果设置多种(两种)请求方式:method={RequestMethod.GET,RequestMethod.POST})  
  22.     @RequestMapping(value="/index.html",method=RequestMethod.GET)  
  23.     public ModelAndView index(){  
  24.         //ModelAndView的用法:三种  
  25.         //第一种用法:  
  26.         /*ModelAndView mav = new ModelAndView(); 
  27.         mav.setViewName("index");//要跳转到的view视图 
  28.         mav.addObject("msg", "Hello,SpringMVC");*///要传递到视图中的值(用法跟request传值相同)  
  29.           
  30.         //第二种用法  
  31.         /*ModelAndView mav = new ModelAndView("index"); 
  32.         mav.addObject("msg", "SpringMVC"); 
  33.         mav.addObject("Hi", "Hi,Jack");*/  
  34.           
  35.         //第三种用法  
  36.         ModelAndView mav = new ModelAndView("index""msg","Hello,SpringMVC");  
  37.           
  38.         return mav;  
  39.     }  
  40.   
  41.     @Autowired  
  42.     public void setUserService(UserService userService) {  
  43.         this.userService = userService;  
  44.     }  
  45. }  
 

 

b.在WebRoot中views文件夹中新建一个index.jsp

 

Html代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4.   <head>  
  5.     <title>My JSP 'index.jsp' starting page</title>  
  6.   </head>  
  7.     
  8.   <body>  
  9.     <!-- 用于显示我们从AppController.java中传的值 -->  
  10.     ${msg }<br/>  
  11.     ${Hi }  
  12.       
  13.     <!-- 用于显示图片(static是我们在springmvc-servlet.xml配置的不用DispatcherServlet拦截的文件夹);不配置的话,图片无法正常显示 -->  
  14.     <img src="static/img/pretty.png"/>  
  15.   </body>  
  16. </html>  
 

 

2>@RequestMapping配置

a.请求的URL:http://xxx/hello/yes.html(两个@RequestMapping配置值组合成一个URL)

 

Java代码  收藏代码
  1. package com.kaishengit.web;  
  2.   
  3. import org.springframework.stereotype.Controller;  
  4. import org.springframework.web.bind.annotation.RequestMapping;  
  5. import org.springframework.web.servlet.ModelAndView;  
  6.   
  7. @Controller  
  8. @RequestMapping("/hello")  
  9. public class HelloController {  
  10.     @RequestMapping("/yes.html")  
  11.     public ModelAndView hello() {  
  12.         return new ModelAndView("hello","message","Hello,SpringMVC");  
  13.     }  
  14. }  

b.传递参数

第一种方式:

 

Java代码  收藏代码
  1. @RequestMapping(value="/hello{id}.html",method=RequestMethod.GET)  
  2.     //@PathVariable指定该变量值是从url中传递过来的(该变量名id和路径中变量id({id})一样)  
  3.     public ModelAndView hello(@PathVariable String id) {  
  4.         System.out.println("id:" + id);  
  5.         return new ModelAndView("hello");  
  6.     }  

 第二种方式:

 

 

Java代码  收藏代码
  1. @RequestMapping(value="/hello{id}.html",method=RequestMethod.GET)  
  2.     //@PathVariable("id")必须指定值id(该变量名personid和路径中变量名id({id})不一样)  
  3.     public ModelAndView hello(@PathVariable("id") String personid) {  
  4.         System.out.println("id:" + personid);  
  5.         return new ModelAndView("hello");  
  6.     }  

 如果传递多个参数,这里用两个举例:

 

Java代码  收藏代码
  1. @RequestMapping(value="/{name}/hello{id}.html",method=RequestMethod.GET)  
  2. public ModelAndView hello(@PathVariable String id,@PathVariable String name) {  
  3.     System.out.println("id:" + id + "\tname:" + name);  
  4.     return new ModelAndView("hello");  
  5. }  
 

 3>Controller return types

第一种:跳转到视图

 

Java代码  收藏代码
  1. @RequestMapping("/index.html")   
  2. public String index() {   
  3.     return "index"//跳转到view视图(index.jsp)  
  4. }  

 第二种:ModelAndView

 

Java代码  收藏代码
  1. @RequestMapping("/index.html")  
  2.     public ModelAndView toIndex() {  
  3.         //设置视图为hello,装载信息  
  4.         ModelAndView mav = new ModelAndView("hello","message","Hello,SpringMVC");   
  5.         return mav;  
  6.     }  

 第三种:@ResponseBody修饰,用于显示信息

a.只显示字符串信息

 

Java代码  收藏代码
  1. @RequestMapping("/show.html")   
  2.     public String showMessage() {   
  3.         return "Hello,SpringMVC";   
  4.     }  

 b.显示对象,转换成json

首先需要导入jar包:jackson-core-lgpl-1.9.6.jar和jackson-mapper-lgpl-1.9.6.jar

 

Java代码  收藏代码
  1. @RequestMapping("/show.html")  
  2.     public @ResponseBody User showMessage(){  
  3.         User user = new User();  
  4.         user.setName("meigesir");  
  5.         user.setAddress("address");  
  6.         return user;  
  7.     }  

4>接受表单值:

a.save.jsp

Html代码  收藏代码
  1. <form action="save" method="post">  
  2.         name:<input name="name" type="text"/><br/>  
  3.         password:<input name="password" type="password""/><br/>  
  4.         zipcode:<input name="zipcode" type="text"/><br/>  
  5.         <input name="submit" type="submit"/>  
  6.     </form>  

  b. @RequestMapping(value="/save.html",method=RequestMethod.POST)

Java代码  收藏代码
  1. //其中对象(user)属性会自动装载,  
  2. public String save(User user,String zipcode){  
  3.     System.out.println(user.getAddress());  
  4.     System.out.println("zipCode:" + zipcode);  
  5.     return "redirect:/index.html";//重定向只需要加"redirect:"  
  6. }  

 5>使用request、response、session(只需要传进来即可)

 

Java代码  收藏代码
  1. @RequestMapping("/show.html")   
  2. public String methodA(HttpServletRequest request, HttpServletResponse response,HttpSession session){  
  3.     session.setAttribute("session""Hello,Session!");  
  4.     return "hello";   
  5. }  

 可以在hello.jsp页面通过${sessionScope.session }取到值

6>文件上传

首先我们导入jar包:commons-fileupload-1.2.2.jar、commons-io-2.0.1.jar

a.配置文件上传解析器:我们已经在springmvc-servlet.xml配置了“配置文件上传解析器”

b.JSP页面

 

Html代码  收藏代码
  1. <form action="file" method="post" enctype="multipart/form-data">  
  2.         <input type="text" name="name"/>  
  3.         <input type="file" name="file"/>  
  4.         <input type="submit" value="upload"/>  
  5.     </form>  

 c.服务器端程序

 

Java代码  收藏代码
  1. @RequestMapping(value="file",method=RequestMethod.POST)  
  2. public String file(String name,@RequestParam MultipartFile file){  
  3.     //上面的@RequestParam代表是从JSP页面传过来的值  
  4.     System.out.println("文件名:" + name);  
  5.     try {  
  6.         file.transferTo(new File("c:/upload/" + file.getOriginalFilename()));  
  7.     } catch (IOException e) {  
  8.         e.printStackTrace();  
  9.     }  
  10.     return "file";  
  11. }  

 7>Model ModelAndView

 

Java代码  收藏代码
  1. @RequestMapping("/model.html")   
  2. public String testModel(Model model){   
  3.     model.addAttribute("message""model");   
  4.     return "hello";   
  5. }  

ModelAndView前面已经详细介绍过

区别就是:Model的返回类型可以是String,ModelAndView返回类型是ModelAndView



用@ModelAttribute注解获取POST请求的FORM表单数据

JSP
1 <form method="post" action="hao.do">
2 a: <input id="a" type="text"   name="a"/>
3 b: <input id="b" type="text"   name="b"/>
4 <input type="submit" value="Submit" />
5 </form>

JAVA pojo
1 public class Pojo{
2     private String a;
3     private int b;
4     
5 

JAVA controller
1 @RequestMapping(method = RequestMethod.POST)
2     public String processSubmit(@ModelAttribute("pojo") Pojo pojo) { 
3         
4         return "helloWorld";
5     }
直接用HttpServletRequest获取
JAVA
1     @RequestMapping(method = RequestMethod.GET)
2     public String get(HttpServletRequest request, HttpServletResponse response) {
4         System.out.println(request.getParameter("a"));
5         return "helloWorld";
6     }
用注解@RequestParam绑定请求参数a到变量a
当请求参数a不存在时会有异常发生,可以通过设置属性required=false解决,
例如:
 
@RequestParam(value="a", required=false)

JAVA
1     @RequestMapping(value = "/requestParam", method = RequestMethod.GET)
2     public String setupForm(@RequestParam("a") String a, ModelMap model) {
3         System.out.println(a);
4         return "helloWorld";}


如果要整合freemarker的框架,则将上面的viewResolver配置更换为以下配置
<!-- 针对freemarker的视图配置 -->
    
<bean id="viewResolver"
        class
="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        
<property name="cache" value="true" />
        
<property name="prefix" value="/WEB-INF/view" />
        
<property name="suffix" value=".ftl" />
        
<property name="contentType" value="text/html;charset=UTF-8"></property>
        
<property name="requestContextAttribute" value="request" />
        
<property name="exposeSpringMacroHelpers" value="true" />
        
<property name="exposeRequestAttributes" value="true" />
        
<property name="exposeSessionAttributes" value="true" />
    
</bean>

另外在applicationContext.xml上加入:
<bean id="freemarkerConfig"
        class
="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        
<property name="templateLoaderPath" value="/WEB-INF/view/" />
        
<property name="freemarkerSettings">
            
<props>
                
<prop key="template_update_delay">0</prop>
                
<prop key="default_encoding">UTF-8</prop>
                
<prop key="number_format">0.##########</prop>
                
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                
<prop key="classic_compatible">true</prop>
                
<prop key="template_exception_handler">ignore</prop>
            
</props>
        
</property>
    
</bean>

Spring MVC集成freemarker常见问题

问题1,spring mvc 找不到ftl文件

 

集成中遇到一个问题,就是一直找不到渲染的ftl文件。后来找到原因是,配置的地方出错。特意标记出来。后面配置的时候需要注意一下。

报错:

Java代码  收藏代码
  1. java.io.FileNotFoundException: Template love/index.ftl not found.  
  2.     at freemarker.template.Configuration.getTemplate(Configuration.java:489)  
 

 

 

Xml代码  收藏代码
  1.     <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
  2.       <property name="cache" value="true"/>  
  3. <span style="color: #0000ff;">    <property name="prefix" value=""/></span>  
  4.   
  5.   
  6.   
  7.   
  8.   
  9.       <property name="suffix" value=".ftl"/>  
  10.     </bean>  

 

Xml代码  收藏代码
  1. <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
  2. span style="color: #0000ff;">     <property name="templateLoaderPath" value="/WEB-INF/ftl/"/></span>  
  3.   
  4.   
  5.   
  6.   
  7.   
  8. </bean>  

 

通常我们在配置渲染的路径时,都会直接在viewResolver中直接配置,prefix,suffix.但是需要注意的在配置freemarker时,还有一个templateLoaderPath值设置问题。

 

问题2,spring mvc 集成Freemarker乱码问题

 

Spring MVC中集成Freemarker乱码问题:在网上查了很久,都找到相关的文件。但都只是写了部分配置事项。Spring在集成Freemarker需要在两个地方指定编码集

1.

Xml代码  收藏代码
  1. <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
  2. strong>   <property name="defaultEncoding" value="UTF-8"/></strong>  
  3.   
  4.   
  5.   
  6.   
  7. </bean>  

 2.

Xml代码  收藏代码
  1. <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
  2. strong>   <property name="contentType" value="text/html;charset=utf-8"></property></strong>  
  3.   
  4.   
  5.   
  6.   
  7. </bean>  

 都指定为UTF-8,问题解决。



0 0