SSM框架开发web项目系列(一) 环境搭建篇

前言

  开发环境:Eclipse Mars + Maven + JDK 1.7 + Tomcat 7 + MySQL

  主要框架:Spring + Spring MVC + Mybatis

  目的:快速上手搭建SSM开发环境,熟悉客户端请求到数据库操作的流程。

准备工作

  本文以“人”Person对象为例,所以首先在数据库中建一张表。这里用的Navicat for MySql,新建一个名为ssm的数据库,然后在库中新建一张名为TBL_PERSON的表,3个字段,分别为主键id,姓名name,性别gender,都为字符串类型。这里主键id没有采用自增,而是用UUID随机字符串。数据表概要如图所示。

 

  新建一个maven web项目,工程结构如下和pom.xml配置如下,并创建一个pojo类Person

<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.0modelVersion>
  <groupId>com.mmmgroupId>
  <artifactId>ssm-webartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>ssm-web Maven Webappname>
  <url>http://maven.apache.orgurl>
  
    <properties>  
              
            <spring.version>4.0.2.RELEASEspring.version>  
              
            <mybatis.version>3.2.6mybatis.version>  
              
            <slf4j.version>1.7.7slf4j.version>  
            <log4j.version>1.2.17log4j.version>  
        properties>  
      
        <dependencies>  
            <dependency>  
                <groupId>junitgroupId>  
                <artifactId>junitartifactId>  
                <version>4.11version>  
                <scope>testscope>  
            dependency>  
              
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-coreartifactId>  
                <version>${spring.version}version>  
            dependency>  
      
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-webartifactId>  
                <version>${spring.version}version>  
            dependency>  
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-oxmartifactId>  
                <version>${spring.version}version>  
            dependency>  
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-txartifactId>  
                <version>${spring.version}version>  
            dependency>  
      
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-jdbcartifactId>  
                <version>${spring.version}version>  
            dependency>  
      
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-webmvcartifactId>  
                <version>${spring.version}version>  
            dependency>  
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-aopartifactId>  
                <version>${spring.version}version>  
            dependency>  
      
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-context-supportartifactId>  
                <version>${spring.version}version>  
            dependency>  
      
            <dependency>  
                <groupId>org.springframeworkgroupId>  
                <artifactId>spring-testartifactId>  
                <version>${spring.version}version>  
            dependency>  
              
            <dependency>  
                <groupId>org.mybatisgroupId>  
                <artifactId>mybatisartifactId>  
                <version>${mybatis.version}version>  
            dependency>  
              
            <dependency>  
                <groupId>org.mybatisgroupId>  
                <artifactId>mybatis-springartifactId>  
                <version>1.2.2version>  
            dependency>  
            <dependency>  
                <groupId>javaxgroupId>  
                <artifactId>javaee-apiartifactId>  
                <version>7.0version>  
            dependency>  
              
            <dependency>  
                <groupId>mysqlgroupId>  
                <artifactId>mysql-connector-javaartifactId>  
                <version>5.1.30version>  
            dependency>  
            <dependency>  
                <groupId>commons-dbcpgroupId>  
                <artifactId>commons-dbcpartifactId>  
                <version>1.2.2version>  
            dependency>  
              
            <dependency>  
                <groupId>jstlgroupId>  
                <artifactId>jstlartifactId>  
                <version>1.2version>  
            dependency>  
            <dependency>  
                <groupId>log4jgroupId>  
                <artifactId>log4jartifactId>  
                <version>${log4j.version}version>  
            dependency>  
            <dependency>  
                <groupId>com.alibabagroupId>  
                <artifactId>fastjsonartifactId>  
                <version>1.1.41version>  
            dependency>  
      
            <dependency>  
                <groupId>org.slf4jgroupId>  
                <artifactId>slf4j-apiartifactId>  
                <version>${slf4j.version}version>  
            dependency>  
      
            <dependency>  
                <groupId>org.slf4jgroupId>  
                <artifactId>slf4j-log4j12artifactId>  
                <version>${slf4j.version}version>  
            dependency>  
            <dependency>  
                <groupId>org.codehaus.jacksongroupId>  
                <artifactId>jackson-mapper-aslartifactId>  
                <version>1.9.13version>  
            dependency>  
            <dependency>  
                <groupId>commons-fileuploadgroupId>  
                <artifactId>commons-fileuploadartifactId>  
                <version>1.3.1version>  
            dependency>  
            <dependency>  
                <groupId>commons-iogroupId>  
                <artifactId>commons-ioartifactId>  
                <version>2.4version>  
            dependency>  
            <dependency>  
                <groupId>commons-codecgroupId>  
                <artifactId>commons-codecartifactId>  
                <version>1.9version>  
            dependency>  
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-annotationsartifactId>
        <version>2.5.0version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-coreartifactId>
        <version>2.5.0version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.5.0version>
    dependency>
        dependencies>  
  <build>
    <finalName>ssm-webfinalName>
  build>
