你的位置:首页 > Java教程

[Java教程]利用maven/eclipse搭建ssm(spring+spring mvc+mybatis)


前言

  本文旨在利用maven搭建ssm环境,而关于maven的具体内容,大家可以去阅读《Maven 实战》。其实园内这方面文章已有不少,那么为什么我还要重复造轮子呢?我只是想记录自己的实践过程罢了,附带着给别人以参考。对于别人的博文,看了固然好,要是能付之实践,那就更好了!

maven安装

  安装过程挺简单的,去apache下载apache-maven的zip包,解压到一个目录下,如下图

  接下来配置windows环境,右击我的电脑--》属性--》高级系统设置--》环境变量--》系统变量--》新建,如下图

  就是你解压的maven的home目录;接着编辑系统变量的Path,如图

  其实跟配置java环境是一样的,最后几个连续确定之后就好了,这几个确定一定要点,不然配置不会保存,更不会生效! home路径一定要写自己的,别搬我的呀!路径最好是拷贝,手动输入太容易出错了。

  接下来验证环境是否配置成功,打开命令行,输入mvn -v 如果出现下图的信息,那么恭喜你,配置成功了!当然,信息可能有些许出入,如版本不同等,这些不用在意。

Eclipse(java ee版)集成maven

  一般而言,新的eclipse都已经集成了maven,如果没有那么就安装,点击eclipse菜单栏Help->Eclipse Marketplace搜索关键字maven到插件Maven Integration for Eclipse 并点击安装即可,接下来将eclipse集成的maven换成我们自己的,而不用eclipse自带的,重新定位,点击Window -> Preference -> Maven -> Installation -> Add进行设置,如下图

  选择项目路径,如下图,然后next

  

  选择项目类型 选择Artifact Id为maven-archetype-webapp那一项,如下图

  输入Group ID和 Artifact ID,以及Package,具体Group ID和 Artifact ID代表什么,可以去阅读《Maven 实战》,Group ID相当于一个组织,而Artifact ID相当于这个组织下的一个具体项目,Packege的话会根据你的Group ID和Artifact ID生成一个默认的名称,就用默认的就可以,如下图

  若目录结构和上面的有差别,那么将perspective改成Java模式就好了。上面的目录结构离标准的maven web结构还有一点差别,少了一个文件夹src/test/resources,我们手动创建下,右键项目根目录点击New -> Source Folder,建出这个文件夹,如下图:

  Finish之后,项目结构图如下所示:

  把项目变成Dynamic Web项目右键项目,properties --》Project Facets,点击Convert to faceted fro,勾上Dynamic Web Module,并将Version为2.3。(3.0为Java7的)。

  设置部署程序集(Web Deployment Assembly)
        上面步骤设置完成后,点击OK,再右键项目,选择properties --》Deployment Assembly,如下图

构建框架

  在pom.

<project   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>com.lee.mvnbook</groupId>  <artifactId>maven-ssm-web</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <name>maven-ssm-web Maven Webapp</name>  <url>http://maven.apache.org</url>  <properties>    <!-- spring版本号 -->    <spring.version>4.0.2.RELEASE</spring.version>  </properties>  <dependencies>    <!-- spring核心包 -->    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-core</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-web</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-oxm</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-tx</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-jdbc</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-webmvc</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-aop</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-context-support</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-test</artifactId>      <version>${spring.version}</version>    </dependency>    <!-- 添加MyBatis依赖 -->    <dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis</artifactId>      <version>3.3.0</version>    </dependency>    <dependency>      <groupId>mysql</groupId>      <artifactId>mysql-connector-java</artifactId>      <version>5.0.8</version>    </dependency>    <!-- 阿里巴巴的数据库连接池 -->    <dependency>      <groupId>com.alibaba</groupId>      <artifactId>druid</artifactId>      <version>1.0.16</version>    </dependency>    <!-- spring结成mybatis -->    <dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis-spring</artifactId>      <version>1.2.3</version>    </dependency>    <!-- jsp标准标签库 -->    <dependency>      <groupId>javax.servlet</groupId>      <artifactId>jstl</artifactId>      <version>1.2</version>    </dependency>    <dependency>      <groupId>log4j</groupId>      <artifactId>log4j</artifactId>      <version>1.2.16</version>    </dependency>    <dependency>      <groupId>org.slf4j</groupId>      <artifactId>slf4j-api</artifactId>      <version>1.6.1</version>    </dependency>    <dependency>      <groupId>org.slf4j</groupId>      <artifactId>slf4j-nop</artifactId>      <version>1.6.4</version>    </dependency>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.7</version>      <scope>test</scope>    </dependency>  </dependencies>  <build>    <finalName>maven-ssm-web</finalName>  </build></project>

View Code

  如果依赖不知道怎么写,比如groupId、artifactId、version不知道填什么,那么直接上http://search.maven.org/搜,对应着填写就可以了,如下图

配置文件

  web.

<?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>    <!-- 配置文件所在位置 -->  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:spring.

View Code

  spring.

<?  ="http://www.w3.org/2001/  ="http://www.springframework.org/schema/aop"   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/tx    http://www.springframework.org/schema/tx/spring-tx.xsd">  <!-- 自动注入 -->  <context:component-scan base-package="com.huawei.service.impl" />  <!-- 加载properties文件 -->  <!-- <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">    <property name="locations">      <list>        <value>classpath:mysqldb.properties</value>      </list>    </property>  </bean> --></beans>

View Code

  mybatis-spring.

