1)Windows 7 旗舰版

2)JDK 1.8.0_131

3)Eclipse Java EE IDE for Web Developers  Version: Neon.3 Release (4.7.3)

4)Tomcat 8.5

1、下载maven,配置maven环境变量。

maven的下载地址:http://maven.apache.org/download.cgi

eclipse+maven搭建ssm-LMLPHP

解压后放在D盘最好,因为我C盘安装的固态,所以我放在C盘了

eclipse+maven搭建ssm-LMLPHP

配置maven环境变量,

在环境变量中,新增系统变量名:MAVEN_HOME,变量值:C:\apache-maven-3.5.3C:\apache-maven-3.5.3

在Path中追加:%MAVEN_HOME%\bin;

在命令行窗口中输入:mvn –v,如果看见下图则说明maven安装配置完毕

eclipse+maven搭建ssm-LMLPHP

2、设置eclipse自带maven整合工具,在Preferences中找到Maven节点,观察User Settings项的设置是否正确

eclipse+maven搭建ssm-LMLPHP

点击Installations节点,添加maven runtime

eclipse+maven搭建ssm-LMLPHP

我的已经配置过了。所以显示名字重复错误。

3、创建maven项目,

eclipse+maven搭建ssm-LMLPHP

eclipse+maven搭建ssm-LMLPHP

eclipse+maven搭建ssm-LMLPHP

eclipse+maven搭建ssm-LMLPHP

创建出的maven项目如下图

eclipse+maven搭建ssm-LMLPHP

在eclipse中设置Server为Tomcat,注意JRE设置为安装的JDK的jre

eclipse+maven搭建ssm-LMLPHP

添加tomcat

eclipse+maven搭建ssm-LMLPHP

eclipse+maven搭建ssm-LMLPHP

eclipse+maven搭建ssm-LMLPHP

在项目上右键,查看项目信息

eclipse+maven搭建ssm-LMLPHP

默认的Dynamic Web Module为2.3,使用Tomcat 8.5,需要修改为3.1

修改方法:

① maven工程所在目录下org.eclipse.wst.common.project.facet.core.xml

eclipse+maven搭建ssm-LMLPHP

将下图的2.3改成3.1

 <installed facet="jst.web" version="2.3"/>

② maven工程下的web.xml文件修改为

<?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">
</web-app>

③ pom.xml文件中修改build节点,添加如下内容

<plugins>
       <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <configuration>
                     <source>1.8</source>
                     <target>1.8</target>
              </configuration>
       </plugin>
</plugins>

④ 修改后,在项目上右键,找到Maven属性下的Update Project,点击

eclipse+maven搭建ssm-LMLPHP

⑤ 选择该项目进行更新,如果怕不能强制更新,可以勾选Force Update of Snapshots/Releases

eclipse+maven搭建ssm-LMLPHP

⑥ 点击OK后更新maven项目,再观察项目属性,Module已经变为3.1

eclipse+maven搭建ssm-LMLPHP

4、下载ssm框架所需jar包

<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>cn.temptation</groupId>
    <artifactId>ssm</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ssm Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- Spring版本号 -->
        <spring.version>4.3.8.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-aop</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-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- AOP相关包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.0</version>
        </dependency>

        <!-- MyBatis相关包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- MySQL相关包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.20</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.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>

        <!-- 单元测试相关包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>ssm</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

5、完善项目结构

因为服务端maven项目的标准结构有四个子包:src/main/java、src/main/resources、src/test/java、src/test/resources,这里缺少了src/test/resources,所以手动补上。

在项目中新建Source Folder

创建src/test/resources目录后,工程如下图所示

eclipse+maven搭建ssm-LMLPHP

eclipse+maven搭建ssm-LMLPHP

6、具体文件代码

UserDao.java

package cn.temptation.dao;

import cn.temptation.domain.User;

public interface UserDao {
	  public abstract User findByUsername(String username);
}

 

UserMapper.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="cn.temptation.dao.UserDao">
    <select id="findByUsername" parameterType="string" resultType="User">
        SELECT * FROM userinfo WHERE username=#{username}
    </select>
</mapper>

User.java

package cn.temptation.domain;

public class User {

	  private Integer userid;
	    private String username;
	    private String password;

	    // 构造函数
	    public User() {
	        super();
	    }

	    public User(Integer userid, String username, String password) {
	        super();
	        this.userid = userid;
	        this.username = username;
	        this.password = password;
	    }

	    // 成员方法
	    public Integer getUserid() {
	        return userid;
	    }

	    public void setUserid(Integer userid) {
	        this.userid = userid;
	    }

	    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;
	    }
	}

UserController.java

