使用eclipse+maven搭建ssm框架 - 简书事先准备好系统环境 Window 10 JDK1.8 Eclipse Java EE IDE for Web Developers(Version: Neon Release...https://www.jianshu.com/p/f3c582edca2b

事先准备好系统环境

使用maven创建SSM框架

  1. 选择Maven Project

     

  2. 选择默认工作空间位置

     

  3. 选择web类型

     

  4. 填写GroupID、ArtifactID
    Group ID:相当于一个组织
    Artifact ID:相当于这个组织下的一个具体项目
    Packege:根据Group ID和Artifact ID生成一个默认的名称

     

  5. 创建出的maven项目如下图

     

     

    提示错误:

     


    解决办法:在eclipse中设置Server为Tomcat,注意JRE设置为安装的JDK的jre

     

    在工程上右键,查看工程属性,找到Java Build Path,添加Server Runtime为Tomcat

     

     


    点击Finish后,项目工程变成下图

  6. 在项目上点击右键,查看项目信息


    默认的Dynamic Web Module为2.3,使用Tomcat 8.5,需要修改为3.1
    修改方法:
    ① maven工程所在目录有个.settings文件夹(默认隐藏)下面有个文件org.eclipse.wst.common.project.facet.core.xml


    将内容改为:

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

② 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,点击之

⑤ 选择该项目进行更新,如果怕不能强制更新,可以勾选Force Update of Snapshots/Releases
⑥ 点击OK后更新maven项目,再观察项目属性,Module已经变为3.1

下载ssm框架所需的jar包

修改pom.xml内容为

<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>com.huyonghua</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>
        <!-- 添加Servlet支持 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- JSP标准标签库 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- 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>

        <!-- 日志相关包 -->
        <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>

保存后,可以看到相关jar包被下载至本地仓库

完善项目结构

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

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


右键查看项目属性,点击Deployment Assembly,移除test和target

Web Deployment Assembly是eclipse中的发布路径设置,DeployPath表示每个资源发布之后的文件路径。eclipse中使用tomcat使用启动web项目的流程是 java build path编译项目源代码生成的class文件放到buildpath的设置路径中,根据web deployment assembly将项目中的各个资源发布到设置的指定文件中

框架测试

  1. 创建项目中用的配置文件

     

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

srping-core.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(com.huyonghua.web..*)" />
    </aop:config>

        <!-- 导入其他配置文件 -->
    <import resource="spring-mybatis.xml" />
    
        <!-- 扫描service -->
    <context:component-scan base-package="com.huyonghua.service"></context:component-scan>
</beans>

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="com.huyonghua.web" />

    <!-- 注册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/test" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

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

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="com.huyonghua.domain" />
    </typeAliases>

</configuration>

配置web.xml启用spring容器

<?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">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
    <!-- Spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-core.xml</param-value>
    </context-param>
    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 添加对springmvc的支持 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>
  1. 数据库插入测试数据
    创建一个test数据库,并建一个userinfo的表,表结构如下

     

     

    插入测试数据

     

  2. 编写服务端代码

     

     

    User.java

package com.huyonghua.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;
    }
}

UserDao.java

package com.huyonghua.dao;

import com.huyonghua.domain.User;

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

UserService.java

package com.huyonghua.service;

import com.huyonghua.domain.User;

public interface UserService {
    public User findUserByName(String name);
}

UserServiceImpl.java

package com.huyonghua.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huyonghua.dao.UserDao;
import com.huyonghua.domain.User;
import com.huyonghua.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;
    @Override
    public User findUserByName(String name) {
        // TODO Auto-generated method stub
        return this.userDao.findByUsername(name);
    }
}

UserController.java

package com.huyonghua.web;


import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
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 com.huyonghua.domain.User;
import com.huyonghua.service.UserService;

/**
 * 用户控制器
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(User model, HttpSession session) {
        User user = userService.findUserByName(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;
        }
    }
}
  1. 编写客户端代码

     

     

    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="${pageContext.request.contextPath }/user/login.do" 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>

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>
  1. 发布项目到tomcat
    右键项目-->run as-->run on server

     

     

本文源码已发布到我的github仓库,欢迎大家Fork and Star!

git@github.com:goldfather008/ssm.git

问题

tomcat运行报错。The Tomcat server configuration at \Servers\Tomcat v7.0 Server at localhost-config is missing. Check the server for errors.
原因:可能不小心删除了Project Explorer下的Server
解决办法:Window-Preferences-Server-Server Runtime Environments重新关联就可以了

查询数据库时发现报错Invalid bound statement (not found)
原因:mybaits的配置文件与接口调用没有对应,一般情况是Mapepr.xml文件中nameapce没有和mapper接口发生映射,导致mybatis绑定失败,检查是否正确配置映射

tomcat在eclipse里面能正常启动,而在浏览器中访问http://localhost:8080/不能访问,且报404错误。同时其他项目页面也不能访问。
关闭eclipse里面的tomcat,在tomcat安装目录下双击startup.bat手动启动tomcat服务器。访问http://localhost:8080/能正常访问tomcat管理页面。
原因:eclipse将tomcat的项目发布目录(tomcat 目录中的webapp)重定向了,所以你会发现在tomcat安装目录下的webapp目录里面找不到你的项目文件。
解决办法:重新配置下tomcat服务器:
在eclipse中的server页面,双击tomcat服务,会看到如图所示的配置页面:

可以看到红圈中选择的是 Use workspace metadata(does not modify Tomcat installion)
如果该tomcat中部署了项目的话,这红圈中的选项会灰掉不能修改,要修改必须得先把tomcat中的部署的服务都移除。

通过右键单击tomcat服务器选择 Add and Remove,在弹出的对话框中移除已部署的项目。移除完确定后,将看到上面的选项面板部分可编辑了。
选择Use tomcat installation(Task control of Tomcat installation) 即选择tomcat的安装目录来作为项目的发布目录。
然后,下来四行,看到"Deploy Path"了没?它后面的值默认是"wtpwebapps",把它改成"webapps",也就是tomcat
中发布项目所在的文件夹名字。
修改后关掉该页面,保存配置。这样就将项目部署到了tomcat安装目录下的webapp

GitHub 加速计划 / ma / maven
36
0
下载
Maven: Apache Maven是一个开源的项目管理和构建工具,主要用于Java项目。适合需要自动化项目构建和依赖管理的开发者。特点包括约定优于配置、易于使用和社区驱动。
最近提交(Master分支:17 天前 )
2865dac1 - https://github.com/checkstyle/checkstyle/pull/17782 Co-authored-by: Vincent Potucek <vpotucek@me.com> 10 小时前
7872c6d8 Changes: * update Mimir to latest 0.8.1 version * update infusers as well * cache changes (see below) Cache strategy changes: * initial build: it is snowballing one cache when build is not about PR * full (rebuild itself + site with itself) and its build: it is snowballing cache differentiated by OS/JDK when build is not about PR Current problems: on unchanged POM (ie. new IT added), the dependencies ITs pull from Central will be cached by Mimir, but due "cache hit" the new cache will not get stored. Hence, Mimir caching was basically lost. Also, there was a mixup of caches from PRs and main branches. Finally, matrix jobs were competing for cache store. 2 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