1. 程式人生 > >SpringMVC入門(一)

SpringMVC入門(一)

ali bubuko his eal host user doc pan 連接

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>

SpringMVC入門(一)