SpringMVC04 使用注解开发

1、spring 配置文件配置

<?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
        https://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.study.controller"/>
    <!-- 让srpingmvc 过滤一些资源,如 .JS .CSS .HTML文件,防止所有都走视图解析器 -->
    <mvc:default-servlet-handler/>
    <!-- 开启后默认帮助我们开启适配器和映射器,我们就不用自己配了 -->
    <mvc:annotation-driven/>

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

2、controller 类书写

@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","注解开发mvc");
        // return 的字符串就是视图名,视图解析器会根据返回的视图名拼接
        return "hello";
    }
}

3、相关注解的作用

  • @Controller:注册bean到spring容器中,并且声明自己是一个控制器类
  • @RequestMapping:用于映射url到控制器类或一个特定的处理方法,可用于类和方法上,如果在类上,类中所有的方法都以该路径作为父路径

4、使用restful接口参数时候

  • @PathVariable 用于接收rul上的参数
    @RequestMapping(value = "/hello/{id}")
    public String hello(@PathVariable int id, Model model){
        model.addAttribute("msg","hello mvc!"+id);
        return "hello";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值