1. 程式人生 > >利用spingmvc及servlet實現對url的地址去除字尾,更改字尾為html

利用spingmvc及servlet實現對url的地址去除字尾,更改字尾為html

效果圖

1.在web.xml中加上如下配置.其實就是利用servlet的目錄過濾,這樣所有帶有news的地址都會被攔截

1  <!-- restfull風格約定,去除前臺超連結訪問的字尾 -->
2   <servlet-mapping>
3           <servlet-name>DispatcherServlet</servlet-name>
4           <url-pattern>/news/*</url-pattern>
5   </servlet-mapping>

2.在springmvc.xml中配置檢視解析器

1 <!-- 檢視解析器(jsp)-->
2     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
3         <!-- <property name="order" value="1"/> -->
4         <property name="prefix" value="/WEB-INF/"/>
5         <property name="suffix" value=".jsp"/>
6
</bean>

3.接下來在你的controller中加入一個方法,我以newsController為例,增加一個go方法用於超連結的跳轉

1 /*前臺超連結跳轉處理*/
2     @RequestMapping("/go/{name}")
3     public String go(@PathVariable String name) {
4         return name;
5     }

4.前臺訪問的地址

<li><a href="${pageContext.request.contextPath}/news/newsController/go/dataAnalysis">網站分析</a></li>

go後面傳遞的是頁面的名稱,這樣即使我們傳遞dataAnalysis.html,只需要在上面的newsController的go方法中把字尾去掉,依然可以訪問到正確的頁面

(當然如果你用了攔截器自己放行就ok了)

 

拓展:首頁的無後綴訪問

首頁是使用者最先訪問的一個頁面,但我的首頁不希望和普通的新聞頁面一樣帶著news之類的字串,實現方式也很簡單

1.在web.xml中增加如下配置

 1 <!-- 首頁 -->
 2   <servlet-mapping>
 3           <servlet-name>IndexServlet</servlet-name>
 4           <url-pattern>/index</url-pattern>
 5   </servlet-mapping>
 6   
 7   <!-- 後臺 -->
 8   <servlet-mapping>
 9           <servlet-name>LoginServlet</servlet-name>
10           <url-pattern>/manage</url-pattern>
11   </servlet-mapping>

說明:建立servlet生成的是以下對映,上面是為了實現我們自定義的地址能夠對映到我們的servlet上

1 <servlet-mapping>
2     <servlet-name>IndexServlet</servlet-name>
3     <url-pattern>/IndexServlet</url-pattern>
4   </servlet-mapping>
5   <servlet-mapping>
6     <servlet-name>LoginServlet</servlet-name>
7     <url-pattern>/LoginServlet</url-pattern>
8   </servlet-mapping>

2.建立servlet,在其中實現轉發

 1 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2         response.setContentType("text/html");
 3         request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
 4     }
 5 
 6     /**
 7          * The doPost method of the servlet. <br>
 8          *
 9          * This method is called when a form has its tag value method equals to post.
10          * 
11          * @param request the request send by the client to the server
12          * @param response the response send by the server to the client
13          * @throws ServletException if an error occurred
14          * @throws IOException if an error occurred
15          */
16     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         doGet(request, response);
18     }

這樣就ok了