自己搭建spring-springmvc-mybatis工程

項目地址:https://github.com/LiuYuanZhe/springmvc-ssm

實習以來,一直在用springmvc,但是從來沒有自己搭建過一個項目,特別是一直在用jpa做簡單的加載,數據庫也一般是在使用es,redis,hbase這些,沒有用到hibernate和mybatis這兩個主流的數據庫映射框架,現在就來自己搭一個idea搭建起來的,坐落在tomcat上的demo。---idea真是好用到飛起,就是有一些配置不太好配,不錯coding事非常好用啊!!!

springmvc加載起來有兩個容器,分別是spring的父容器和springmvc的子容器,要區分好兩個容器的配置。

首先,建立一個maven的webapp項目,在pom中配置相應的依賴,需要spring,springmvc,jdbc,jstl,mybatis,springmybatis等依賴,就不詳細寫了。


這是項目的包結構。

web.xml的配置

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <display-name>Archetype Created Web Application</display-name>

    <filter><!--解決編碼問題-->
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
      </init-param>
    </filter>

    <filter-mapping>
      <filter-name>characterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

        <!--配置dispatcherservlet前端控制器,向後端分發請求-->
    <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:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>

    <!--配置springmvc攔截器攔截後綴名爲action的請求-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

    <!--監聽器加載spring和springmvc的父子容器配置文件-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>

</web-app>

在裏面配置好攔截器,和加載好配置文件,攔截器等。

sprinmvc.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:aop="http://www.springframework.org/schema/aop"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--註解掃包-->
    <context:component-scan base-package="com.sdust.ssm.controller"></context:component-scan>
    <!--視圖解析器-->
    <!--配置前端頁面的後綴以及目錄-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--處理器適配器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
    <bean id="validatorFactoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!--hibernate校驗器-->
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
        <!--指定校驗使用的資源文件,在文件中配置校驗錯誤信息-->
        <!--<property name="validationMessageSource" ref="messageSource"></property>-->
    </bean>
    <!--錯誤文件信息-->
    <!--<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">-->
        <!--<!–資源文件名–>-->
        <!--<property name="basenames">-->
            <!--<list>-->
                <!--<value>classpath:ValidationMessage</value>-->
            <!--</list>-->
        <!--</property>-->
        <!--<!–資源文件編碼格式–>-->
        <!--<property name="defaultEncoding" value="UTF-8"></property>-->
        <!--<!–對資源文件緩存時間–>-->
        <!--<property name="cacheSeconds" value="120"></property>-->
    <!--</bean>-->
    <!--配置多部件類型解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--設置上傳圖片大小-->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>
    <!--<mvc:interceptors>-->
        <!--<mvc:interceptor>-->
            <!--<mvc:mapping path=""/>-->
            <!--<-->
        <!--</mvc:interceptor>-->
    <!--</mvc:interceptors>-->
</beans>
用不到的暫時註釋掉了,在這裏面配置好註解等還有handler攔截後返回的jsp文件路徑等。

然後事spring的配置:

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <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>-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--把對象加載到spring容器,加載註解的對象-->
    <context:component-scan base-package="com.sdust.ssm"></context:component-scan>
</beans>

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

    <context:property-placeholder location="classpath:config/db.properties"></context:property-placeholder>
    <!--配置數據源dbcp-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <!--最大連接數-->
        <property name="maxActive" value="30"></property>
        <!--空閒最大連接數-->
        <property name="maxIdle" value="5"></property>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入數據源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--加載mybatis核心配置文件-->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <!--加載mapper.xml文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>
    <!--配置mapper掃描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入sqlSessionFactory對象-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <!--配置掃描的包路徑-->
        <property name="basePackage" value="com.sdust.ssm.mapper"></property>
    </bean>
</beans>

將註解和mybatis的配置文件配入,配置好數據庫連接池信息,和簡單的jdbc+jsp工程不同,將配置信息都分離,達到最大程度的解耦合,使開發任務更加的清晰。

在配置mybatis的配置:

<?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.sdust.ssm.po"></package>
    </typeAliases>
    <!--配置mapper文件-->
    <!--<mappers>-->
    <!--<package name="classpath:mappers/*.xml"></package>-->
    <!--</mappers>-->
</configuration>
由於使用spring mybatis,mappers不在這裏配置,spring自動掃入,但是別名還是要設的。

開始java代碼的編寫,首先是handler的編寫:

/**
 * Created by LiuYuanZhe on 17/12/17.
 */
@Controller
@RequestMapping(value = "/student")
public class StudentController {
    @Autowired
    StudentService studentService;

//    測試springmvc是否鏈接responsebody返回body部分可以直接用postman請求測試
    @RequestMapping(value = "/testConnection",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String connection(){
        System.out.println("連接成功");
        return "testConnection";
    }

    /**
     * 返回一個modelview來返回mybatis查取的信息
     * @return
     */
    @RequestMapping(value = "/getStudent",method = {RequestMethod.POST,RequestMethod.GET})
    public ModelAndView getStudent(){
        ModelAndView modelAndView = new ModelAndView();
        try {
            Student student = studentService.getStudentById();
            modelAndView.addObject("student",student);
            modelAndView.setViewName("student");
            System.out.println(student.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return modelAndView;
    }
}

只是一個簡單的demo,所以就使用modelandview來做一個前後端的承載。


這裏是java的包結構,然後事mapper的編寫,demo都很簡單

<?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.sdust.ssm.mapper.StudentMapper">

    <!--查詢商品列表-->
    <select id="getStudentById" resultType="Student">
        SELECT * FROM student WHERE id=1
    </select>
    <select id="getAllStudent" resultType="Student">
        SELECT id,name,sex,age,memo,birthday FROM student
    </select>
    <insert id="addStudent" parameterType="Student">
        INSERT INTO student (name,sex,age,memo,birthday) VALUES (#{name},#{sex},#{age},#{memo},#{birthday})
    </insert>
    <delete id="deleteStudent" parameterType="int">
        DELETE FROM student WHERE id=#{id}
    </delete>
    <!--<update id="updateStudent" parameterType="Student">-->
        <!--UPDATE -->
    <!--</update>-->
</mapper>

package com.sdust.ssm.mapper;

import com.sdust.ssm.po.Student;

import java.util.List;

/**
 * Created by LiuYuanZhe on 17/12/17.
 */
/*
因爲使用spring-mybatis所以mapper的xml配置文件和class類要放在同一個目錄下.
 */
public interface StudentMapper {
    public Student getStudentById() throws Exception;
    public List<Student> getAllStudent() throws Exception;
    public void addStudent(Student student) throws Exception;
    public void deleteStudent(int id) throws Exception;
}

配置文件和接口要同名,還有一個問題就是,因爲spring自動去掃描,所以mapper的類和配置文件要在同一個目錄下!!!一開始這裏卡了半天。。。

這就是簡單的maven管理的使用idea搭建的springmvc-mybatis的初學demo。

搭建好tomcat之後跑起來,使用postman調用接口,訪問成功。





調用接口查到了數據庫的數據,ohYeah!!!

還有一個地方,idea裏面tomcat配置的時候


要勾選這裏或者在depolyment


這裏配置一個別名,,,,

先到這裏吧,過一陣傳到github裏。。。。mac的截圖出來真大啊

截圖貌似都沒有傳上去

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章