Eclipse中使用Maven搭建SSM框架

Eclipse中不使用Maven搭建SSM框架:https://www.cnblogs.com/xuyiqing/p/9569459.html

IDEA中使用Maven搭建SSM框架:https://www.cnblogs.com/xuyiqing/p/10522339.html

 

Eclipse新建Maven Project->archetype选择webapp

Window-Preferences->搜索JRES配置本地JDK(推荐1.8,过高或过低可能出现未知问题)

Window-Preferences->搜索Maven配置本地Maven和settings.xml

Window-Preferences->搜索Server配置本都Tomcat

 

然而新建好的Maven Project是报错的

解决:选中项目右键Properties->Java Build Path->Libraries->Add Library,添加Server Runtime,应用后就不会报错了

 

pom.xml加入Maven编译插件,并配置JDK和编码:

    <build>
        <finalName>xxxfinalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.6.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF8encoding>
                configuration>
            plugin>
        plugins>
    build>

保存后,项目右键Maven->Update ... 

 

由于自动构建的项目缺少src/test/resources目录,可以选择性地自行创建

Java Resource目录右键new source folder:

Project Name和项目名一致

Folder Name:src/test/resources

完成后

项目右键Properties->Java Build Path->Source

如果是最新版Eclipse,在src/test/java中选中Contains Test Source->Toggle

src/test/resources设置Output和src/test/java地Output路径一致

应用

 

设置Project Facets:可以省略,我设置只是为了提高效率

项目右键设置properties->搜索facets,设置Dynamic Web Module为3.1

发现设置失败,这是Eclipse的BUG,无论新旧版本

解决办法:进入项目路径.settins目录,打开目录中的XML文件:修改为下图所示

xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="wst.jsdt.web"/>
  <installed facet="jst.web" version="3.1"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
  <installed facet="java" version="1.8"/>
faceted-project>

 web.xml也要修改为3.1版本:

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" metadata-complete="true">

    <display-name>Archetype Created Web Applicationdisplay-name>
web-app>

 

测试:启动项目,如果正常跳到index.jsp说明准备工作顺利完成

 

接下来开始正式搭建SSM框架:

pom.xml:我选取了SSM框架和一些常用的包作为依赖

xml version="1.0" encoding="UTF-8"?>
<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>org.dreamtechgroupId>
    <artifactId>xiuxianartifactId>
    <packaging>warpackaging>
    <version>0.0.1-SNAPSHOTversion>
    <name>xiuxian Maven Webappname>
    <url>http://maven.apache.orgurl>
    
    <properties>
        <spring.version>4.3.7.RELEASEspring.version>
    properties>
    
    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.1version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.37version>
        dependency>
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.2version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.3.1version>
        dependency>
        
        <dependency>
            <groupId>taglibsgroupId>
            <artifactId>standardartifactId>
            <version>1.1.2version>
        dependency>
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.8.7version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>commons-collectionsgroupId>
            <artifactId>commons-collectionsartifactId>
            <version>3.2version>
        dependency>
        
        <dependency>
            <groupId>com.github.pengglegroupId>
            <artifactId>kaptchaartifactId>
            <version>2.3.2version>
        dependency>
    dependencies>

    <build>
        <finalName>xiuxianfinalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.6.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF8encoding>
                configuration>
            plugin>
        plugins>
    build>
project>

 

新建两个source folder:

src/main/resources/spring:用于放Spring配置文件

src/main/resources/mapper:用于放MyBatis的映射文件

在src/main/resources下创建数据库连接配置文件:jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=xxx

 

在src/main/resources下创建MyBatis配置文件: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>
    
    <settings>
        
        <setting name="useGeneratedKeys" value="true" />
        
        <setting name="useColumnLabel" value="true" />
        
        <setting name="mapUnderscoreToCamelCase" value="true" />
    settings>
configuration>

 

配置Spring:

在src/main/resources/spring下创建spring-dao.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"
    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:property-placeholder
        location="classpath:jdbc.properties" />
    
    <bean id="dataSource"
        class="com.mchange.v2.c3p0.ComboPooledDataSource">
        
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
        <property name="autoCommitOnClose" value="false" />
        <property name="checkoutTimeout" value="10000" />
        <property name="acquireRetryAttempts" value="2" />
    bean>
    
    <bean id="sqlSessionFactory"
        class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource" />
        
        <property name="configLocation"
            value="classpath:mybatis-config.xml" />
        
        <property name="typeAliasesPackage"
            value="org.dreamtech.xxx.entity" />
        
        <property name="mapperLocations"
            value="classpath:mapper/*.xml" />
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName"
            value="sqlSessionFactory" />
        
        <property name="basePackage"
            value="org.dreamtech.xxx.dao" />
    bean>
beans>

 

在src/main/resources/spring下创建spring-service.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: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/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <context:component-scan base-package="org.dreamtech.xxx.service" />
    
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource" />
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" />
beans>

 

在src/main/resources/spring下创建spring-web.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-3.2.xsd">
    
    <mvc:annotation-driven />
    
    <mvc:resources mapping="/resources/**"
        location="/resources/" />
    <mvc:default-servlet-handler />
    
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/html/" />
        <property name="suffix" value=".html" />
    bean>
    
    <context:component-scan
        base-package="org.dreamtech.xxx.web" />
beans>

 

