场景
springmv的视图不能满足自己特殊需求时候,可以自己定义视图
配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.shuoeasy.springmvc"></context:component-scan> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/views/"></property> <!-- 文件名 --> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置解析器,使用视图的名字来解析视图 --> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> <!-- order属性定义来自视图解析器的优先级。值越小优先级越高 --> <property name="order" value="123"></property> </bean> </beans>
自定义视图 MyView.java:
package com.shuoeasy.springmvc.view; import java.util.Date; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.View; /** * 自定义视图 * */ @Component public class MyView implements View { @Override public String getContentType() { return "text/html"; } @Override public void render(Map<String, ?> arg0, HttpServletRequest request, HttpServletResponse response) throws Exception { response.getWriter().print("time: " + new Date()); } }
控制器:
package com.shuoeasy.springmvc.control; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/home") @Controller public class Home { /** * 路径 : home/show */ @RequestMapping("/show") public String showPage(){ System.out.println("接收到页面请求"); // 这里使用自定义视图的名字 return "myView"; } }
页面输出:
time: Sat Sep 03 15:52:15 CST 2016