SpringMVC+Spring+Mybaits项目框架搭建

Posted 秋天de枫叶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC+Spring+Mybaits项目框架搭建相关的知识,希望对你有一定的参考价值。

SSM+Maven是现在比较流行的项目框架,工作一年半载的对于这个项目框架都比较熟悉,这里就不在叙述SSM框架的好处。博文主要是作为一个笔者的笔记,记录一下自己的搭建过程,俗话说好纸上来得终觉浅,绝知此事要躬行。所以对于没有搭建过SSM框架的伙伴,自己最好试一试搭建过程。遇到问题,解决了也是一次不错的经历。(如果能帮到大家,我也很开心。。。注:搭建过程没有使用maven管理jar包)

 

准备的工作:

Spring:v4.2.0

Mybatis:v3.4.4

mybatis-spring:v1.3.0

mysql:6.0.6

至于搭建过程中需要用到的日志,工具等一下jar包,我会在最下面分分享出来。

 

第一步:首先建jar包引入项目中。

第二步:配置数据库引导文件与日志输出配置文件:

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mconline?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username=root
password=qwe123
initialSize=5
maxActive=10
minIdle=1
maxWait=5000

数据库:db.properties,在这里向提一下 url配置,

url=jdbc:mysql://127.0.0.1:3306/mconline?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC

防止数据库插入乱码useUnicode=true&characterEncoding=utf8 。

时区的设置:serverTimezone=UTC

 

log4j.properties配置:

log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/biz.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%dyyyy-MM-dd HH\\:mm\\:ss][%c]%m%n

第三步:配置Spring-mybatis.xml 文件:

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

    <!--自动扫描-->
    <context:component-scan base-package="com.mconline"/>

    <!--引入数据库连接文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:db.properties"/>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <!--方言-->
        <property name="driverClassName" value="$driverClassName"/>
        <!--数据库地址-->
        <property name="url" value="$url"/>
        <!--用户名-->
        <property name="username" value="$username"/>
        <!--密码-->
        <property name="password" value="$password"/>
        <!--初始化连接大小-->
        <property name="initialSize" value="$initialSize"/>
        <!--连接池最大连接数-->
        <property name="maxActive" value="$maxActive"/>
        <!--连接池最小连接数-->
        <property name="minIdle" value="$minIdle"/>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="$maxWait"/>
    </bean>

    <!--spring-mybatis整合-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--扫描mappe包下的所有xml文件-->
        <property name="configLocation" value="WEB-INF/SqlMapConfig.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--dao接口所在包,自动扫描,spring 会自动查找其下的类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--扫描数据实体包下所有的接口-->
        <property name="basePackage" value="com.mconline.mapper"/>

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

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

</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>
        <!-- 批量别名定义
        指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)
        -->
        <package name="com.mconline.po"/>

    </typeAliases>

    <!--批量加载映射文件 -->
    <mappers>
        <package name="com.mconline.mapper"/>
    </mappers>

</configuration>

第五步:设置SpringMvc.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
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--映射-->
    <mvc:annotation-driven/>
    <!--自动扫描vo,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.mconline.controller"/>
    <!--加载配置静态资源-->
    <mvc:default-servlet-handler/>

    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!--引入velocity页面模板-->
    <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath" value="/WEB-INF/view/" />
        <property name="velocityProperties">
            <props>
                <prop key="input.encoding">utf-8</prop>
                <prop key="output.encoding">utf-8</prop>
            </props>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
        <property name="cache" value="true" />
        <property name="prefix" value="" />
        <property name="suffix" value=".vm" />
        <property name="order" value="1" />
        <property name="contentType">
            <value>text/html;charset=utf-8</value>
        </property>
        <!--是否使用spring对宏定义的支持-->
        <property name="exposeSpringMacroHelpers" value="true" />
        <!--request属性引用名称,例如$rc.contextPath 获取的是项目名称-->
        <property name="requestContextAttribute" value="rc" />
    </bean>

第六步:配置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">
    <display-name>mconline</display-name>
    <!--通过过滤器设置——编码格式-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--设置spring与mybaitis配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mybatis.xml</param-value>
    </context-param>
    <!--设置spring监听-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--设置初始化springMvc-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/springmvc.xml</param-value>
        </init-param>
        <!--当 大于等于0时,初始化时加载servlet,小于0时,在使用时进行初始化-->
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.c</url-pattern>
    </servlet-mapping>
    <!--首次欢迎页面-->
    <welcome-file-list>
        <welcome-file>index.c</welcome-file>
    </welcome-file-list>