web.xml中对Spring进行配置:顺便我也配置了验证码插件Kaptcha

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" metadata-complete="true">
    <display-name>xxxdisplay-name>
    <welcome-file-list>
        <welcome-file>index.jspwelcome-file>
    welcome-file-list>
    
    <servlet>
        <servlet-name>Kaptchaservlet-name>
        <servlet-class>com.google.code.kaptcha.servlet.KaptchaServletservlet-class>
        <init-param>
            <param-name>kaptcha.borderparam-name>
            <param-value>noparam-value>
        init-param>
        <init-param>
            <param-name>kaptcha.textproducer.font.colorparam-name>
            <param-value>redparam-value>
        init-param>
        <init-param>
            <param-name>kaptcha.textproducer.char.stringparam-name>
            <param-value>ACDEFGHJKMNPRSTUVWX23456789param-value>
        init-param>
        <init-param>
            <param-name>kaptcha.textproducer.char.lengthparam-name>
            <param-value>4param-value>
        init-param>
        <init-param>
            <param-name>kaptcha.textproducer.font.namesparam-name>
            <param-value>Arialparam-value>
        init-param>
        <init-param>
            <param-name>kaptcha.image.widthparam-name>
            <param-value>135param-value>
        init-param>
        <init-param>
            <param-name>kaptcha.image.heightparam-name>
            <param-value>50param-value>
        init-param>
        <init-param>
            <param-name>kaptcha.textproducer.font.colorparam-name>
            <param-value>redparam-value>
        init-param>
        <init-param>
            <param-name>kaptcha.textproducer.font.sizeparam-name>
            <param-value>43param-value>
        init-param>
        <init-param>
            <param-name>kaptcha.noise.colorparam-name>
            <param-value>blackparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>Kaptchaservlet-name>
        <url-pattern>/Kaptchaurl-pattern>
    servlet-mapping>
    
    <servlet>
        <servlet-name>DispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring/spring-*.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

 

到这里就配置完成了!

下面进行测试:

我写一个简单的实体类,并在数据库加入一条信息

package org.dreamtech.xiuxian.entity;

public class Person {

    private String userId;
    private Integer exp;
    private String stateId;
    private String username;
    private String password;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public Integer getExp() {
        return exp;
    }

    public void setExp(Integer exp) {
        this.exp = exp;
    }

    public String getStateId() {
        return stateId;
    }

    public void setStateId(String stateId) {
        this.stateId = stateId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "Person [userId=" + userId + ", exp=" + exp + ", stateId=" + stateId + ", username=" + username
                + ", password=" + password + "]";
    }

}

 

Dao层测试:

package org.dreamtech.xiuxian.dao;

import org.apache.ibatis.annotations.Param;
import org.dreamtech.xiuxian.entity.Person;

public interface PersonDao {
    /**
     * 根据用户名和密码得到用户信息
     * 
     * @return 用户
     */
    Person getPersonByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}
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="org.dreamtech.xiuxian.dao.PersonDao">
    <select id="getPersonByUsernameAndPassword" resultType="Person">
        SELECT
        user_id,exp,state_id,username,password
        FROM
        tb_person
        WHERE
        username=#{username}
        AND
        password=#{password}
    select>
mapper>
    
package org.dreamtech.xiuxian.dao;

import org.dreamtech.xiuxian.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/spring-dao.xml" })
public class DaoTest {
    @Autowired
    private PersonDao personDao;

    @Test
    public void testPersonDao() {
        Person person = personDao.getPersonByUsernameAndPassword("test", "test");
        System.out.println(person.getUserId());
    }
}

Dao层测试成功!

 

Service层测试:

package org.dreamtech.xiuxian.service;

import org.dreamtech.xiuxian.entity.Person;

public interface PersonService {
    /**
     * 根据用户名和密码得到用户信息
     * 
     * @return 用户
     */
    Person getPersonByUsernameAndPassword(String username, String password);
}
package org.dreamtech.xiuxian.service.impl;

import org.dreamtech.xiuxian.dao.PersonDao;
import org.dreamtech.xiuxian.entity.Person;
import org.dreamtech.xiuxian.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonDao personDao;

    @Override
    public Person getPersonByUsernameAndPassword(String username, String password) {
        if (username != null && !username.equals("")) {
            username = username.replace(" ", "");
        } else {
            throw new RuntimeException("username is null");
        }
        if (password != null && !password.equals("")) {
            password = password.replace(" ", "");
        } else {
            throw new RuntimeException("password is null");
        }
        Person person = null;
        try {
            person = personDao.getPersonByUsernameAndPassword(username, password);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("error:PersonDao.getPersonByUsernameAndPassword");
        }
        return person;
    }

}
package org.dreamtech.xiuxian.service;

import org.dreamtech.xiuxian.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml" })
public class ServiceTest {
    @Autowired
    private PersonService personService;

    @Test
    public void testPersonDao() {
        Person person = personService.getPersonByUsernameAndPassword("test", "test");
        System.out.println(person.getUserId());
    }
}

Service层测试成功!

 

Controller层测试:

package org.dreamtech.xiuxian.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dreamtech.xiuxian.entity.Person;
import org.dreamtech.xiuxian.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private PersonService personService;

    @RequestMapping("login")
    private Map login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Map modelMap = new HashMap();
        try {
            Person person = personService.getPersonByUsernameAndPassword(username, password);
            modelMap.put("person", person);
            modelMap.put("success", true);
        } catch (Exception e) {
            modelMap.put("success", false);
        }
        return modelMap;
    }
}

Controller层就不需要写测试类了,直接访问:

http://localhost:8080/xiuxian/person/login?username=test&password=test

 

所有测试完成!

转载于:https://www.cnblogs.com/xuyiqing/p/10761407.html

你可能感兴趣的:(Eclipse中使用Maven搭建SSM框架)