Spring MVC筆記(四) 訪問靜態頁面


本例通過<mvc:resources>標簽訪問一個靜態或動態頁面。

首先還是創建一個web工程,並引入相關jar包:

創建控制器類,WebController.java

 1 package com.young.saticpage.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RequestMethod;
 6 
 7 @Controller
 8 public class WebController {
 9   @RequestMapping(value = "/index", method = RequestMethod.GET)
10   public String index() {
11     return "index";
12   }
13 
14   public String redirect() {
15     return "redirect:/pages/final.html";
16   }
17 }

staticPage-servelet.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.young" />

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

    <!-- <mvc:default-servlet-handler /> -->
    <mvc:annotation-driven/>
    <mvc:resources mapping="/pages/**" location="/WEB-INF/pages/" />
</beans>

這里使用<mvc:resources ..../>標記來映射靜態頁面。映射屬性必須是指定http請求的URL模式的Ant模式。location屬性必須指定一個或多個有效的資源目錄位置,其中包含靜態頁面,包括圖片,樣式表,JavaScript和其他靜態內容。可以使用逗號分隔的值列表指定多個資源位置。

下面是Spring視圖文件WEB-INF/jsp/index.jsp的內容。這將是一個登錄頁面,此頁面將發送一個請求訪問staticPage服務方法,該方法將此請求重定向到WEB-INF/pages文件夾中的靜態頁面。

<%@ page contentType="text/html; charset=UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring Landing Page</title>
</head>
<body>
    <h2>Spring Landing Page</h2>
    <p>點擊下面的按鈕獲得一個簡單的HTML頁面</p>
    <form:form method="GET" action="/staticPage/staticPages">
        <table>
            <tr>
                <td><input type="submit" value="獲取HTML頁面" /></td>
            </tr>
        </table>
    </form:form>
</body>
</html>

啟動Tomcat服務器,訪問http://localhost:8080/staticPage/index,如下所示:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM