自己搭建spring-springmvc-mybatis工程

来源:互联网 发布:mac眼线液笔好用吗 编辑:程序博客网 时间:2024/05/28 05:17

项目地址: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的截图出来真大啊

截图貌似都没有传上去

原创粉丝点击