SpringMVC 注解入门

90 阅读1分钟

实现步骤其实非常的简单:

1.新建一个web项目
2.导入相关jar包
3.编写web.xml,注册DispatcherServlet

注意web.xml版本问题,要最新版
注册DispatcherServlet
关联SpringMVC的配置文件启动级别为1
映射路径为/【不要用/*,会404】

4.编写pringmvc配置文件

扫描对应包中的注解,让IOC的注解生效
静态资源过滤:HTML . Js . css .图片,视频......
MVC的注解驱动(handlerdriven)
配置视图解析器(InternalResourceViewResolver)

5.接下来就是去创建对应的控制类,controller(@Controller@RequestMapping(String url))
6.最后完善前端视图和controller之间的对应
7.测试运行调试.

样例

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

spring.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">

    <context:component-scan base-package="com.mvc.controller"/>
    <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>

controller.java

@Controller
public class HelloController {
    @RequestMapping("/h1")
    public String hello(Model model){
        model.addAttribute("msg","Hello,SpringMVC");
        return "hello";
    }
}

hello.jsp

[][][]

image.png ---------------------------------------- ----------------------------------------

image.png