MAVEN+spring+springmvc+mybatis+mysql框架搭建+git管理

1、MAVEN下载并配置好,在命令提示符(cmd)中输入mvn -version 出来了maven版本即配置成功

2、在eclipse中新建maven工程如下:

                                                      

   选择建立webapp选项,点击next。groupid和Artifact id可以随便填写

                                              


3.建立好会出现src/main/java,src/main/resources,src/test/java,src/test/resources,如果缺少可以自己新建对应的文件夹,记得是新建source folder而不是folder,然后在buildpath中点击source,配置好每个文件夹的output folder:XXX的默认out folder路径。

4.项目框架的基本结构如下:

     在src/main/java文件夹中,新建包com.maven.spring.model(存放javabean),

                                            com.maven.spring.dao(存放spring与mybatis连接接口),

                                            cn.maven.spring.service(service接口),

                                            com.maven.spring.service.impl(service接口的实现),

                                            com.maven.spring.controller(存放控制层controller)

     在src/main/resource文件夹中,新建包conf(存放配置文件),

                                                   mapper(mybatis的mapper文件)

     在src/test/java文件夹中,新建包cn.springmvc.test(存放测试文件)

    在WEB-INF文件夹下新建jsp文件夹(存放jsp文件)


5.在maven中导入依赖包。打开pom.xml,我的pom.xml如下:

     <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>MAVEN</groupId>
    <artifactId>SpringMvc</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringMvc Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- spring需要的jar包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.4.RELEASE</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.4.RELEASE</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.4.RELEASE</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.4.RELEASE</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.2.4.RELEASE</version>
            <type>jar</type>
        </dependency>

        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!-- 连接MySQL数据库需要的jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
        <!-- 阿里巴巴数据源包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.2</version>
        </dependency>


        <!-- dbcp连接池需要的jar包 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- jstl需要的jar包 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- json数据 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <!-- log4j需要的jar包 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.0.3.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
    <plugins>
        <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <path>/</path>
                    <port>8080</port>
                    <uriEncoding>UTF-8</uriEncoding>
                    <contextReloadable>true</contextReloadable>
                </configuration>
            </plugin>
        </plugins>
        <finalName>SpringMvc</finalName>
    </build>
    
</project>

5.在resources/conf中新建spring-mybatis.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.2.xsd">

    <context:component-scan base-package="com.maven.spring.Service"/>
    <!-- 引入jdbc配置文件 -->
    <context:property-placeholder location="classpath:conf/jdbc.properties" />

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mysql?useUnicode=true&amp;characterEncoding=utf-8" />
        <property name="username" value="root" />
        <property name="password" value="root" />

        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />

        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize"
            value="33" />
        <!-- 用来检测有效sql -->
        <property name="validationQuery" value="select 1 from dual;" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- 监控数据库 -->
        <property name="filters" value="mergeStat" />
    </bean>

    <!-- mybatis文件配置,扫描所有mapper文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:conf/mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

    <!-- spring与mybatis整合配置,扫描所有dao -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.maven.spring.dao" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

    <!-- 对数据源进行事务管理 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>


6.同样在resources/conf中新建mybatis-config.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>
         <typeAlias alias="Student" type="com.maven.spring.model.Student"/>
    </typeAliases>
 
    <!-- 映射map
    <mappers>
         <mapper resource="classpath:mapper/*.xml" />
    </mappers>-->
</configuration>


