SpringMVC入门(一)

Srping Web Mvc和struts2都属于表现层框架,它是spring框架的一部分。

springmvc处理流程如下:

新建一个简单的springmvc程序-idea:https://www.cnblogs.com/wormday/p/8435617.html

1.src下新建文件夹com.david.controller

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_3_1.xsd"
         version="3.1">
    <!--前端控制器 -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <!--如果不配置会默认去找 /WEB-INF/{servlet-name}-servlet.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <!-- 1. /* 拦截所有 jsp js png css
             2. *.action *.do 拦截以action do结尾的请求
             3. / 拦截所有(不包含jsp) 包含js png css
         -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3.springmvc核心配置文件- dispatcher-servlet.xml  (没有用init-param指定)

<?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"
       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">
    <!--扫描controller -->
    <context:component-scan base-package="com.david.controller"></context:component-scan>
</beans>

4.在controller目录下新增ProductController类 --这里注意不要印错ModelAndView 是servlet下的 自动引入会引入portlet下的导致无法访问

package com.david.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/product") //一级路径
public class ProductController {

    @RequestMapping("/list") //二级路径 也可写成/product/list
    public ModelAndView list(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/WEB-INF/views/list.jsp");
        return mav;
    }
}

5.去目录新建该文件 输入/product/list访问测试

springmvc架构

1.用户发送请求到前端控制器DispatcherServlet

2.DispatcherServlet收到请求调用HandlerMapping处理器映射器

3.处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器一并返回给DispatcherServlet

4.DispatcherServlet通过HandlerAdapter处理器适配器调用处理器

5.执行处理器Controller

6.Controller执行完成返回ModelAndView

7.HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet

8.HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet

9.DispatcherServlet将ModelAndView传给ViewReslover视图解析器

10.DispatcherServlet对view进行渲染试图

11.DispatcherServlet响应给用户

配置三大组件

配置处理器映射

spring3.1开始废除了DefaultAnnotationHandlerMapping的使用,默认还是这个,推荐使用RequestMappingHandlerMapping完成注解式处理器映射。

在Dispatcher-servlet.xml中配置如下

<!-- 配置处理器映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

配置处理器适配器

从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

注解驱动

直接配置以上两个比较麻烦,可以直接使用注解驱动来加载。

SpringMVC使用<mvc:annotation-driven>自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter

<mvc:annotation-driven />

视图解析器

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置逻辑视图的前缀 -->
        <property name="prefix" value="/WEB-INF/views/" />
        <!-- 配置逻辑视图的后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

在controller中就可以直接写文件名了

mav.setViewName("list");///WEB-INF/views/list.jsp

springmvc与mybatis整合

spring(包含springmvc)、mybatis、mybatis-spring整合包、数据库驱动、第三方连接池。

编辑db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/david2018_db?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234

编辑applicationContet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Mapper代理的方式扫描包 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置Mapper接口 -->
        <property name="basePackage" value="com.david.mapper" />
    </bean>

    <!--注解事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--开启注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

编辑SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 设置别名 -->
    <typeAliases>
        <package name="com.david.pojo"/>
    </typeAliases>
</configuration>

编辑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_3_1.xsd"
         version="3.1">
    <!--spring监听器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--springmvc前端控制器  -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

编辑dispatcher-servlet.xml 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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描controller -->
    <context:component-scan base-package="com.david.controller"></context:component-scan>
    <!--注解驱动 -->
    <mvc:annotation-driven />
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置逻辑视图的前缀 -->
        <property name="prefix" value="/WEB-INF/views/" />
        <!-- 配置逻辑视图的后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

编写pojo类

package com.david.pojo;

public class Product {
    private Integer id;
    private String name;
    private String price;
    private Integer categoryId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }
}

编写mapper接口和xml文件

package com.david.mapper;

import com.david.pojo.Product;
import com.sun.tools.javac.util.List;

public interface ProductMapper {
    List<Product> GetProductList();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.david.mapper.ProductMapper">
    <select id="GetProductList" resultType="Product">
        select * from Product
    </select>
</mapper>

编辑ProductController

@Controller
@RequestMapping("/product")
public class ProductController {

    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("list");

        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

        ProductMapper mapper = ac.getBean(ProductMapper.class);
        List<Product> list = mapper.GetProductList();

        mav.addObject("list",list);

        return mav;
    }
}

list.jsp

<html>
<head>
    <title>Title</title>
</head>
<body>
${list.size()}
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/baidawei/p/9095663.html