学习springMVC 01

来源:互联网 发布:手机淘宝密码修改 编辑:程序博客网 时间:2024/06/09 21:17

1.什么是Spring MVC:

Spring MVC属于SpringFrameWork的后续产品,它提供了构建 Web 应用程序的全功能 MVC 模块,与Struts2一样是一种优秀MVC框架,不同的是自Spring2.5引入了注解式controller及Spring 3以后的不断完善,使得采用Spring MVC框架开发结构清晰明了,效率大大提高。

2.注解式Spring MVC响应流程:

绘图1

 

3.重要的接口和类的简单说明:

DispatcherServlet:前端控制器,用于接收请求。

HandlerMapping接口:用于处理请求的映射。

DefaultAnnotationHandlerMapping:HandlerMapping接口的实现,用于把一个URL映射到具体的Controller类上。

HandlerAdapter接口:用于处理请求的映射。

AnnotationMethodHandlerAdapter:HandlerAdapter接口的试下,用于把一个URL映射到对应Controller类的某个方法上。

ViewResolver接口:用于解析View。

InternalResourceViewResolver:ViewResolver接口的实现,用于把ModelAndView的逻辑视图名解析为具体的View。



4.URL通配符映射:

我们还可以通过通配符对URL映射进行配置,通配符有“?”和“*”两个字符。其中“?”表示1个字符,“*”表示匹配多个字符,“**”表示匹配0个或多个路径。

例如:

“/helloworld/index?”可以匹配“/helloworld/indexA”、“/helloworld/indexB”,但不能匹配“/helloworld/index”也不能匹配“/helloworld/indexAA”;

“/helloworld/index*”可以匹配“/helloworld/index”、“/helloworld/indexA”、“/helloworld/indexAA”但不能匹配“/helloworld/index/A”;

