springMvc学习之RestFul风格(三)

springMvc的Rest风格

@PathVariable获取Url变量
springMvc对静态资源文件的处理

1.在web.xml,修改请求拦截为“/”,拦截所有。
2.在spring-mvc中,对静态资源进行处理

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

    <!-- 使用注解的包,包括子集 -->
    <context:component-scan base-package="com.java1234"/>

    <mvc:annotation-driven/>
    <!-- 对静态资源进行处理 -->
    <mvc:resources mapping="/resources/**" location="/images/"/>

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


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

</beans>

2.使用PathVariable获取变量

package com.newbeedaly.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.newbeedaly.model.Article;

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

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

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

3.文章详情页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources2/css.css"/>
</head>
<body>
<p class="p1">${article.title }</p>
<p>${article.content }</p>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/willdic/article/details/80540969