注解版的HelloSpringMVC

pom.xml、web.xml、hello.jsp 都不需要变,可以参《HelloSpringMVC》只需要改动springmvc-servlet.xml和HelloController.java

首先看springmvc-servlet.xml

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

    <!--自动扫描这个包下的注解 由IOC容器统一管理-->
    <context:component-scan base-package="com.zkw.controller"/>
    <!--让spring mvc不处理静态资源 例如 .css .js .html .mps .mp4 等-->
    <mvc:default-servlet-handler/>
    <!--
        mvc注解驱动
            在spring中一般采用@RequestMapping注解来完成映射关系
            想要使用@RequestMapping注解生效
            必须向上文中注册DefaultAnnotationHandlerMapping
            和一个AnnotationMethodHandlerAdapter实例
            这两个实例分别在类级别和方法级别处理
            而annotation-driver配置帮助我们自动完成上述两个实力的注入
    -->
    <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>

然后看HelloController.jar

package com.zkw.controller;

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

@Controller
public class HelloController {
    
    

    //如果/hello换成/zkw 那么请求的URL为
    //http://localhost:8080/springmvc_03_annotation_war_exploded/zkw
    @RequestMapping("/hello")
    public String Hello(Model model){
    
    
        //业务处理部分
        model.addAttribute("msg","Hello SpringMVC Annotation!!!!");
        //下边这个return 相当于 /WEB-INF/jsp/hello.jsp
        return "hello";
    }

}

结果如下

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/fgets__/article/details/120976164