project>

 

package com.mmm.pojo;
/**
 * Person实体类
 * */
public class Person {
    
    private String id;
    
    private String name;
    
    private String gender;
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getGender() {
        return gender;
    }
    
    public void setGender(String gender) {
        this.gender = gender;
    }
    

}

配置篇

  1.Spring 集成Mybatis配置文件以及应用(application-root.xml + maybatis-config.xml + jsbc.properties)

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:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd">  
                        
                    
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
       
    <context:component-scan base-package="com.mmm" />
    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>
        
      
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
          
        <property name="mapperLocations" value="classpath:com/mmm/mapper/*.xml">property>  
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
    bean>  
  
      
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.mmm.mapper" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>  
    bean>
     
beans>
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="person" type="com.mmm.pojo.Person" />
    typeAliases>
configuration>
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

  2.Spring MVC配置(application-mvc.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:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
                        
     
      <context:component-scan base-package="com.mmm.web" />
     <mvc:annotation-driven/>
     
       
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/views/" />  
        <property name="suffix" value=".jsp" />  
    bean>  
                        
                        
beans>

  3.PersonMapper映射配置文件(personMapper.xml)

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.mmm.mapper.PersonMapper">
    
    <resultMap type="person" id="personResultMap" >
        <id property="id" column="id">id>
        <result property="name" column="name">result>
        <result property="gender" column="gender">result>
    resultMap>
    
    
    <insert id="insert" parameterType="person" >
        <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
            select replace(uuid(),'-','') from dual
        selectKey>
        insert into `TBL_PERSON` values (#{id},#{name},#{gender})
    insert>
    
    
    <delete id="delete">
        delete from `TBL_PERSON` where id = #{id}
    delete>
    
    
    <update id="update" parameterType="person">
        update `TBL_PERSON` set name = #{name}, gender = #{gender}
    update>
    
    
    <select id="selectAll" resultMap="personResultMap">
        select * from `TBL_PERSON`
    select>
    
    
    <select id="selectById" resultType="person">
        select * from `TBL_PERSON` where id = #{id}
    select>
mapper>

  4.web.xml配置(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"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    version="3.0"> 
    
      
    <context-param>  
        <param-name>contextConfigLocationparam-name>  
        <param-value>classpath:application-root.xmlparam-value>  
    context-param>  
      
    <filter>  
        <filter-name>encodingFilterfilter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
        <async-supported>trueasync-supported>  
        <init-param>  
            <param-name>encodingparam-name>  
            <param-value>UTF-8param-value>  
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>encodingFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  
      
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
    listener>  
  
      
    <servlet>  
        <servlet-name>SpringMVCservlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
        <init-param>  
            <param-name>contextConfigLocationparam-name>  
            <param-value>classpath:application-mvc.xmlparam-value>  
        init-param>  
        <load-on-startup>1load-on-startup>  
        <async-supported>trueasync-supported>  
    servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVCservlet-name>  
        <url-pattern>/url-pattern>  
    servlet-mapping>  
    
web-app>

代码篇

  1.mapper包下(com.mmm.mapper)

package com.mmm.mapper;

import java.util.List;

import com.mmm.pojo.Person;

public interface PersonMapper {
    //新增一个Person对象
    void insert(Person p);
    
    //根据主键id删除Person对象
    void deleteById(String id);
    
    //修改一个person对象
    void update(Person p);
    
    //根据主键id查找Person对象
    Person selectById(String id);
    
    //查找所有Person对象,返回集合类型
    List selectAll();

}

  2.service包下(com.mmm.service)

package com.mmm.service;

import java.util.List;

import com.mmm.pojo.Person;

public interface PersonService {
    
    //新增一个Person对象
    void insert(Person p);
    
    //根据主键id删除Person对象
    void deleteById(String id);
    
    //修改一个person对象
    void update(Person p);
    
    //根据主键id查找Person对象
    Person selectById(String id);
    
    //查找所有Person对象,返回集合类型
    List selectAll();
}
package com.mmm.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mmm.mapper.PersonMapper;
import com.mmm.pojo.Person;
@Service
public class PersonServiceImpl implements PersonService {
    
    @Resource
    PersonMapper personMapper;

    @Override
    public void insert(Person p) {
        personMapper.insert(p);
    }

    @Override
    public void deleteById(String id) {
        personMapper.deleteById(id);
    }

    @Override
    public void update(Person p) {
        personMapper.update(p);
    }

    @Override
    public Person selectById(String id) {
        return personMapper.selectById(id);
    }

    @Override
    public List selectAll() {
        return personMapper.selectAll();
    }
    
}

  3.web包下(com.mmm.web)

package com.mmm.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mmm.pojo.Person;
import com.mmm.service.PersonService;

@Controller
@RequestMapping("person")
public class PersonController {
    
    @Autowired
    PersonService personService;
    
    /**
     * 这里return的字符串"mvc"加上前面Spring MVC配置文件中视图解析配置的前缀"/WEB-INF/views/"和后缀".jsp",
     * 构成了要请求转发要跳转到的页面路径,从根路径webapp下开始,即为/WEB-INF/views/mvc.jsp
     * */
    @RequestMapping(value="mvc")
    public String testMvc() {
        return "mvc";//
    }
    
    /**
     * 这里@ResponseBody代表方法是直接返回一个json数据回前端,
     * 注意Spring mvc配置文件中不要漏掉
     * */
    @RequestMapping(value="list")
    @ResponseBody
    public List findAll() {
        List list = personService.selectAll();
        return list;//这里通过前端返回的json数据查看到完整数据
    } 
    
    /**
     * 其中@PathVariable用来获得请求url中的动态参数
     * */
    @RequestMapping(value="one/{id}")
    @ResponseBody
    public Person findOne(@PathVariable("id") String id) {
        return personService.selectById(id);
    }
    
    
}

   至此,ssm开发基本环境已经初步搭建好

测试篇

  1.测试mybatis封装的持久层(这里以获取所有TBL_PERSON表的NAME字段值为例)

package com.test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mmm.pojo.Person;
import com.mmm.service.PersonService;

public class TestDb {
    @SuppressWarnings("resource")
    @Test
    public void testDb() {
        ApplicationContext context = new ClassPathXmlApplicationContext("application-root.xml");
        PersonService bean = (PersonService) context.getBean("personServiceImpl");
        List list = bean.selectAll();
        for(Person p:list) {
            System.out.println(p.getName());
        }
        
    }
}

结果如下

  2.测试Spring MVC部分

   Tomcat启动项目,地址栏输入http://localhost:8080/ssm-web/person/list,拿到如下图所示数据即为成功

 反省篇

  最后,SSM开发环境基本搭建完毕,既然是基本,还存在许多没有尽量完善的地方。首先Mybatis部分,这里是从零开始,也没用到什么逆向工程之类的,都自己手写,便于理解,然后关联映射只写了简单的单表操作,关联的没写到,另外单表简单操作,在这里与spring集成过程中事务也没有进行事务管理的配置等。Spring MVC方面更是简陋了点,不过实际工作开发中,比较核心的有视图解析后转发到相应页面和json返回数据,大多问题是在考虑怎样实现业务逻辑。很多细节没有写出来,然后有些原理性的东西自己也还需要不断理解学习,之后应该写一些关键细节描述类的总结文。

转载于:https://www.cnblogs.com/young-z/p/7923180.html

你可能感兴趣的:(SSM框架开发web项目系列(一) 环境搭建篇)