springmvc.xml配置文件

<!--RequestMappingHandlerMapping:对使用了@RequestMapping的方法进行映射-->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->

<!--RequestMappingHandlerAdapter:对使用了@RequestMapping的方法进行适配-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->


<!--注解驱动  代替处理器映射器和处理器适配器
    会自动注册一些bean,包括RequestMappingHandlerMapping和RequestMappingHandlerAdapter
    以及数据绑定的支持和json数据传输的支持
-->
<mvc:annotation-driven></mvc:annotation-driven>

<context:component-scan base-package="com.me.controller"></context:component-scan>

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

参数类型和三种返回类型

参数类型

  • HttpServletRequest
  • HttpServletResponse
  • Model

处理器示例1

/*
* @RequestMapping:作用是定义了请求url和处理器或者处理器方法的映射
* value="/first" 指的是对 ** first.action的url进行映射
* value定义请求的url,缺省的默认值,所以可省略
* url:(value="/first.action") 前面的“/”可加可不加。“.action”可加可不加
* method:如果不写,所有类型都支持
*/
@RequestMapping(value = "first",method = RequestMethod.GET)
public ModelAndView first(){
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.addObject("msg","这是一个springMVC注解开发");

    modelAndView.setViewName("hello");
    return modelAndView;
}

处理器示例2(返回类型)

@Controller
@RequestMapping("two")
public class TwoController {

    @RequestMapping("/first")
    public ModelAndView first(HttpServletRequest request, HttpServletResponse response){
        ModelAndView modelAndView=new ModelAndView();
        String name=request.getParameter("name");
        request.setAttribute("name","request域对象:"+name);
        modelAndView.setViewName("hello");
        return modelAndView;
    }

    @RequestMapping("/second")
    public void second(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setAttribute("name","李四");
            request.getRequestDispatcher("/one/first.action").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/third")
    public void fourth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setAttribute("name","kim");//因为是重定向,hello.jsp页面无法获取{name}
        response.sendRedirect(request.getContextPath()+"/one/first.action");
    }

    @RequestMapping("/fourth")
    public String third(){
        System.err.println("到达third");
        return "forward:/one/first.action";
    }

    @RequestMapping("/fifth")
    public String fifth(){
        return "redirect:/one/first.action";
    }

    /*直接返回一个字符串,会被视图解析器自动解析到相应页面,如“hello”则被解析到“hello.jsp”*/
    @RequestMapping("/sixth")
    public String sisth(){
        return "hello";
    }
}