Spring MVC学习指南(四)基于注解的控制器

一、Spring MVC注解类型的优点

  • 一个控制器类可以处理多个动作
  • 基于注解的控制器的请求映射不需要存储在配置文件中。使用RequestMapping注释类型。

二、Spring MVC 注解类型的配置

1、需要在Spring MVC的配置文件中声明spring-context

<beans 
    ...
    xmlns:context="http://www.springframework.org/schema/context"  
    >  

2、需要使用<component-scan/>

 <!--指定控制器类所在的package,越精确越好 -->
    <context:component-scan base-package="com.lyjs.controller"/> 
    <context:component-scan base-package="com.lyjs.service.impl"/> 

 三、注解类型的使用

1、import org.springframework.stereotype.Controller :用于指示Spring类的实例是一个控制器。

@Controller
public class ProductController {
}

2、import org.springframework.web.bind.annotation.RequestMapping:让Spring知道用哪一种方法来处理它的动作

@RequestMapping(value="/product_input")
    public String inputProduct(){
        return "ProductForm";
    }

 也可以用来注释一个控制器类(/product/product_input:才会映射到inputProduct()方法中。)

@Controller
@RequestMapping(value="/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @RequestMapping(value="/product_input")
    public String inputProduct(){
        return "ProductForm";
    }
}

3、import org.springframework.beans.factory.annotation.Autowired:依赖注入字段

为了使类能被spring扫描到,类必须被注明为@Service。(ProductService 的实现类需要注明 @Service 

@Autowired
private ProductService productService;

四、重定向和Flash属性

  • 1、转发比重定向快,因为重定向经过客户端,而转发没有。
  • 2、使用重定向无法轻松地传值给目标页面

Spring 3.1 版本通过Flash属性提供一种重定向传值的方法。

  • 必须Spring MVC配置文件中有一个<annotation-driven/>
  • 必须在方法上添加一个新的参数类型:import org.springframework.web.servlet.mvc.support.RedirectAttributes;

五、请求参数和路径变量

    @RequestMapping(value="/book_edit/{id}")
    public String editBook(Model model,@PathVariable long id){
        List<Category> categories=bookService.getAllCategories();
        model.addAttribute("categories", categories);
        Book book=bookService.get(id);
        model.addAttribute("book", book);
        return "BookEditForm";
    }
  • 首先,需要在RequestMapping注解的值属性中添加一个变量,该变量必须放在花括号中
  • 然后,在方法签名中添加一个同名变量,并加上@PathVariable 注解。

 

posted @ 2016-07-11 14:40  LyJs  阅读(131)  评论(0)    收藏  举报