package cn.temptation.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.temptation.dao.UserDao;
import cn.temptation.domain.User;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Resource
    private UserDao userDao;

    @RequestMapping("/view")
    public String view() {
        return "main/login";
    }

    @RequestMapping("/indexview")
    public String index() {
        return "main/index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(User model, HttpSession session) {
        User user = userDao.findByUsername(model.getUsername());

        if (user == null || !user.getPassword().equals(model.getPassword())) {
            return new ModelAndView("redirect:/login.jsp");
        } else {
            session.setAttribute("user", user);
            ModelAndView mav = new ModelAndView();
            mav.setViewName("index");
            return mav;
        }
    }
}

log4j.properties

#USE THIS SETTING FOR OUTPUT MYBATIS`s SQL ON THE CONSOLE
log4j.rootLogger=DEBUG, Console

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

 

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>
        <package name="cn.temptation.domain" />
    </typeAliases>
</configuration>
 

spring-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: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.xsd">

    <!-- 启动自动扫描 -->
    <context:component-scan base-package="cn.temptation.*" />

    <!-- 注册MVC注解驱动 -->
    <mvc:annotation-driven />

    <!-- 静态资源可访问的设置方式 -->
    <mvc:default-servlet-handler />

    <!-- 配置视图解析器,可以显式设置,也可以不设置,不设置会依据SpringMVC的默认设置 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 定义数据源Bean -->
    <!-- Druid -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/ssmtest" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <!-- 注册SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mappers.xml文件 -->
        <property name="mapperLocations" value="classpath:cn/temptation/dao/*.xml" />
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
    
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.temptation.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>

spring-tx.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:aop="http://www.springframework.org/schema/aop"
    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/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">

    <!-- 开启AOP注解扫描 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />

    <!-- 事务管理器,依赖于数据源 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 编写通知:对事务进行增强(通知),需要编写对切入点和具体执行事务细节 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <!--
                为切入点方法添加事务详情
                name:方法名,*表示任意方法名称
                propagation:设置传播行为
                isolation:设置隔离级别
                read-only:是否只读
            -->
            <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" rollback-for="Exception" />
            <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" rollback-for="Exception" />
            <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>
    
    <!-- 设置AOP,让Spring自动对目标生成代理,需要使用AspectJ表达式 -->
    <aop:config proxy-target-class="true">
        <!-- 切面:整合切入点和通知 -->
        <aop:advisor advice-ref="txAdvice" pointcut="within(cn.temptation.web..*)" />
    </aop:config>
</beans>

eclipse+maven搭建ssm-LMLPHP

web.xml

<?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">
</web-app>

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>主页</title>
</head>
<body>
<h3>欢迎,${user.username }</h3>
</body>
</html>

login.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>登录</title>
</head>
<body>
<form action="user/login" method="post">
<label>账号:</label>
<input type="text" id="txtUsername" name="username" placeholder="请输入账号" /><br/>
<label>密码:</label>
<input type="password" id="txtPassword" name="password" placeholder="请输入密码" /><br/>
<input type="submit" value="提交" />
<input type="reset" value="重置" />
</form>
</body>
</html>

十月 04, 2018 9:32:48 下午 org.apache.tomcat.util.digester.SetPropertiesRule begin
警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:SSML' did not find a matching property.
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server version:        Apache Tomcat/8.5.29
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server built:          Mar 5 2018 13:11:12 UTC
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server number:         8.5.29.0
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS Name:               Windows 7
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS Version:            6.1
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Architecture:          amd64
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Java Home:             C:\Program Files\Java\jre1.8.0_161
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM Version:           1.8.0_161-b12
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM Vendor:            Oracle Corporation
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_BASE:         E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_HOME:         D:\apache-tomcat-8.5.29
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.base=E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.home=D:\apache-tomcat-8.5.29
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dwtp.deploy=E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Djava.endorsed.dirs=D:\apache-tomcat-8.5.29\endorsed
十月 04, 2018 9:32:48 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dfile.encoding=UTF-8
十月 04, 2018 9:32:48 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_161\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_161/bin/server;C:/Program Files/Java/jre1.8.0_161/bin;C:/Program Files/Java/jre1.8.0_161/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Java\jdk1.8.0_161\bin;C:\Program Files\Java\jre1.8.0_161\bin;C:\apache-maven-3.5.3\bin;C:\Users\Administrator\eclipse\jee-oxygen\eclipse;;.]
十月 04, 2018 9:32:48 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-nio-8080"]
十月 04, 2018 9:32:49 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
十月 04, 2018 9:32:49 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["ajp-nio-8009"]
十月 04, 2018 9:32:49 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
十月 04, 2018 9:32:49 下午 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 1249 ms
十月 04, 2018 9:32:49 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Catalina]
十月 04, 2018 9:32:49 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.5.29
十月 04, 2018 9:32:53 下午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
十月 04, 2018 9:32:56 下午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
十月 04, 2018 9:32:56 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-nio-8080"]
十月 04, 2018 9:32:56 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["ajp-nio-8009"]
十月 04, 2018 9:32:56 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in 6730 ms

eclipse+maven搭建ssm-LMLPHP

10-04 21:41