效果图

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

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

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

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

  <!-- restfull风格约定,去除前台超链接访问的后缀 -->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/news/*</url-pattern>
</servlet-mapping>

2.在springmvc.xml中配置视图解析器

 <!-- 视图解析器(jsp)-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="order" value="1"/> -->
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>

3.接下来在你的controller中加入一个方法,我以newsController为例,增加一个go方法用于超链接的跳转

 /*前台超链接跳转处理*/
@RequestMapping("/go/{name}")
public String go(@PathVariable String name) {
return name;
}

4.前台访问的地址

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

go后面传递的是页面的名称,这样即使我们传递dataAnalysis.html,只需要在上面的newsController的go方法中把后缀去掉,依然可以访问到正确的页面

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

拓展:首页的无后缀访问

首页是用户最先访问的一个页面,但我的首页不希望和普通的新闻页面一样带着news之类的字符串,实现方式也很简单

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

 <!-- 首页 -->
<servlet-mapping>
<servlet-name>IndexServlet</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping> <!-- 后台 -->
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/manage</url-pattern>
</servlet-mapping>

说明:创建servlet生成的是以下映射,上面是为了实现我们自定义的地址能够映射到我们的servlet上

 <servlet-mapping>
<servlet-name>IndexServlet</servlet-name>
<url-pattern>/IndexServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>

2.创建servlet,在其中实现转发

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

这样就ok了

05-26 02:52