【超详细demo编写过程】idea中使用maven多模块结合ssm框架+mysql

写这篇文章的原因

      这段时间自己也正是在学习这块,网上找了很多都没有详细的例子,然后基础还不够扎实的原因,花了不少时间才最后跑起来,所以写这篇文章,希望能够帮到入门的兄弟们,希望可以少走一些弯路,当然也有可能看这篇文章的时候就已经走上了弯路(开个玩笑)。同时也希望有大神看到我的这篇文章,能指出不足之处,本人也非常渴望进步以及学到新的东西和思想!


demo需求

       这个demo主要的业务逻辑就是:用户通过index.jsp进入登录界面,可以注册会员,会员登录后可以对论文进行简单的增删改查。



开发工具      

  • IntelliJ IDEA Ultimate 2018.1.3.x
  • Apache-tomcat-9.0.81
  • JDK 1.8.0_172
  • MySQL 5.7.22
  • Maven 3.3.9

工程结构

       首先说明一下我对多模块的项目的理解:

              1.多模块是通过各个模块的pom.xml文件联系起来的,继承或依赖关系在pom.xml文件里体现;

              2.多个模块中有一个父模块,其他为它的子模块,父模块的pom.xml负责管理所有jar包;

              3.web是最“靠外”的一个模块,modle是最“靠内”的一个模块,所以在pom文件的依赖中,web是需要依赖其他的一些特定的模块的,但是modle不需要,相反,很多模块需要依赖他。


最终完成后的工程结构如图:




IDEA+Maven搭建项目骨架

新建数据库:

    由于数据库内容设计的非常简单,用的是以前随便做的数据库表,在这里就只直接贴图给大家看看是什么样的了。



大家创建好数据库之后再开始下面的步骤吧~


新建Maven项目: 

点击File -> New -> Project ->Empty Project->next



确定后,继续点击File-->new ,如下图,新建一个module



这里因为是要把他作为父模块,没有什么其他特别的操作,所以选择quickstart




这里选择自己的maven




再点击next会需要等一下,maven会自动创建wzy.parent的内部结构

然后再右键wzy.parent,选择moudle,以同样的方式创建wzy.modle,需要注意的是,下图需要按照步骤设置,不然多模块看起来结构会不清晰。



还有下面这一处也要改成wzy.modle


点击next会生成wzy.modle模块。

接下来以wzy.modle一样的顺序,创建wzy.bll、wzy.commons、wzy.dal、wzy.factory。


