码迷,mamicode.com
首页 > 编程语言 > 详细

第三次课:使用注解的方式配置springMVC

时间:2016-02-29 16:02:33      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

第一部分:程序结构

技术分享

第二部分:配置与测试

1、配置扫描包

      <!-- 配置扫描包 -->
      <context:component-scan base-package="cn.shxy.web.controller" />

2、启用注解

      <!-- 启用注解 -->
      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
      <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

3、编写请求代码

package cn.shxy.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * Controller类
 * @author John
 *
 */
@Controller
public class AnnotationController {

    /**
     * 请求路径配置
     * @return
     */
    @RequestMapping(value = "/user/hello", method = RequestMethod.GET)
    public ModelAndView hello() {
        return new ModelAndView("/index", "msg", "张三");
    }

    @RequestMapping(value = "/test/index", method = RequestMethod.GET)
    public ModelAndView index() {
        return new ModelAndView("/index", "msg", "李四");
    }
}

4、测试

打开浏览器,浏览路径:http://localhost:8080/mvc1/test/index

技术分享

第三部分:注解优化

1、启用注解优化

      <!-- 启用注解 -->
      <mvc:annotation-driven />

2、@RequestMapping优化

@RequestMapping("/test/hello")
    public String hello(HttpServletRequest request) {
        request.setAttribute("msg", "张三");
        return "/index";
    }

3、请求路径优化

package cn.shxy.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Controller类
 * @author John
 *
 */
@Controller
@RequestMapping("/user")
public class AnnotationController {

    /**
     * 请求路径配置
     * @return
     */
    @RequestMapping("/test/hello")
    public String hello(HttpServletRequest request) {
        request.setAttribute("msg", "张三");
        return "/index";
    }

    @RequestMapping("/gxt/index")
    public String index(HttpServletRequest request) {
        request.setAttribute("msg", "张三");
        return "/index";
    }
}

 

第三次课:使用注解的方式配置springMVC

标签:

原文地址:http://www.cnblogs.com/tanhao/p/5227403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!