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>xxx</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF8</encoding>
</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 Application</display-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.0</modelVersion>
<groupId>org.dreamtech</groupId>
<artifactId>xiuxian</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>xiuxian Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<spring.version>4.3.7.RELEASE</spring.version>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.1</version>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 其他包 -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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-tx</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-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<!-- 验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
</dependencies> <build>
<finalName>xiuxian</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF8</encoding>
</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>
<!-- 使用JDBC的getGeneratedKeys获取数据库自增主键值 -->
<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>
<!-- 配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation"
value="classpath:mybatis-config.xml" />
<!-- 使用别名 -->
<property name="typeAliasesPackage"
value="org.dreamtech.xxx.entity" />
<!-- 扫描mapper文件 -->
<property name="mapperLocations"
value="classpath:mapper/*.xml" />
</bean> <!-- 配置扫描dao接口包 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<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">
<!-- 开启SpringMVC注解模式 -->
<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>xxx</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 验证码 -->
<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>red</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>ACDEFGHJKMNPRSTUVWX23456789</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>Arial</param-value>
</init-param>
<init-param>
<param-name>kaptcha.image.width</param-name>
<param-value>135</param-value>
</init-param>
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>red</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>43</param-value>
</init-param>
<init-param>
<param-name>kaptcha.noise.color</param-name>
<param-value>black</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/Kaptcha</url-pattern>
</servlet-mapping>
<!-- 配置Spring -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-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<String, Object> login(HttpServletRequest request) {
String username = request.getParameter("username");
String password = request.getParameter("password");
Map<String, Object> modelMap = new HashMap<String, Object>();
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

所有测试完成!

上一篇:第n次搭建 SSM 框架


下一篇:使用Springboot快速搭建SSM框架