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的更多相关文章

  1. 《Programming Hive》读书笔记(两)Hive基础知识

    <Programming Hive>读书笔记(两)Hive基础知识 :第一遍读是浏览.建立知识索引,由于有些知识不一定能用到,知道就好.感兴趣的部分能够多研究. 以后用的时候再具体看.并结 ...

  2. tensorflow笔记(一)之基础知识

    tensorflow笔记(一)之基础知识 版权声明:本文为博主原创文章,转载请指明转载地址 http://www.cnblogs.com/fydeblog/p/7399701.html 前言 这篇no ...

  3. php面试笔记(5)-php基础知识-自定义函数及内部函数考点

    本文是根据慕课网Jason老师的课程进行的PHP面试知识点总结和升华,如有侵权请联系我进行删除,email:guoyugygy@163.com 在面试中,考官往往喜欢基础扎实的面试者,而函数相关的考点 ...

  4. php面试笔记(3)-php基础知识-运算符

    本文是根据慕课网Jason老师的课程进行的PHP面试知识点总结和升华,如有侵权请联系我进行删除,email:guoyugygy@163.com 在面试中,考官往往喜欢基础扎实的面试者,而运算符相关的考 ...

  5. Spring笔记(4) - Spring的编程式事务和声明式事务详解

    一.背景 事务管理对于企业应用而言至关重要.它保证了用户的每一次操作都是可靠的,即便出现了异常的访问情况,也不至于破坏后台数据的完整性.就像银行的自助取款机,通常都能正常为客户服务,但是也难免遇到操作 ...

  6. Spring笔记1——Spring起源及其核心技术

    Spring的作用 当我们使用一种技术时,需要思考为什么要使用这门技术.而我们为什么要使用Spring呢?从表面上面SSH这三大框架中,Struts是负责MVC责任的分离,并且提供为Web层提供诸如控 ...

  7. php面试笔记(2)-php基础知识-常量和数据类型

    本文是根据慕课网Jason老师的课程进行的PHP面试知识点总结和升华,如有侵权请联系我进行删除,email:guoyugygy@163.com 面试是每一个PHP初学者到PHP程序员必不可少的一步,冷 ...

  8. Spring笔记(6) - Spring的BeanFactoryPostProcessor探究

    一.背景 在说BeanFactoryPostProcessor之前,先来说下BeanPostProcessor,在前文Spring笔记(2) - 生命周期/属性赋值/自动装配及部分源码解析中讲解了Be ...

  9. Spring笔记(7) - Spring的事件和监听机制

    一.背景 事件机制作为一种编程机制,在很多开发语言中都提供了支持,同时许多开源框架的设计中都使用了事件机制,比如SpringFramework. 在 Java 语言中,Java 的事件机制参与者有3种 ...

随机推荐

  1. Qt控制台中文乱码问题

    本文主要记录了Qt控制台出现中文乱码的问题,一下列出了集中编码设置的方法.以前用VC6.0写的一个贪吃蛇的游戏,今天把源文件拿出来在Qt上面运行,出现中文乱码的问题.以前也遇到过,没想到小小的乱码,折 ...

  2. jQuery的选择器中的通配符[id^='code']

    1.选择器 (1)通配符: $("input[id^='code']");//id属性以code开始的所有input标签 $("input[id$='code']&quo ...

  3. Oracle查询DQL脚本记录

    --查询列 Select t.sname,t.ssex,t.class from student t --t 别名; Select *from student t; --* 代表查询表内所有数据 '; ...

  4. Oracle VM VirtualBox配置文件

    Linux 虚拟机配置文件分为两处. windows下: 1.用户名/.VirtualBox/ 这里面有2个配置文件: VirtualBox.xml 和 VirtualBox.xml-prev. 后面 ...

  5. 初入职场的建议--摘自GameRes

    又开始一年一度的校招了,最近跑了几个学校演讲,发现很多话用短短的一堂职业规划课讲还远远不够,因为那堂课仅仅可能帮大家多思考怎样找到一份合适的工作,并没有提醒大家怎样在工作中发展自己的职业. 见过这么多 ...

  6. [JavaWeb]关于DBUtils中QueryRunner的一些解读.

    前言:[本文属于原创分享文章, 转载请注明出处, 谢谢.]前面已经有文章说了DBUtils的一些特性, 这里再来详细说下QueryRunner的一些内部实现, 写的有错误的地方还恳请大家指出. Que ...

  7. salesforce 零基础开发入门学习(二)变量基础知识,集合,表达式,流程控制语句

    salesforce如果简单的说可以大概分成两个部分:Apex,VisualForce Page. 其中Apex语言和java很多的语法类似,今天总结的是一些简单的Apex的变量等知识. 有如下几种常 ...

  8. Android笔记——了解SDK,数据库sqlite的使用

    一.adb是什么? adb的全称为Android Debug Bridge,就是起到调试桥的作用.通过adb我们可以在Eclipse中方面通过DDMS来调试Android程序,说白了就是debug工具 ...

  9. WPF自定义控件与样式(4)-CheckBox/RadioButton自定义样式

    一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要内容: Che ...

  10. java接口的应用举例

    /* 接口的理解: 接口就是前期定义一个规则!某一个类A,为了扩展自身的功能,对外提供这个接口,后期只要是符合这个接口(规则) 的类(这个类是接口的子类),将子类对象的引用传递给类A中方法(方法中的参 ...