创建好这些模块之后,我们开始创建wzy.web模块,创建web和其他的不一样,如下图所示(注意:此处不要错选成上面的cocoom-22-archetype-webapp



所有模块创建完之后需要做下列操作,设置各个模块里面的一些文件夹的属性,如下



设置好之后,每一个模块里面需要建的类及相关文件及代码如下:

wzy.parent:


parent的pom.xml如下

<?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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wzy</groupId>
  <artifactId>wzy.parent</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>
  <modules>
    <module>../wzy.modle</module>
    <module>../wzy.web</module>
    <module>../wzy.factory</module>
    <module>../wzy.dal</module>
    <module>../wzy.commons</module>
    <module>../wzy.bll</module>
  </modules>

  <name>wzy.parent</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring.version>5.0.3.RELEASE</spring.version>
    <mybatis.version>3.4.4</mybatis.version>
  </properties>


  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- 第一部分:Spring 配置-->
    <!-- Spring core -->
    <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-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- Spring DAO -->
    <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>
    <!-- Spring mvc -->
    <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>
    <!-- 第二部分:Servlet web -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.4</version>
    </dependency>
    <!-- 第三部分:数据库和mybatis -->
    <!-- 数据库 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!-- 数据库连接池 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <!-- MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis-spring整合包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- 第四部分:日志 -->
    <!-- 实现slf4j接口并整合 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.1</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>



wzy.modle:


Paper:

package com.wzy.modle;

public class Paper {
    private long paperId;
    private String paperName;
    private int paperNum;
    private String paperDetail;
    //实体类
    public long getPaperId() {
        return paperId;
    }

    public void setPaperId(long paperId) {
        this.paperId = paperId;
    }

    public String getPaperName() {
        return paperName;
    }

    public void setPaperName(String paperName) {
        this.paperName = paperName;
    }

    public int getPaperNum() {
        return paperNum;
    }

    public void setPaperNum(int paperNum) {
        this.paperNum = paperNum;
    }

    public String getPaperDetail() {
        return paperDetail;
    }

    public void setPaperDetail(String paperDetail) {
        this.paperDetail = paperDetail;
    }

}

User:

package com.wzy.modle;

public class User {
    private  int id;
    private  String name;
    private String userName;
    private String passWord;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

Wzy.factory:


PaperFactory:

package com.wzy.factory;

import java.util.List;
import com.wzy.modle.Paple;

public interface PaperFactory {
    int addPaper(Paper paper);

    int deletePaperById(long id);

    int updatePaper(Paper paper);

    Paper queryById(long id);

    List<Paper> queryAllPaper();
}

这里我们import  Paper 的时候还是会报错,是因为这个module没有依赖wzy.module这个module,所以他找不到modle包,因此找不到Paper类,所以我们需要在Factory的pom文件中加入与modle的依赖,如下:


UserFactory :



wzy.dal:



paperDal:

package com.wzy.dal;

import java.util.List;
import com.wzy.modle.Paper;

public interface PaperDal {
    int addPaper(Paper paper);

    int deletePaperById(long id);

    int updatePaper(Paper paper);

    Paper queryById(long id);

    List<Paper> queryAllPaper();
}

这里会报和factory一样的错误,按照一样的方法去解决就好了。

UserDal:

package com.wzy.dal;

import com.wzy.modle.User;

public interface UserDal {
    int addUser(User user);
    // 用户登录
    User userSubmit(String username,String password);
    //根据账号查找所有信息
    User findByUsername(String username);
}

PaperDalImpl:@Service,这个注解加上去是配合相关配置文件中

<context:component-scan base-package="XXX"/>
这一段进行自动注入spring容器里面。如果想重写父类的方法,比如toString()方法的话,在方法前面加上@Override, 系统可以帮你检查方法的正确性,@Autowired 这个注解就是 spring可以自动帮你把bean里面引用的对象的setter/getter方法省略,它会自动帮你set/get
package com.wzy.dal.impl;

import com.wzy.dal.PaperDal;
import com.wzy.modle.Paper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wzy.factory.PaperFactory;

import java.util.List;

@Service
public class PaperDalImpl implements PaperDal {
    @Autowired
    private PaperFactory paperFactory;

    @Override
    public int addPaper(Paper paper) {
        return paperFactory.addPaper(paper);
    }

    @Override
    public int deletePaperById(long id) {
        return paperFactory.deletePaperById(id);
    }

    @Override
    public int updatePaper(Paper paper) {
        return paperFactory.updatePaper(paper);
    }

    @Override
    public Paper queryById(long id) {
        return paperFactory.queryById(id);
    }

    @Override
    public List<Paper> queryAllPaper() {
        return paperFactory.queryAllPaper();
    }

}
这里也会报一个错误,原因是没有依赖wzy.factory这个module,找不到PaperFactory,所以会报错,解决办法也是在POM文件里面加dependency,让本身这个module依赖wzy.factory。


UserDalImpl:

package com.wzy.dal.impl;

import com.wzy.dal.UserDal;
import com.wzy.factory.UserFactory;
import com.wzy.modle.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserDalImpl implements UserDal {
    @Autowired
    private UserFactory userFactory;
    private User user;

    @Override
    //这个标签如果是在没有用implements去实现userdal的情况下的话,就会报错
    public int addUser(User user) {
        return userFactory.addUser(user);
    }

    @Override
    public User userSubmit(String username,String password){
        User user = userFactory.findByUsername(username);
        if(user != null && user.getPassWord().equals(password)){

            return user;
        }
        return null;
    }
    @Override
    public User findByUsername(String username)
    {
        return userFactory.findByUsername(username);
    }

}


wzy.bll:



PaperBll:      这里使用RequestMapping(“/paper”),告诉页面“我PaperBll的代号就是   /paper,你们有事就叫我这个名字,我下面的方法也有自己的名字,你们要用的时候就叫我给他们取的名字就好了”。 controller 这个是告诉扫描器,你应该要来扫描我这个包。被Controller标记的类就是一个控制器,这个类中的方法,就是相应的动作。

package com.wzy.bll;



import com.wzy.dal.PaperDal;
import com.wzy.modle.Paper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
//控制器,负责接收页面请求,转发和处理。

@Controller
@RequestMapping("/paper")
public class PaperBll {
    @Autowired
    private PaperDal paperDal;

    @RequestMapping("/allPaper")
    public String list(Model model) {
        List<Paper> list = paperDal.queryAllPaper();
        model.addAttribute("list", list);
        return "allPaper";
    }

    @RequestMapping("toAddPaper")
    public String toAddPaper() {
        return "addPaper";
    }

    @RequestMapping("/addPaper")
    public String addPaper(Paper paper) {
        paperDal.addPaper(paper);
        return "redirect:/paper/allPaper";
    }

    @RequestMapping("/del/{paperId}")
    public String deletePaper(@PathVariable("paperId") Long id) {
        paperDal.deletePaperById(id);
        return "redirect:/paper/allPaper";
    }

    @RequestMapping("toUpdatePaper")
    public String toUpdatePaper(Model model, Long id) {
        model.addAttribute("paper", paperDal.queryById(id));
        return "updatePaper";
    }

    @RequestMapping("/updatePaper")
    public String updatePaper(Model model, Paper paper) {
        paperDal.updatePaper(paper);
        paper = paperDal.queryById(paper.getPaperId());
        model.addAttribute("paper", paper);
        return "redirect:/paper/allPaper";
    }
}


这里的报错原因是和前几个一样的,都是没有添加依赖。


UserBll:

package com.wzy.bll;

import com.wzy.dal.UserDal;
import com.wzy.modle.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpSession;

//控制器,负责接收页面请求,转发和处理。
@Controller
@RequestMapping("/user")

//这里用了@SessionAttributes,可以直接把model中的user(也就key)放入其中
//这样保证了session中存在user这个对象
@SessionAttributes("user")
public class UserBll {

    @Autowired
    private UserDal userDal;

    //正常访问login页面
    @RequestMapping("toLogin")
    public String login(){
        return "login";
    }

    //表单提交过来的路径
    @RequestMapping("userSubmit")
    public String userSubmit(User user, Model model){
        //调用service方法
        user = userDal.userSubmit(user.getUserName(),user.getPassWord());
        //若有user则添加到model里并且跳转到成功页面
        if(user != null){
            model.addAttribute("user",user);
            return "allPaper";
        }
        return "login";
    }
    /*@RequestMapping("/allPaper")
    //定义一个handelRequest方法映射/allPaper访问
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //用allPaper访问地址实例化一个ModelAndView对象
        ModelAndView mav = new ModelAndView("allPaper");
        //注入信息
        mav.addObject("message", "Hello Spring MVC");
        return mav;
    }
    @RequestMapping("/jump")
    public ModelAndView jump() {
        //redirect:/allPaper表示客户端跳转
        ModelAndView mav = new ModelAndView("redirect:/allPaper");
        return mav;
    }*/

/*
    @RequestMapping("/allPaper")
    //"/check"的访问映射方法需要接受一个HttpSession类的参数
    public ModelAndView check(HttpSession session) {
        //i的值等于session中count变量的值
        Integer i = (Integer)session.getAttribute("count");
        if(i==null)
            i=0;
        i++;
        //将自增后的i重新赋值给count
        session.setAttribute("count", i);

        ModelAndView mav = new ModelAndView("allPaper");
        return mav;
    }
*/

    @RequestMapping("addUser")
    public String addUser(User user) {
        userDal.addUser(user);
        return "redirect:/user/toLogin";
    }
    //注册用户
    @RequestMapping("toUserRegister")
    public String userRegister(){
        return "userRegister";
    }

    //测试超链接跳转到另一个页面是否可以取到session值
    @RequestMapping("/anotherpage")
    public String hrefpage(){

        return "anotherpage";
    }

    //注销方法
    @RequestMapping("/outLogin")
    public String outLogin(HttpSession session){
        //通过session.invalidata()方法来注销当前的session
        session.invalidate();
        return "login";
    }
}


    到这里除了wzy.web的每一个module里面的基本内容就全部写完了,值得注意的是,除了web和parent的pom文件,其他的怕pom文件里面的的packageing  都是  jar,而web 的为war, parent 的为 pom


wzy.web:

    这里要单独写,是因为涉及到配置文件,涉及到网页,我先全部贴出来,其中我碰到的问题或者我觉得可能会出问题的我挑出来和大家分享一下。

    结构还是如下图所示(没有自动创建的文件夹或文件需要自己手动创建):


下面我们开始写每一个配置文件和网页的代码,写的过程中也会碰到没有依赖的问题,解决办法和先前一样,加依赖就好啦。

PaperMapper.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.wzy.factory.PaperFactory">
    <resultMap type="Paper" id="paperResultMap" >
        <id property="paperId" column="paper_id"/>
        <result property="paperName" column="name"/>
        <result property="paperNum" column="number"/>
        <result property="paperDetail" column="detail"/>
    </resultMap>
    <insert id="addPaper" parameterType="Paper">
        INSERT INTO paper(paper_id,name,number,detail) VALUE (#{paperId},#{paperName}, #{paperNum}, #{paperDetail})
    </insert>

    <delete id="deletePaperById" parameterType="long">
        DELETE FROM paper WHERE paper_id=#{paperID}
    </delete>

    <update id="updatePaper" parameterType="Paper">
        UPDATE paper
        SET NAME = #{paperName},NUMBER = #{paperNum},detail = #{paperDetail}
        WHERE  paper_id = #{paperId}
    </update>

    <select id="queryById" resultType="Paper" parameterType="long">
        SELECT paper_id,name,number,detail
        FROM paper
        WHERE paper_id=#{paperId}
    </select>
    <select id="queryAllPaper" resultMap="paperResultMap">
        SELECT paper_id,name,number,detail
        FROM paper
    </select>

</mapper>


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.wzy.factory.UserFactory">
    <resultMap type="User" id="userResultMap" >
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="userName" column="username"/>
        <result property="passWord" column="password"/>
    </resultMap>
    <insert id="addUser" parameterType="User">
        INSERT INTO t_user(id,name,username,password) VALUE (#{id},#{name}, #{userName}, #{passWord})
    </insert>

    <!-- 目的:为DAO接口方法提供sql语句配置 -->
    <!-- 查询用户和密码进行登录 -->
    <select id="findByUsername" resultType="User" parameterType="String">
        select * from t_user where username = #{userName}
    </select>

</mapper>


spring-dal.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">
    <!-- 扫描service包下所有使用注解的类型 -->

    <!-- 4.配置扫描dal接口包,动态实现Dao接口,注入到spring容器中-->
    <!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!– 注入sqlSessionFactory –>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!– 给出需要扫描dal接口包 –>
        <property name="basePackage" value="com.wzy.dal"/>
    </bean>-->
    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.wzy.dal" />
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>


spring-factory.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">
    <!-- 配置整合mybatis过程 -->
    <!-- 1.配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 2.数据库连接池 -->
    <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}"/>

        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!-- 3.配置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"/>
        <!-- 扫描pojo包 使用别名 -->
        <property name="typeAliasesPackage" value="com.wzy.modle"/>
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.wzy.factory"/>
    </bean>
</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-3.0.xsd">
    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解模式 -->
    <!-- 简化配置:
        (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
        (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
    -->
    <mvc:annotation-driven />

    <!-- 2.静态资源默认servlet配置
        (1)加入对静态资源的处理:js,gif,png
        (2)允许使用"/"做整体映射
     -->
    <mvc:default-servlet-handler/>

    <!-- 3.配置jsp 显示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 4.扫描web相关的bean -->
    <!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!– 注入sqlSessionFactory –>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!– 给出需要扫描bll包 –>
        <property name="basePackage" value="com.wzy.bll"/>
    </bean>-->
    <context:component-scan base-package="com.wzy.bll"></context:component-scan>
</beans>


jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/wzy?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=Wzy,525110


log4j.properties:

log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n


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" />

        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>


注意!!!:在spring-dal.xml里面,下面这一段会报错:

<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />

原因是因为web.xml里面还没有配置springmvc需要加载的配置文件,所以这里默认是找不到这个ref的。将web.xml修改如下:

web.xml:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<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>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置springMVC需要加载的配置文件
        spring-dao.xml,spring-service.xml,spring-mvc.xml
        Mybatis - > spring -> springmvc
     -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-*.xml</param-value>
    </init-param>

  </servlet>
  <!-- 加载spring的xml配置文件到 spring的上下文容器中 -->
  <!--    <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring/spring-*.xml</param-value>
      </context-param>-->
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <!-- 默认匹配所有的请求 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>
      org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <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>
</web-app>


好了,到这里我们目前所需要的配置文件已经全部集齐了,如果没有其他的报错,现在开始就可以写我们的页面了。页面代码如下(页面写的很简陋,主要就是体现一下功能):

addPaper.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2018/4/7
  Time: 16:45
  To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<html>
<head>
    <title>新增论文</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于SSM框架的管理系统:简单实现增、删、改、查。
                </h1>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增论文</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="" name="userForm">
        论文名称:<input type="text" name="paperName"><br><br><br>
        论文数量:<input type="text" name="paperNum"><br><br><br>
        论文详情:<input type="text" name="paperDetail"><br><br><br>
        <input type="button" value="添加" onclick="addPaper()">
    </form>

    <script type="text/javascript">
        function addPaper() {
            var form = document.forms[0];
            form.action = "<%=basePath %>paper/addPaper";
            form.method = "post";
            form.submit();
        }
    </script>
</div>
</body>
</html>

allPaper.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2018/4/6
  Time: 16:57
  To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% String appPath = request.getContextPath(); %>
<html>
<head>
    <title>Paper列表</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%--<div>
    <strong> welcome,${sessionScope.user.username}! </strong>
</div>--%>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于SSM框架的管理系统:简单实现增、删、改、查。
                </h1>
               <%-- session被访问的次数为:${count}--%>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>论文列表 —— 显示所有论文</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${path}/paper/toAddPaper">新增</a>
        </div>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>论文编号</th>
                    <th>论文名字</th>
                    <th>论文数量</th>
                    <th>论文详情</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="paper" items="${requestScope.get('list')}" varStatus="status">
                    <tr>
                        <td>${paper.paperId}</td>
                        <td>${paper.paperName}</td>
                        <td>${paper.paperNum}</td>
                        <td>${paper.paperDetail}</td>
                        <td>
                            <a href="${path}/paper/toUpdatePaper?id=${paper.paperId}">更改</a> |
                            <a href="<%=appPath%>/paper/del/${paper.paperId}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

login.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2018/4/7
  Time: 16:45
  To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>用户登录</title>
</head>
<body>

<form action="" name="userLoginForm">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input id="username" name="userName" type="text"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input id="password" name="passWord" type="password"></td>
        </tr>

    </table>
    <input type="submit" value="登录" onclick="userSubmit()">
</form>
        <a href="${path }/user/toUserRegister">点击进入注册页面</a>
<script type="text/javascript">
    function userSubmit(){
        var form = document.forms[0];
        form.action = "<%=basePath %>user/userSubmit";
        form.method = "post";
        form.submit();
    }
</script>
</body>
</html>

updatePaper.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<html>
<head>
    <title>修改论文</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于SSM框架的管理系统:简单实现增、删、改、查。
                </h1>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>修改论文</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="" name="userForm">
        <input type="hidden" name="paperId" value="${paper.paperId}"/>
        论文名称:<input type="text" name="paperName" value="${paper.paperName}"/>
        论文数量:<input type="text" name="paperNum" value="${paper.paperNum}"/>
        论文详情:<input type="text" name="paperDetail" value="${paper.paperDetail }"/>
        <input type="button" value="提交" onclick="updatePaper()"/>
    </form>
    <script type="text/javascript">
        function updatePaper() {
            var form = document.forms[0];
            form.action = "<%=basePath %>paper/updatePaper";
            form.method = "post";
            form.submit();
        }
    </script>
</div>
</body>
</html>

userRegister.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2018/4/7
  Time: 16:45
  To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<html>
<head>
    <title>新增论文</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    请输入您想创建的用户名和密码
                </h1>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>创建用户</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="" name="registerForm">
        <table>
            <tr>
                <td>用户id:</td>
                <td><input id="id" name="id" type="text"></td>
            </tr>
            <tr>
                <td>用户名:</td>
                <td><input id="name" name="name" type="text"></td>
            </tr>
            <tr>
                <td>登录名:</td>
                <td><input id="username" name="userName" type="text"></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input id="password" name="passWord" type="password"></td>
            </tr>
        </table>
        <input type="button" value="创建" onclick="addUser()">
    </form>

    <script type="text/javascript">
        function addUser() {
            var form = document.forms[0];
            form.action = "<%=basePath %>user/addUser";
            form.method = "post";
            form.submit();
        }
    </script>
</div>
</body>
</html>

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    pageContext.setAttribute("path", request.getContextPath());
%>
<!DOCTYPE HTML>
<html>
<head>
    <title>首页</title>
    <style type="text/css">
        a {
            text-decoration: none;
            color: black;
            font-size: 18px;
        }

        h3 {
            width: 180px;
            height: 38px;
            margin: 100px auto;
            text-align: center;
            line-height: 38px;
            background: deepskyblue;
            border-radius: 4px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于SSM框架的管理系统:简单实现增、删、改、查。
                </h1>
            </div>
        </div>
    </div>
</div>
<br><br>
<h3>
    <a href="${path }/user/toLogin">点击进入登陆页面</a>
</h3>
</body>
</html>


写完之后就可以开始部署在tomcat上跑啦!


部署tomcat

流程如下:




选择后点击应用,然后点击deployment,如下图



选择war exploded, 这里我们的wzy.web的pom文件里面早就把packageing设置为war了。

再直接点击应用,然后切回server



再点击应用,然后点击OK,这样,我们的程序就部署在tomcat上面了。

接下来咱们只要运行,就可以顺利跑起来啦。



感悟

    刚开始接触这样一个多模块的框架,最大的问题出现在各个模块的关系没有理清楚,导致逻辑混乱,pom文件之间的依赖漏加,再加上自己本身对于ssm的理解不够深入,促使自己没有办法及时准确的找到问题所在,一开始有点急,后来慢慢沉下心捋了几遍,才发现问题所在,期间也多亏了网上各位大神的一些分享给了我一些方向和灵感!分享万岁!!!这也是我写这篇文章的原因,希望有朋友在初涉及这一块的时候能够少走一点弯路,或者说我的文章能够稍微给其一些启发,那这就写的有意义了。这里也贴一下对我有帮助的两篇文章的链接,写的很详细,我一步步跟着来才明白的。

1.(超详细、适合新手入门)IDEA+Maven 整合SSM框架实现简单的增删改查

    https://blog.csdn.net/khxu666/article/details/79851070#comments

2.  Intellij IDEA 2016学习系列之(一)创建maven 多模块项目

    https://blog.csdn.net/liudongdong0909/article/details/52270604

    另外,做开发真的是一个细致活,逻辑要理清楚,很多细小的地方也特别需要注意,并不是所有的问题IDE工具都会报错!!并不是所有的问题IDE工具都会报错!!并不是所有的问题IDE工具都会报错!!  重要的事情说三遍!IDE工具不报错的问题才是真正难找的问题!所以细心真的很重要,可以避免很多不必要的问题。

    最后,所有东西其实都是一个道理,所以基础很重要,基础好的话,理解这个应该也不用到处找文章看,自己找个demo下载下来,走一遍就明白了,说到底还是活到老学到老,打好基础最重要!加油!各位一起学习的朋友们!

展开阅读全文

没有更多推荐了,返回首页