利用spingmvc及servlet实现对url的地址去除后缀,更改后缀为html

效果图

1.在web.xml中加上如下配置.其实就是利用servlet的目录过滤,这样所有带有news的地址都会被拦截

 一定要放在.actiobn下面,否则springmvc会无法找到对应的controller

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了

原文地址:https://www.cnblogs.com/tele-share/p/10008157.html