spring笔记3 spring MVC的基础知识3
4,spring MVC的视图
Controller得到模型数据之后,通过视图解析器生成视图,渲染发送给用户,用户就看到了结果。
视图:view接口,来个源码查看;它由视图解析器实例化,是无状态的,所以线程安全。

spring mvc提供是视图种类如图所示,根据需要选择合适的视图:

视图解析器:值提供一个把视图名称,结合本地化得到视图实例的方法;

spring mvc提供的具体视图解析器有,除去两个抽象的,一共有14个;用户可选择多个视图解析器,通过orderNo指定优先级,默认的ContenNegotiatingViewResolver优先级最高,InternalResourceViewResolver,XsltViewResolver优先级最低;

下面分别对常用的视图举例,记录配置和使用方法:
Jsp和JStL的配置和使用方法:

jsp页面的写法:这里用到了三个标签库,还有国际化信息:
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fm" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<html>
<head>
<title>${title}</title>
</head>
<body>
<h1>${title}</h1>
<form:form modelAttribute="account" method="post" action="${ctx}/account/${action}">
<table width="100%" border="1px">
<thead>
<tr>
<td colspan="2"></td>
</tr>
</thead>
<tr>
<td><fm:message key="account.username"/> </td>
<td>
<form:errors path="userName" cssStyle="color: red;font: bolder;"/>
<form:input path="userName" size="50" htmlEscape="true"/>
</td>
</tr>
<tr>
<td><spring:message code="account.password"/></td>
<td>
<form:errors path="password" cssStyle="color: red;font: bolder;"/>
<form:password path="password" size="50" htmlEscape="true"/>
</td>
</tr>
<tr>
<td>昵称</td>
<td>
<form:errors path="nickName" cssStyle="color: red;font: bolder;"/>
<form:input path="nickName" size="50" htmlEscape="true"/>
</td>
</tr>
<tr>
<td><fm:message key="account.birthday"/></td>
<td>
<form:errors path="birthday" cssStyle="color: red;font: bolder;"/>
<form:input path="birthday" size="50" htmlEscape="true"/>
</td>
</tr>
<%--<tr>--%>
<%--<td>有效期</td>--%>
<%--<td>--%>
<%--<form:errors path="validateTime" cssStyle="color: red;font: bolder;"/>--%>
<%--<form:input path="validateTime" size="50" htmlEscape="true"/>--%>
<%--</td>--%>
<%--</tr>--%>
<tr>
<td><input type="submit" value="注册"/></td>
<td><input type="reset" value="重置"/></td>
</tr>
</table>
</form:form>
</body>
</html>
关于spring提供的form标签,如果是列表选择,一般带一个隐藏的字段,字段名是选择标签的名称前面加个下划线,保证服务器表单对象和页面表单组件数据一致;
Freemarker模版视图:
首先看配置:

然后是使用了spring提供的宏的一个简单模版:
<#import "spring.ftl" as spring />
<html>
<head>
<title>${title}</title>
</head>
<body>
<table width="100%" border="1px;"> <#list accountList as account>
<tr>
<td>${account_index}</td>
<td>${account[0]}</td>
<td>${account[1]}</td>
<td>${account[2]}</td>
</tr>
</#list>
</table>
</body>
</html>
pdf:配置方法:

生成的视图类:
package com.lfc.sh.web.sp.view; import com.google.common.base.Charsets;
import com.lfc.sh.web.sp.util.AppConstant;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.document.AbstractPdfView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.List;
import java.util.Map; public class UserListPdfView extends AbstractPdfView {
@Override
protected void buildPdfDocument(Map<String, Object> model, com.lowagie.text.Document document, com.lowagie.text.pdf.PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = new String("用户列表".getBytes(), Charsets.ISO_8859_1);
response.setHeader(AppConstant.RESPONSE_HEADER, "inline;filename=" + fileName);
Table table = new Table(5);
table.setWidth(100);
table.setBorder(1);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
Font font = new Font(BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false), 12, Font.BOLD, Color.BLACK);
ModelAndView modelAndView= (ModelAndView) model.get("modelAndView");
List<Object[]> accountList = (List<Object[]>)modelAndView.getModel().get("accountList");
if(accountList!=null&&!accountList.isEmpty())
for (Object[] account : accountList) {
table.addCell(account[0].toString());
table.addCell(account[3].toString());
table.addCell(account[4].toString());
table.addCell(account[2].toString());
table.addCell(account[1].toString());
} document.addTitle("用户列表");
document.add(table);
}
}
效果:

json:配置方式

controller的写法:

最终效果:

xls:配置方法:
<bean id="userListXls" class="com.lfc.sh.web.sp.view.UserListXlsView"></bean>
实现方法,引入poi;
package com.lfc.sh.web.sp.view; import com.google.common.base.Charsets;
import com.lfc.sh.web.sp.util.AppConstant;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map; /**
* Company: Copyright© 2009 www.7road.com All rights reserved.
* com.lfc.sh.web.sp.view
* Create Date: 13-11-19 下午12:14
* Note:一个xls的视图
*/
public class UserListXlsView extends AbstractExcelView { @Override
protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = new String("用户列表".getBytes(), Charsets.ISO_8859_1);
response.setHeader(AppConstant.RESPONSE_HEADER, "inline;filename=" + fileName); HSSFSheet sheet=workbook.createSheet("用户列表");
HSSFRow head=sheet.createRow(0);
head.createCell(0).setCellValue("编号");
head.createCell(1).setCellValue("密码");
head.createCell(2).setCellValue("昵称");
head.createCell(3).setCellValue("用户名");
head.createCell(4).setCellValue("生日"); List<Object[]> accountList= (List<Object[]>) model.get("accountList"); int rowNum=1;
for(Object[] account:accountList)
{
HSSFRow row=sheet.createRow(rowNum);
rowNum++;
row.createCell(0).setCellValue(account[0].toString());
row.createCell(1).setCellValue(account[3].toString());
row.createCell(2).setCellValue(account[2].toString());
row.createCell(3).setCellValue(account[4].toString());
row.createCell(4).setCellValue(account[5].toString());
}
}
}

RessourceBoundleViewResolver,不同的地区用户提供不同类型的视图;
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="/i18n/views"/>
</bean>
/account/list.(class)=org.springframework.web.servlet.view.InternalResourceViewResolver
内容协商视图:ContentNegotiatingViewResolver
配置方式:
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
</bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="/i18n/content"/>
<property name="cacheSeconds" value="0"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean> <!-- 定义无Controller的path<->view直接映射 -->
<!--<mvc:view-controller path="/" view-name="redirect:/task"/>--> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="3"/>
</bean> <bean id="userListPdf" class="com.lfc.sh.web.sp.view.UserListPdfView"></bean> <bean id="userListJson" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prettyPrint" value="true"/>
<property name="renderedAttributes" value="accountList"/>
</bean> <bean id="userListXls" class="com.lfc.sh.web.sp.view.UserListXlsView"></bean> <!--<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">-->
<!--<property name="basename" value="/i18n/views"/>-->
<!--</bean>--> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="0"/>
<property name="defaultContentType" value="text/html"/>
<property name="ignoreAcceptHeader" value="true"/>
<property name="favorParameter" value="true"/>
<property name="favorPathExtension" value="false"/>
<property name="parameterName" value="content"/>
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"></bean>
</list>
</property> </bean>
效果:


//todo
5,spring MVC的本地化解析,文件上传,静态资源处理,拦截器,异常处理等
6,小结
spring笔记3 spring MVC的基础知识3的更多相关文章
- 《Programming Hive》读书笔记(两)Hive基础知识
<Programming Hive>读书笔记(两)Hive基础知识 :第一遍读是浏览.建立知识索引,由于有些知识不一定能用到,知道就好.感兴趣的部分能够多研究. 以后用的时候再具体看.并结 ...
- tensorflow笔记(一)之基础知识
tensorflow笔记(一)之基础知识 版权声明:本文为博主原创文章,转载请指明转载地址 http://www.cnblogs.com/fydeblog/p/7399701.html 前言 这篇no ...
- php面试笔记(5)-php基础知识-自定义函数及内部函数考点
本文是根据慕课网Jason老师的课程进行的PHP面试知识点总结和升华,如有侵权请联系我进行删除,email:guoyugygy@163.com 在面试中,考官往往喜欢基础扎实的面试者,而函数相关的考点 ...
- php面试笔记(3)-php基础知识-运算符
本文是根据慕课网Jason老师的课程进行的PHP面试知识点总结和升华,如有侵权请联系我进行删除,email:guoyugygy@163.com 在面试中,考官往往喜欢基础扎实的面试者,而运算符相关的考 ...
- Spring笔记(4) - Spring的编程式事务和声明式事务详解
一.背景 事务管理对于企业应用而言至关重要.它保证了用户的每一次操作都是可靠的,即便出现了异常的访问情况,也不至于破坏后台数据的完整性.就像银行的自助取款机,通常都能正常为客户服务,但是也难免遇到操作 ...
- Spring笔记1——Spring起源及其核心技术
Spring的作用 当我们使用一种技术时,需要思考为什么要使用这门技术.而我们为什么要使用Spring呢?从表面上面SSH这三大框架中,Struts是负责MVC责任的分离,并且提供为Web层提供诸如控 ...
- php面试笔记(2)-php基础知识-常量和数据类型
本文是根据慕课网Jason老师的课程进行的PHP面试知识点总结和升华,如有侵权请联系我进行删除,email:guoyugygy@163.com 面试是每一个PHP初学者到PHP程序员必不可少的一步,冷 ...
- Spring笔记(6) - Spring的BeanFactoryPostProcessor探究
一.背景 在说BeanFactoryPostProcessor之前,先来说下BeanPostProcessor,在前文Spring笔记(2) - 生命周期/属性赋值/自动装配及部分源码解析中讲解了Be ...
- Spring笔记(7) - Spring的事件和监听机制
一.背景 事件机制作为一种编程机制,在很多开发语言中都提供了支持,同时许多开源框架的设计中都使用了事件机制,比如SpringFramework. 在 Java 语言中,Java 的事件机制参与者有3种 ...
随机推荐
- EF架构~数据分批批量提交
回到目录 对于大数据量提交,包括插入,更新和删除,我始终不建议用EF自带的方法,因为它会增加与数据库的交互次数,一般地,EF的一个上下文在提交时会打开一个数据连接,然后把转换成的SQL语句一条一条的发 ...
- 我所了解的chrome
Chrome的隐身模式 先来说说隐身模式的启用方法吧 1.键盘快捷:Ctrl + Shift + N. 2.在Windows7下的任务栏处,右击“Chrome”图标,会出一个下拉菜单,点击“新建隐身窗 ...
- Atitit 图像金字塔原理与概率 attilax的理解总结qb23
Atitit 图像金字塔原理与概率 attilax的理解总结qb23 1.1. 高斯金字塔 ( Gaussianpyramid): 拉普拉斯金字塔 (Laplacianpyramid):1 1.2 ...
- Atititi 版本管理 rc final rtm ga release 软件的生命周期中一般分4个版本
Atititi 版本管理 rc final rtm ga release 软件的生命周期中一般分4个版本 RC=Release Candidate,含义是"发布候选版",它不是最终 ...
- git 操作简明扼要,命令不需要多,够用就行
提升能力最快的方法就是做项目. 从前使用svn时,最开始是自己看网上教程,只会一个从服务端checkout文件,update一下,commit一下,后来使用到了分支,感觉好了不少,感觉svn还挺不错的 ...
- C#设计模式-单例模式
单例模式三种写法: 第一种最简单,但没有考虑线程安全,在多线程时可能会出问题…… public class Singleton { private static Singleton _instance ...
- java 面向对象
Java语言是纯粹的面向对象的程序设计语言,这主要表现为Java完全支持面向对象的三种基本特征:继承.封装和多态.Java语言完全以对象为中心,Java程序的最小程序单位是类,整个Java程序由一个一 ...
- seajs模块化开发
seajs是一个起辅助作用的库,所以它可以更方便开发,而它可以解决以下问题: 1.命名问题,就是冲突 2.性能问题,就是只要一个功能,但却使用一个大插件中的一个小功能,所以要手动拆分出这个功能 3.j ...
- Lookup 组件异常
Lookup组件有两个数据源,一个是上流组件的输出,一个是组件lookup的数据源,这个数据源是在Connection选项卡中进行配置.在开发package的过程中,我发现一个异常,当Lookup数据 ...
- AngularJs ui-router 路由的简单介绍
之前有写过一篇关于Angular自带的路由:ngRoute.今天来说说Angular的第三方路由:ui-router.那么有人就会问:为什么Angular有了自带的路由,我们还需要用ui-router ...