SpringMVC(五)View Rendering

首先需要配置下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上

(@Valid注解用于验证参数是否符合要求)

@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";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值