springmvc之自定义视图

在springmvc.xml中配置

    
    
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="100">property>
    bean>

常用的视图解析器是:

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

一般而言,这两种视图解析器都存在,所以我们要将自定义视图的优先级设置为低。

HelloView.java 自定义视图需要继承View

package com.gong.springmvc.views;

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 HelloView implements View{

    @Override
    public String getContentType() {
        return "text/html";
    }

    @Override
    public void render(Map model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        response.getWriter().print("hello view, time: " + new Date());
    }

}

SpringmvcTest.java

@RequestMapping("/springmvc")
@Controller
public class SpringmvcTest {
    private static final String SUCCESS = "success";
    
    @RequestMapping("/testView")
    public String testView(){
        System.out.println("testView");
        return "helloView";
    }
}

返回的值是我们自定义视图的名字:首字母小写。

index.jsp

    <a href="springmvc/testView">Test Viewa>

启动服务器之后:

 

点击:

 

证明自定义的视图解析器是成功的。当然我们也可以定义解析向excel等视图。 

你可能感兴趣的:(springmvc之自定义视图)