JavaEE(13)SpringMVC入门、注解开发

1. 回顾MVC

1. 什么是MVC
(1)MVC是模型(Model)、视图(View)、控制器(Controller)的简写,是一种软件设计规范
(2)是将业务逻辑、数据、显示分离的方法来组织代码
(3)MVC主要作用是降低了视图与业务逻辑间的双向偶合
(4)MVC详解

1. Model(模型):数据模型,提供要展示的数据,因此包含数据和行为,
	可以认为是领域模型或JavaBean组件(包含数据和行为),
	不过现在一般都分离开来:Value Object(数据Dao) 和 服务层(行为Service)。
	也就是模型提供了模型数据查询和模型数据的状态更新等功能,包括数据和业务
2. View(视图):负责进行模型的展示,一般就是我们见到的用户界面,客户想看到的东西
3. 接收用户请求,委托给模型进行处理(状态改变),
	处理完毕后把返回的模型数据返回给视图,由视图负责展示。
	也就是说控制器做了个调度员的工作

2. 典型MVC模型
最典型的MVC就是JSP + servlet + javabean的模式
在这里插入图片描述

2. 回顾Servlet

1. 新建一个maven父工程,导入pom依赖

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.2</version>
        </dependency>
    </dependencies>

2. 建立一个子工程(springmvc_01_servlet)
3. 导入servlet和jsp依赖

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>
    </dependencies>

4. 编写Servlet类,用来处理客户请求

public class HelloServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String method = request.getParameter("method");
        if (method.equals("add")){
            request.getSession().setAttribute("msg","执行了add方法");
        }

        if (method.equals("del")){
            request.getSession().setAttribute("msg","执行了del方法");
        }

        //业务逻辑
        //视图跳转
        request.getRequestDispatcher("WEB-INF/jsp/hello.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

5. 编写hello.jsp:在WEB-INF下新建一个jsp的文件夹,新建hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

6. 在web.xml中注册Servlet

<?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>HelloServlet</servlet-name>
        <servlet-class>com.nelws.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

7. 配置tomcat,启动测试

localhost:8080/hellor?method=add

localhost:8080/hello?method=del

3. SpringMVC概述

1. Spring MVC是Spring Framework的一部分,是基于Java实现MVC的轻量级Web框架
2. 特点

1. 轻量级,简单易学
2. 高效 , 基于请求响应的MVC框架
3. 与Spring兼容性好,无缝结合
4. 约定优于配置
5. 功能强大:RESTful、数据验证、格式化、本地化、主题等
6. 简洁灵活

3. Spring的web框架围绕 DispatcherServlet [调度Servlet] 设计

4. SpringMVC入门程序

1. 新建moudle(springmvc_02_hello),添加web支持
2. 配置web.xml,注册DispatcherServlet

<?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">

    <!--注册DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--关联一个springmvc的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--启动级别-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--
        /   匹配所有的请求 不包括.jsp
        /*  匹配所有的请求 包括.jsp
    -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3. 编写SpringMVC的配置文件:springmvc-servlet.xml
4. 添加处理器映射器
5. 添加处理器适配器
6. 添加视图解析器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--添加处理器映射器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <!--添加处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

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

    <!--注册Controller-->
    <bean class="com.nelws.controller.HelloController" id="/hello"/>
</beans>

7. 编写要操作业务的Controller,实现Controller接口;需要返回一个ModelAndView,装数据,封视图

public class HelloController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        //ModelAndView 模型和视图
        ModelAndView mv = new ModelAndView();

        //封装对象,放在ModelAndView中。Model
        mv.addObject("msg","HelloSpringMVC!");

        //封装要跳转的视图,放在ModelAndView中
        mv.setViewName("hello");

        return mv;
    }
}

8. 将Controller类在Spring中注册

<!--注册Controller-->
<bean class="com.nelws.controller.HelloController" id="/hello"/>

9. 写要跳转的jsp页面,显示ModelAndView存放的数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

10. 配置tomcat并测试

4. 使用注解开发

1. 配置maven资源过滤

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

2. 配置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>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

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

    <!--指定扫描包,让指定包下的注解自动生效,由IOC容器统一管理-->
    <context:component-scan base-package="com.nelws.controller"/>

    <!--让SpringMVC不处理静态资源-->
    <mvc:default-servlet-handler/>

    <!--支持MVC注解驱动
            在spring中一般采用@RequestMapping注解来完成映射关系
            要想使@RequestMapping注解生效
            必须向上下文中注册DefaultAnnotationHandlerMapping
            和一个AnnotationMethodHandlerAdapter实例
            这两个实例分别在类级别和方法级别处理。
            而annotation-driven配置帮助我们自动完成上述两个实例的注入
    -->
    <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>

4. 创建Controller

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello(Model model){
        //向模型中添加属性msg与值,可以在JSP页面中取出并渲染
        model.addAttribute("msg","Hello,SpringMVCAnno~");
        //返回值就是视图层的名字(/WEB-INF/jsp/hello.jsp)
        return "hello";
    }
}

5. 创建视图层

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

${msg}

</body>
</html>

6. 配置tomcat并测试
7. 总结
使用springMVC必须配置的三大件:处理器映射器、处理器适配器、视图解析器
通常,我们只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可,而省去了大段的xml配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值