it技术IT技术征服Spring

SpringMVC(五)View Rendering

2016-11-23  本文已影响75人  yongguang423

首先需要配置下SpringMVC默认视图,这里配置的是jsp

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>
渲染jsp模板

如下代码所示,直接return Jsp模板的路径(不包括后缀)即可。将需要在页面读取的数据通过model.addAttribute,在jsp页面直接可以el获取设置的变量

@RequestMapping(value="html", method=RequestMethod.GET)
public String prepare(Model model) {
        model.addAttribute("foo", "bar");
        model.addAttribute("fruit", "apple");
        return "views/html";
}

jsp代码如下所示:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
    <title>My HTML View</title>
    <link href="<c:url value="/resources/form.css" />" rel="stylesheet"  type="text/css" />     
</head>
<body>
<div class="success">
    <h3>foo: "${foo}"</h3>
    <h3>fruit: "${fruit}"</h3>
</div>
</body>
</html>
默认请求路径作为模板名

如果Controller的方法返回void,则SpringMVC会将请求路径直接作为模板的路径,如下所示,下面会映射到viewName.jsp上。

@RequestMapping(value="/viewName", method=RequestMethod.GET)
public void usingRequestToViewNameTranslator(Model model) {
    model.addAttribute("foo", "bar");
    model.addAttribute("fruit", "apple");
}
使用路径变量

使用@PathVariable可以读取url中传递的参数,SpringMVC会将方法中的参数合并到Model上去,这里不用显示的往Model里设置属性,在jsp可以直接用EL读取

@RequestMapping(value="pathVariables/{foo}/{fruit}", method=RequestMethod.GET)
public String pathVars(@PathVariable String foo, @PathVariable String fruit) {
        // No need to add @PathVariables "foo" and "fruit" to the model
        // They will be merged in the model before rendering
        return "views/html";
}

数据绑定

如下代码所示,可以将url中的变量直接绑定到javabean上

@RequestMapping(value="dataBinding/{foo}/{fruit}", method=RequestMethod.GET)
public String dataBinding(@Valid JavaBean javaBean, Model model) {
        // JavaBean "foo" and "fruit" properties populated from URI variables 
        return "views/dataBinding";
    }
上一篇下一篇

猜你喜欢

热点阅读