7.在resources/mapper下新建StudentMapper.xml:(mybaits链接数据库的核心)

 <?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.maven.spring.dao.StudentDAO">
            
         <insert id="insertStudent" parameterType="Student" keyProperty="id">
             insert into student(
         name,
         age,
         aihao)
         values
         (       
         #{name},
         #{age},
         #{aihao})
         </insert>
         
         <select id="selectById" parameterType="int" resultType="Student">
             select * from student where id=#{id}
         </select>
          
</mapper>

8.在dao层中建立StudentDAO.java:  注:不用实现,因为会和StudengMapper中的id相对应从而实现具体

package com.maven.spring.dao;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional
import com.maven.spring.model.Student;

@Repository
public interface StudentDAO {
/*
 * 添加新用户
 */
    public int insertStudent(Student student);
    /*
     * 查找用户
     */
    public Student selectById(int id);
}

9.在model层建立Student.java:

package com.maven.spring.model;

/*
 * 学生基本信息表
 */
public class Student {
    private int id;
    private String name;
    private int age;
    private String aihao;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAihao() {
        return aihao;
    }

    public void setAihao(String aihao) {
        this.aihao = aihao;
    }

}

10.在service层建立StudentService.java:

package com.maven.spring.Service;

import com.maven.spring.model.Student;

public interface StudentService {

    public int insertStudent(Student stu);

    public Student selectStu(int id);
}

11.在service/impl中具体实现service层的接口:StudentServiceImpl.java:

package com.maven.spring.Service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.maven.spring.Service.StudentService;
import com.maven.spring.dao.StudentDAO;
import com.maven.spring.model.Student;

@Service
public class StudentServiceImpl implements StudentService{
    
    @Autowired
    private StudentDAO studao;
    
    @Override
    public int insertStudent(Student stu) {
        // TODO Auto-generated method stub
        return studao.insertStudent(stu);
    }

    @Override
    public Student selectStu(int id) {
        // TODO Auto-generated method stub
        return studao.selectById(id);
    }
}

12.在test中新建com.maven.spring.test包。新建StudentTest.java进行单元测试:

 package com.maven.spring.test;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.maven.spring.Service.StudentService;
import com.maven.spring.Service.impl.StudentServiceImpl;
import com.maven.spring.model.Student;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:conf/spring-mybatis.xml" })
public class StudentTest {
    private static final Logger LOGGER = Logger
            .getLogger(StudentTest.class);
    @Autowired
    private StudentService stuservice;
//     public void before(){                                                                   
//            @SuppressWarnings("resource")
//            ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:conf/spring.xml"
//                    ,"classpath:conf/spring-mybatis.xml"});
//            stuservice = (StudentService) context.getBean("StudentServiceImpl");
//        }
      @Test
        public void addUser(){
           Student stu = new Student();
           stu.setId(100);
           stu.setAge(1);
           stu.setName("佳佳");
           stu.setAihao("听音乐");
           int i=stuservice.insertStudent(stu);
           System.out.println("i am print:"+i);
        }
}

最后测试成功。可以从数据库中查看有没有成功完成数据插入。


现在加入springMVC:

首先建立student表。内容是id(int),age(int),name(varchar),aihao(varchar)

13.web.xml配置为:  //从web.xml中加载并识别找到加载哪些配置

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!-- 区分项目名称,防止默认重名 -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>maven.example.root</param-value>
    </context-param>
     <!-- Spring和mybatis的配置文件 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:conf/spring-mybatis.xml</param-value>  
    </context-param>
    
    <!-- Spring的log4j监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 字符集 过滤器 -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Spring view分发器 -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

14.web.xml同级目录下建立:dispatcher-servlet

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"   
       xmlns:aop="http://www.springframework.org/schema/aop"   
       xmlns:context="http://www.springframework.org/schema/context"  
       xmlns:mvc="http://www.springframework.org/schema/mvc"   
       xmlns:tx="http://www.springframework.org/schema/tx"   
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xsi:schemaLocation="http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-3.0.xsd   
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
 
    <mvc:annotation-driven />  
    <context:component-scan base-package="com.maven.spring" />  
 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
 
</beans> 

15.在controller层中新建StuController.java:

package com.maven.spring.Controller;

import javax.servlet.http.HttpServletRequest;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.maven.spring.Service.StudentService;
import com.maven.spring.model.Student;

@Controller
public class StuController {

    @Autowired
    private StudentService stuservice;
    
    @RequestMapping("stuselect")
    public String getStu(@RequestParam("idno") String idno, HttpServletRequest request,Model model) {
    //    String dd="55555jia";
        int id=Integer.parseInt(idno);
        Student stu=stuservice.selectStu(id);
//        if(stu.getName().equals("张三"))
//                dd="666666zhen";
    //    request.setAttribute("stu",stu);
        //request.setAttribute("dd",dd);    
        model.addAttribute("stu",stu);
        //request.setAttribute("newUserName", newUserName);
        //System.out.print("stu name is:"+stu.getName());
        return "selectStu";

    }
}

16.建立index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="stuselect.do" method="post">
请输入Id号查询:<input type="text" name="idno" />

<input type="submit" value="提交" />

<br />

</form>
</body>
</html>


17.建立selectStu.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>
    id:${stu.id}<br/>
    name:${stu.name}</br>
    age:${stu.age}</br>
    aihao:${stu.aihao}</br>
</p>
</body>
</html> 


最后可以从index.jsp中输入id来查找数据库中的对应的学生信息.完成搭建。

记住:网上很多教程都是右键项目-Properties-Project Facets 来转成web项目(即项目左上角有一个地球的标志),其实没必要这样,我们完成了所有的搭建之后,用git bash或者cmd 进入到我们项目用:mvn eclipse:eclipse 转成eclipse项目即可。  在git bash 中mvn tomcat7:run启动tomcat。在浏览器中输入:localhost:8080即可。

点击提交即可查询到数据库中的内容。如果没有出来的话就再好好调试一下吧,程序员的工作就是不断的和bug做斗争。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值