“/helloworld/index/*”可以匹配“/helloworld/index/”、“/helloworld/index/A”、“/helloworld/index/AA”、“/helloworld/index/AB”但不能匹配    “/helloworld/index”、“/helloworld/index/A/B”;

“/helloworld/index/**”可以匹配“/helloworld/index/”下的多有子路径,比如:“/helloworld/index/A/B/C/D”;

如果现在有“/helloworld/index”和“/helloworld/*”,如果请求地址为“/helloworld/index”那么将如何匹配?Spring MVC会按照最长匹配优先原则(即和映射配置中哪个匹配的最多)来匹配,所以会匹配“/helloworld/index”

5.URL正则表达式映射:

Spring MVC还支持正则表达式方式的映射配置

@RequestMapping(value="/reg/{name:\\w+}-{age:\\d+}", method = {RequestMethod.GET})
public ModelAndView regUrlTest(@PathVariable(value="name") String name, @PathVariable(value="age") Integer age)

http://localhost:8080/SpringMVCLesson/helloworld/reg/Hanmeimei-18 正确

http://localhost:8080/SpringMVCLesson/helloworld/reg/Hanmeimei-Lilei错误

可以为某个action指定映射的请求中必须包含某参数,或必须不包含某参数,或者某参数必须等于某个值,或者某参数必须不等于某个值这些限制

当我们为headers指定多个参数时如:headers={"example1", "example2"},表示的是and关系,即两个参数限制必须同时满足。

6。绑定数据的注解:

@RequestParam,绑定单个请求数据,可以是URL中的数据,表单提交的数据或上传的文件; 
@PathVariable,绑定URL模板变量值; 
@CookieValue,绑定Cookie数据; 
@RequestHeader,绑定请求头数据; 
5.@ModelAttribute,绑定数据到Model; 
6.@SessionAttributes,绑定数据到Session; 
7.@RequestBody,用来处理Content-Type不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等; 
8.@RequestPart,绑定“multipart/data”数据,并可以根据数据类型进项对象转换;

@RequestBody 调用合适的MessageConvert来把非application/x-www-form-urlencoded请求中的内容转换为指定的对象它通常与@ResponseBody合用,@ResponseBody与.@RequestBody刚好相反,他把指定的对象转换为合适的内容(请求头为Accept:application/json 则返回json数据)并返回。

7.数据验证

<!-- 默认的注解映射的支持 -->      <mvc:annotation-driven validator="validator" conversion-service="conversion-service" />        <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">        <property name="providerClass"  value="org.hibernate.validator.HibernateValidator"/>        <!--不设置则默认为classpath下的 ValidationMessages.properties -->        <property name="validationMessageSource" ref="validatemessageSource"/>    </bean>    <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />    <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">          <property name="basename" value="classpath:validatemessages"/>          <property name="fileEncodings" value="utf-8"/>          <property name="cacheSeconds" value="120"/>      </bean>
其中<property name="basename" value="classpath:validatemessages"/>中的classpath:validatemessages为注解验证消息所在的文件,需要我们在resources文件夹下添加。

public class ValidateModel{        @NotEmpty(message="{name.not.empty}")    private String name;    @Range(min=0, max=150,message="{age.not.inrange}")    private String age;    @NotEmpty(message="{email.not.empty}")    @Email(message="{email.not.correct}")    private String email;

在注解验证消息所在的文件即validatemessages.properties文件中添加以下内容:

name.not.empty=\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u3002age.not.inrange=\u5E74\u9F84\u8D85\u51FA\u8303\u56F4\u3002email.not.correct=\u90AE\u7BB1\u5730\u5740\u4E0D\u6B63\u786E\u3002email.not.empty=\u7535\u5B50\u90AE\u4EF6\u4E0D\u80FD\u60DF\u6050\u3002

其中name.not.empty等分别对应了ValidateModel.java文件中message=”xxx”中的xxx名称,后面的内容是在输入中文是自动转换的ASCII编码,当然你也可以直接把xxx写成提示内容,而不用另建一个validatemessages.properties文件再添加,但这是不正确的做法,因为这样硬编码的话就没有办法进行国际化了。

下面是主要的验证注解及说明:

注解

适用的数据类型

说明

@AssertFalse

Boolean, boolean

验证注解的元素值是false

@AssertTrue

Boolean, boolean

验证注解的元素值是true

@DecimalMax(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMax指定的value值

@DecimalMin(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMin指定的value值

@Digits(integer=整数位数, fraction=小数位数)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值的整数位数和小数位数上限

@Future

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间晚

@Max(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.

验证注解的元素值小于等于@Max指定的value值

@Min(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number.

验证注解的元素值大于等于@Min指定的value值

@NotNull

Any type

验证注解的元素值不是null

@Null

Any type

验证注解的元素值是null

@Past

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间早

@Pattern(regex=正则表达式, flag=)

String. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值与指定的正则表达式匹配

@Size(min=最小值, max=最大值)

String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小

@Valid

Any non-primitive type(引用类型)

验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象

@NotEmpty

CharSequence,CollectionMap and Arrays

验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)

@Range(min=最小值, max=最大值)

CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

验证注解的元素值在最小值和最大值之间

@NotBlank

CharSequence

验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格

@Length(min=下限, max=上限)

CharSequence

验证注解的元素值长度在min和max区间内

@Email

CharSequence

验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

 



jsp添加引用<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>并用spring:eval来绑定要显示的值。

名称功能NumberFormatter实现Number与String之间的解析与格式化CurrencyFormatter实现Number与String之间的解析与格式化(带货币符号)PercentFormatter实现Number与String之间的解析与格式化(带百分数符号)DateFormatter实现Date与String之间的解析与格式化NumberFormatAnnotationFormatterFactory@NumberFormat注解,实现Number与String之间的解析与格式化,可以通过指定style来指示要转换的格式(Style.Number/Style.Currency/Style.Percent),当然也可以指定pattern(如pattern=“#.##”(保留2位小数) ),这样pattern指定的格式会覆盖掉Style指定的格式JodaDateTimeFormatAnnotationFormatterFactory@DateTimeFormat注解,实现日期类型与String之间的解析与格式化这里的日期类型包括Date、Calendar、Long以及Joda的日期类型。必须在项目中添加Joda-Time包

下面就开始演示:

   @NumberFormat(style=Style.CURRENCY)   private double money;    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")    private Date date;


 money:<br/>    <spring:eval expression="contentModel.money"></spring:eval><br/>    date:<br/>    <spring:eval expression="contentModel.date"></spring:eval><br/>





名称功能NumberFormatter实现Number与String之间的解析与格式化CurrencyFormatter实现Number与String之间的解析与格式化(带货币符号)PercentFormatter实现Number与String之间的解析与格式化(带百分数符号)DateFormatter实现Date与String之间的解析与格式化NumberFormatAnnotationFormatterFactory@NumberFormat注解,实现Number与String之间的解析与格式化,可以通过指定style来指示要转换的格式(Style.Number/Style.Currency/Style.Percent),当然也可以指定pattern(如pattern=“#.##”(保留2位小数) ),这样pattern指定的格式会覆盖掉Style指定的格式JodaDateTimeFormatAnnotationFormatterFactory@DateTimeFormat注解,实现日期类型与String之间的解析与格式化这里的日期类型包括Date、Calendar、Long以及Joda的日期类型。必须在项目中添加Joda-Time包

下面就开始演示:

0 0
原创粉丝点击