在上一篇中我们进行了控制器方法的编写,只是简单的配置了下视图渲染。这一篇中我会介绍有关jsp模型的数据。
1视图解析
我们在Spring中通过控制器来处理逻辑并且维护和更新视图。那么我们是怎么确定渲染哪一个视图的呢?这里就用到的Spring的视图解析器了。在上一篇中我们所用到了InternalResourceViewResolver的视图解析器。在这里我们在了解一下具体是怎么操作的。首先在SpringMvc中我们定义了一个ViewResolver的接口

当给方法resolveViewName()传入参数时会返回一个view实例。

view的任务就是把需要渲染的内容放到response中进而展现到用户的浏览器中。
当然在Spring中还有很多视图解析器,比如freemarker视图解析等等。因为大部分开发还是用的jsp模板我们还是用的是InternalResourceViewResolver视图解析。当然不排除其他的技术。
我们在最后还会介绍下一种新的技术Thymeleaf ,因为这个模板的产出最像html文件,而不需要我们操作java代码。
在Spring中提供了两种支持jsp视图的方式:

在使用配置jsp逻辑视图名称的时候我们需要配置好前缀与后缀。下面分别为Class中配置与xml文件中配置


这里我们使用了别名p来标识 ,需要在xml文件引入别名。或者自己改为标签也可以的。在我们通常使用的jsp当中,我们都需要使用jstl来获取从后台传输过来的值,那么我们在视图解析器中应该这样配置

在配置中增加jstl解析类帮助解析jstl内容。
2 使用jsp库
1)表单数据
Spring的表单绑定jsp标准库包含了14个标签。他们都是用来渲染html中的标签,区别是相对于html标签,这些jsp标签会绑定一个对象,根据属性值填充。并且标签库中还包含了为用户展示错误的标签,将信息渲染到html中。
为了使用jsp的表单绑定库,首先在页面需要声明一下


这些标签其实跟Html中的作用基本上是类似的。最终都会渲染成对应的标签。

因为在form表单中我们需要将使用commandName来绑定模型,并且在Controller中增加模型的数据。

在控制器中我们创建了一个模型,那么我们就能在表单中得到这个模型,并且表单下的属性标签会根据path里面的属性去拿到我们模型中的数据。
前面说到,我们可以使用<sf:errors>来给用户展现错误的信息,

从代码中我们也能看到它的path也设置成跟上面的path是一样的这样如果校验有错误的情况下,就可以直接展示在页面上了。为了显示明显,我们可以在errors中增加cssClass属性。其他属性标签语气使用类似,就不介绍了。
3Spring中通用的标签库


在使用这些标签我们需要首先导入

首先我们会使用<s:message>

我们需要用信息源来渲染信息,在这里比较推荐使用ReloadableResourceBundleMessageSource这个接口,样例如下

在这个样例中直接设置basename属性,可以根据类路径或者文件系统,或者在web应用的根路径下查找属性文件。并且基础信息会被命名为message.
网友评论