</web-app>

到这里:配置文件基本配置完成,下面开始建表,建实体、然后调通SSM框架。

 

下面设置数据库:建表


建实体:

public class UserRegister 

    private long rid; //userId

    private String accunt; //账号

    private String password; //密码

    private long registertime;//注册时间

    private int isrealname; //是否实名

    public long getRid() 
        return rid;
    

    public void setRid(long rid) 
        this.rid = rid;
    

    public String getAccunt() 
        return accunt;
    

    public void setAccunt(String accunt) 
        this.accunt = accunt;
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

    public long getRegistertime() 
        return registertime;
    

    public void setRegistertime(long registertime) 
        this.registertime = registertime;
    

    public int getIsrealname() 
        return isrealname;
    

    public void setIsrealname(int isrealname) 
        this.isrealname = isrealname;
    
    

dao接口:

public interface RegisterMapper 

     UserRegister findRegisterAccount(String username);

     int insertRegisterInfo(UserRegister userRegister);


mapper文件:mapper文件的namespace等于dao接口的"包名.接口名”

 
<?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.mconline.mapper.RegisterMapper"> <select id="findRegisterAccount" parameterType="java.lang.String" resultType="UserRegister"> SELECT * FROM userregister WHERE account=#value </select> <insert id="insertRegisterInfo" parameterType="UserRegister" > INSERT INTO userregister (rid,account,PASSWORD,registertime,isrealname)VALUES(#rid,#accunt,#password,#registertime,#isrealname) </insert> <select id="findUserReallyName" parameterType="Long" resultType="java.lang.String"> select * from userregister <where> <include refid="user_reallyName"></include> </where> </select> </mapper> 


bo层:

 
@Service public class RegisterAccountBo  @Resource private RegisterMapper registerMapper; //查询用户名是否存在 public int addAccountInfo(String acc,String pwd)  UserRegister userRegister=registerMapper.findRegisterAccount(acc); if(userRegister!=null) return resultCnst.EXIST;  if(userRegister==null) //实例UserRegister对象 userRegister=new UserRegister(); long time=System.currentTimeMillis(); userRegister.setRid(UUIDUtil.GenerateUUID()); userRegister.setAccunt(acc); userRegister.setPassword(pwd); userRegister.setRegistertime(time); userRegister.setIsrealname(0); int uid=registerMapper.insertRegisterInfo(userRegister); if(uid>0) return resultCnst.SUCCESS;  return resultCnst.ERROR;  return resultCnst.ERROR;  

controller 层:

 
@Controller @RequestMapping(value = "/register") public class RegisterController  @Autowired RegisterAccountBo registerAccountBo; @RequestMapping(value="/showregister.c") public String showRegisterPage(HttpServletRequest req, HttpServletResponse res) return "/register/register";  /** * 注册账户信息 */ @RequestMapping(value="/register.c") public void registerAccountInfo(HttpServletRequest req, HttpServletResponse rep) String account=req.getParameter("account"); String password=req.getParameter("password"); JsonHolder json=new JsonHolder(); //查询用户名是否存在 int res=registerAccountBo.addAccountInfo(account,password); if(res== resultCnst.SUCCESS) ResponseUtil.writeJson(rep,json);   



到这里,SSM框架基本搭建完成。在搭建的过程中会遇到各种各样的问题,不过最终自己还是搭建出来了,原来感觉应该挺好搭建的,但在调试的时候,出现各种问题。会不会,还需要自己动手实践一下,才知道是不是真的会了。

源码下载:https://pan.baidu.com/s/1wyRPnh9uI9tL7UhFn2QfHA 
提取码:yep8 
 


 

 

 

 

 

 

 

 

 

以上是关于SpringMVC+Spring+Mybaits项目框架搭建的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC+Spring+Mybaits项目框架搭建

分享一套spring+springMVC+mybaits+EasyUI+jQuery+Ajax+面向接口编程进销存管理系统源码!

java springmvc mybaits maven shiro mysql整合

SSM整合

mybaits和spring整合后pojo扫描怎么配置

SpringMVC——Spring整合Mybatis和SpringMVC