SpringMVC中的自定義視圖使用
實現的基本步驟:
- 編寫自定義view
- 進行springmvc配置文件的配置
- 實現到目標方法的鏈接
- 在控制層添加目標方法
項目基本結構
1.在com.springmvc.view包下編寫自定義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 HelloView implements View {
@Override
public String getContentType() {
return "text/html";
}
@Override
public void render(Map<String, ?> arg0, HttpServletRequest arg1,HttpServletResponse arg2) throws Exception {
arg2.setHeader("Content-type", "text/html;charset=UTF-8");
arg2.setCharacterEncoding("UTF-8");
arg2.getWriter().print("hello view:" + new Date());
}
}
注意:我們定義的視圖類要加上註解@Component
2.進行springmvc配置文件的配置
<!-- 讓spring掃描你註解的包 -->
<context:component-scan base-package="com.springmvc.view"></context:component-scan>
<!-- 配置自定義view的解析器 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="100"></property>
</bean>
注意:order的值越小優先級越高,當有多個視圖解析器時,先通過優先級高的視圖解析器來解析,如果不行,再由優先級低的視圖解析器去解析。
3.實現到目標方法的鏈接
<a href="springmvc/helloView">This MyView</a><br>
注意:href裏面的”helloView”,
要和目標方法的@RequestMapping(“/helloView”)一致
4.在控制層添加目標方法
@RequestMapping("/springmvc")
@Controller
public class Helloword {
@RequestMapping("/helloView")
public String view() {
return "helloView";
}
...
}
注意:return “helloView”,首字母要小寫;我們自定義的視圖是HelloView,spring容器會幫我們自動去找對應的方法來實例對象。
運行結果
OK,到此結束,一個簡單的自定義視圖使用完成
這是我的第一個博客,剛好學到springmvc自定義視圖的引用,所以寥寥寫了一下,有一些還沒有解釋到位,希望大家共同探討!