SpringMVC学习---注解开发

SpringMVC配置文件内容

<?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: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/context
		https://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/mvc
		https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--自动扫描包,让指定包下的注解生效-->
    <context:component-scan base-package="com.yyl"/>
    <!--让SpringMVC不处理静态资源:例如css,js,html请求,不走SpringMVC请求 -->
    <mvc:default-servlet-handler/>
    <!--
        配置注解驱动:可以自动实现HandlerMapping以及HandlerAdapter的注入
    -->
    <mvc:annotation-driven/>

    <!--
        添加视图解析器:
        DispatcherServlet给他的ModelAndView
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

使用注解使一个普通类变成Controller

@Controller
public class HelloController {
    public String hello(Model model){
    //该方法的返回值必须为String,返回值会被视图解析器处理
        //封装数据
        model.addAttribute("msg","Hello,SpringMVC annotation!");

        return "hello";
    }
}

为方法添加url请求以及多级请求

@Controller
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping("/h1")
    public String hello(Model model){//该方法的返回值必须为String,返回值会被视图解析器处理
        //封装数据
        model.addAttribute("msg","Hello,SpringMVC annotation!");

        return "hello";
    }
}

【注】:

  1. 在类上声明@RequestMapping时,代表类级别的url请求,说明请求指向该类下
  2. 在对应方法上声明@RequestMapping时,相应的url就具体到对应的方法
  3. 在给出的例子中,想要访问到hello()方法就需要加入url的请求为 /hello/h1

使用注解实现Controller的好处

使用注解时,一个Controller类下面可以写多个请求方法,这是它相对于使用接口来实现Controller的优点

配置总结

SpringMVC配置的三大件:

  1. HandlerMapping(处理器映射器)
  2. HandlerAdapter(处理器适配器)
  3. ViewResolver(视图解析器)

但是在注解中,只要开启:<mvc:annotation-driven/>
上述1,2两项就会被隐式地注入,就不需要再配置一遍了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值