自定义视图
写数据到JFreeChart,excel等功能是通过此特性完成的
开发步骤
1. 添加自定义视图
package org.rabbitx.web.spring4mvc.customview;
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 PrintOutView implements View {
@Override
public String getContentType() {
return "text/html";
}
@Override
public void render(Map<String, ?> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.getWriter().println("PrintOutView: " + new Date());
}
}
注意:需要把此自定义视图放置到spring容器中。后面配置的视图解析器会到容器中查找此视图bean。
2. 添加请求handler
package org.rabbitx.web.spring4mvc.requestmapping;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rabbitx.web.spring4mvc.requestmapping.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
/**
* 类定义处标记的@RequestMapping 限定了处理器类可以处理所有 URI 为 /user 的请求,它相对于 WEB 容器部署的根路径
*
* @author RabbitX
*/
@Controller
@SessionAttributes(value={"user","time"},types={String.class})
@RequestMapping("/user")
public class UserController {
/**
* 自定义视图
*
* 写数据到JFreeChart,excel等功能是通过此特性完成的
*/
@RequestMapping("/testPrintOutView")
public String testPrintOutView()
{
System.out.println("-----testPrintOutView-------");
return "printOutView";
}
}
3. 在springmvc.xml文件中配置视图解析器
<!-- 配置视图 BeanNameViewResolver 解析器: 使用视图的名字来解析视图 --> <!-- 通过 order 属性来定义视图解析器的优先级, order 值越小优先级越高 --> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> <property name="order" value="100"></property> </bean>
4. 添加jsp页面内容
<li><a href="user/testPrintOutView">自定义视图解析器</a></li>
本文详细介绍了如何在Spring MVC框架中实现并应用自定义视图,包括添加自定义视图、配置视图解析器、添加请求处理器和jsp页面内容等关键步骤。着重展示了自定义视图在写数据到JFreeChart、excel等功能中的重要作用。
942

被折叠的 条评论
为什么被折叠?



