Springmvc RESTful支持

1 Springmvc RESTful支持

1.1 添加DispatcherServlet的rest配置

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

1.2 URL 模板模式映射

@RequestMapping(value=”/editItem/{item_id}”):{×××}占位符,请求的URL可以是“/editItem/1”或“/editItem/2”,通过在方法中使用@PathVariable获取{×××}中的×××变量。

   @RequestMapping("/editItem/{item_id}") 
    public String useredit(@PathVariable("item_id ") String id,Model model) throws Exception{
        //方法中使用@PathVariable获取useried的值,使用model传回页面
        model.addAttribute("userid", userid);
        return"/user/useredit";
    }

如果RequestMapping中表示为”/editItem/{id}”,id和形参名称一致,@PathVariable不用指定名称。

商品查询的controller方法也改为rest实现:

// 查询商品列表
    @RequestMapping("/queryItem")
    public ModelAndView queryItem() throws Exception {
        // 商品列表
        List<Items> itemsList = itemService.findItemsList(null);

        // 创建modelAndView准备填充数据、设置视图
        ModelAndView modelAndView = new ModelAndView();

        // 填充数据
        modelAndView.addObject("itemsList", itemsList);
        // 视图
        modelAndView.setViewName("item/itemsList");

        return modelAndView;
    }

1.3 静态资源访问

spring mvc 的实现对静态资源进行映射访问。
如下是对js文件访问配置:
<mvc:resources location="/js/" mapping="/js/**"/>

猜你喜欢

转载自blog.csdn.net/fd2025/article/details/80454283
今日推荐