<?  ="http://www.w3.org/2001/  ="http://www.springframework.org/schema/aop"   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/tx    http://www.springframework.org/schema/tx/spring-tx.xsd">  <!-- 配置数据源 -->  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">    <!-- 基本属性 url、user、password -->     <property name="driverClassName" value="com.mysql.jdbc.Driver" />     <property name="url" value="jdbc:mysql://192.168.1.100:3306/mybatis" />     <property name="username" value="root" />     <property name="password" value="root" />     <property name="initialSize" value="1" />     <property name="minIdle" value="1" />      <property name="maxActive" value="20" />     <property name="maxWait" value="60000" />    <!-- 超过时间限制是否回收 -->    <property name="removeAbandoned" value="true" />    <!-- 超过时间限制多长; -->    <property name="removeAbandonedTimeout" value="180" />    <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->    <property name="timeBetweenEvictionRunsMillis" value="60000" />    <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->    <property name="minEvictableIdleTimeMillis" value="300000" />    <!-- 用来检测连接是否有效的sql,要求是一个查询语句-->    <property name="validationQuery" value="SELECT 1" />    <!-- 申请连接的时候检测 -->    <property name="testWhileIdle" value="true" />    <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->    <property name="testOnBorrow" value="false" />    <!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->    <property name="testOnReturn" value="false" />  </bean>  <!-- Mybatis文件 -->  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="configLocation" value="classpath:mybatis-config.class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="basePackage" value="com.huawei.dao" />    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />  </bean>  <!-- 事务管理器 -->  <bean id="transactionManager"    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="dataSource" />  </bean>    <tx:annotation-driven transaction-manager="transactionManager" /></beans>

View Code

  spring-mvc.

<?  ="http://www.w3.org/2001/  ="http://www.springframework.org/schema/context"  ="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="    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    ">  <!-- 启用spring mvc 注解 -->  <context:annotation-config />    <!-- 设置使用注解的类所在的jar包 -->  <context:component-scan base-package="com.huawei.controller" />  <!-- 完成请求和注解POJO的映射 -->  <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />  <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"    p:prefix="/" p:suffix=".jsp" /></beans>

View Code

   mybatis-config.

<?DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd">    <configuration>   <!-- 全局别名设置,在映射文件中只需写别名,而不必写出整个类路径 -->   <typeAliases>       <typeAlias type="com.huawei.model.Person" alias="Person"/>   </typeAliases>      <mappers>     <mapper resource="com/huawei/mapping/PersonMapper.
View Code

  log4j.properties

log4j.rootLogger=DEBUG, stdoutlog4j.logger.org.mybatis=DEBUGlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

View Code

  mysqldb.properties

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://192.168.1.100:3306/mybatisjdbc.username=rootjdbc.password=rootjdbc.initialSize=1jdbc.minIdle=1jdbc.maxActive=20jdbc.maxWait=60000jdbc.removeAbandoned=truejdbc.removeAbandonedTimeout=180jdbc.timeBetweenEvictionRunsMillis=60000jdbc.minEvictableIdleTimeMillis=300000jdbc.validationQuery=SELECT 1jdbc.testWhileIdle=truejdbc.testOnBorrow=falsejdbc.testOnReturn=false

View Code

   项目结构图如下

java文件与jsp文件

  PersonController.java

package com.huawei.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import com.huawei.model.Person;import com.huawei.service.IPersonService;@Controller@RequestMapping("/personController")public class PersonController {    private IPersonService personService;    public IPersonService getPersonService() {    return personService;  }  @Autowired  public void setPersonService(IPersonService personService) {    this.personService = personService;  }  @RequestMapping("/showPerson")  public String showPersons(Model model){    List<Person> persons = personService.loadPersons();    model.addAttribute("persons", persons);    return "showperson";  }}

View Code

  PersonMapper.java

package com.huawei.dao;import java.util.List;import com.huawei.model.Person;public interface PersonMapper {  /**   * 插入一条记录   * @param person   */  void insert(Person person);    /**   * 查询所有   * @return   */  List<Person> queryAll();}

View Code

  PersonMapper.

<?     select * from person   </select></mapper>

View Code

  Person.java

package com.huawei.model;/** * person 实体 * @author Administrator * */public class Person {  private int id;  private String name;  private int age;    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;  }    @Override  public String toString() {    return "Person [id=" + id + ", name=" + name + "]";  }}

View Code

  IPersonService.java

package com.huawei.service;import java.util.List;import com.huawei.model.Person;public interface IPersonService {  /**   * 加载全部的person   * @return   */  List<Person> loadPersons();}

View Code

  PersonServiceImpl.java

package com.huawei.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.huawei.dao.PersonMapper;import com.huawei.model.Person;import com.huawei.service.IPersonService;@Service("personService")public class PersonServiceImpl implements IPersonService {    private PersonMapper personMapper;  public PersonMapper getPersonMapper() {    return personMapper;  }  @Autowired  public void setPersonMapper(PersonMapper personMapper) {    this.personMapper = personMapper;  }  @Override  public List<Person> loadPersons() {    return personMapper.queryAll();  }  }

View Code

  showperson.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"   pageEncoding="utf-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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=ISO-8859-1">    <title>person list</title>  </head>  <body>    <table>      <tr>        <th>姓名</th>        <th>年龄</th>      </tr>      <c:forEach items="${persons}" var="person">        <tr>          <td>${person.name }</td>          <td>${person.age }</td>        </tr>      </c:forEach>    </table>  </body></html>

View Code

mysql数据库表

最终效果

  

  那么恭喜你,也恭喜我,搭建ssm成功了!

后话

  用心的小伙伴应该发现了,前面的windows配置maven和我们用eclipse搭建ssm没有一点关系,确实和ssm搭建没有什么卵关系,我写出来是为什么了,就是有时候我们不用IDE工具,而在dos命令下利用maven搭建我们的项目的时候,那么windows配置maven就需用到了!