SpringMVC_04_Restful 风格的资源 URL

Restful 风格的资源 URL 简介 


url没有后缀:

像这样的是Restfu风格:

 

而像这种的:就不是Restful风格

 

虽然Restful显得很优雅,但会出现一些问题。


SpringMVC对Restful的支持

用模拟一个简单实例来解释:

首先修改web.xml文件,把拦截改为/,所有后缀都拦截。

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

新建实体类 Article 属性有id title  content  

新建Controller类:ArticleController类:

@Controller
@RequestMapping("/article")
public class ArticleController {

	@RequestMapping("/list")
	public String list() {
		return "article/list";
	}
}

在jsp文件夹下,新建article文件夹。在里面新建list.jsp:

<table>
	<tr>
		<th colspan="2">文章列表</th>
	</tr>
	<tr>
		<td>文章1</td>
		<td><a href="${pageContext.request.contextPath }/article/details/1">内容</a></td>
	</tr>
	<tr>
		<td>文章2</td>
		<td><a href="${pageContext.request.contextPath }/article/details/2">内容</a></td>
	</tr>
	
</table>

在ArticleController中新建请求映射方法:

	@RequestMapping("/details/{id}")
	public ModelAndView details(@PathVariable("id") int id) {
		ModelAndView mav = new ModelAndView();
		if(id==1) {
			Article article = new Article("文章一", "文章一内容");
			mav.addObject("article", article);
		}else if(id==2) {
			Article article = new Article("文章二", "文章二内容");
			mav.addObject("article", article);
		}
		mav.setViewName("article/details");
		return mav;
	}

用{}代替url的值,用@PathVariable取值。

但是如果在list.jsp中请求一个图片:

<th colspan="2"><img alt="文章列表" src="${pageContext.request.contextPath }/images/article_list.jpg"></th>

会发现:

这是因为,在web.xml中进行了拦截。

这个时候需要把图片资源改为静态资源。在

<mvc:annotation-driven/>  
    <mvc:resources location="/images/" mapping="/resources/**"></mvc:resources>

把images路径映射为resourse路径。在请求images时:

<th colspan="2"><img alt="文章列表" src="${pageContext.request.contextPath }/resources/article_list.jpg"></th>

把images用resourse替换,底层就把里面的东西认为是静态资源,不需要过滤。

如果还有css,js文件,也可以这样写:

<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>

猜你喜欢

转载自blog.csdn.net/qq_27163329/article/details/81700410