Maven + Spring + SpringMVC + MyBatis + MySQL框架搭建Java Web工程

参考:

Java框架搭建-Maven、Mybatis、Spring MVC整合搭建

SSM框架——Spring+SpringMVC+Mybatis的搭建教程

一 下载并安装Eclipse-jee

二 新建Maven项目

  1. 菜单File -> New -> Maven Project
  2. 点击Next ,在Archetype 列表中选择maven-archetype-webapp
  3. 点击Next ,在Group Id 中填入包名,此处为com.vitaArtifact Id 中填入工程名,此处为FirstFinish
  4. 新建项目后,会看到报错,这是因为build path 没有引入java ee
    • 设置build path
      • 右键项目,Build Path -> Configure Build Path... -> Libraries
      • 双击JRE System Library 以编辑,选择Alternate JREWorkspace default JRE ,这里选择Alternate JREFinish

三 项目配置文件配置

1 配置pom.xml

    4.0.0
    com.vita
    First
    war
    1.0-SNAPSHOT
    First Maven Webapp
    http://maven.apache.org

    
        
        4.0.5.RELEASE
        
        3.2.1
        
        1.6.6
        1.2.12
        5.1.35
    

    
        
        

        
        
            org.springframework
            spring-core
            ${spring.version}
        
        
            org.springframework
            spring-oxm
            ${spring.version}
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-context-support
            ${spring.version}
        
        
            org.springframework
            spring-aop
            ${spring.version}
        
        
            org.springframework
            spring-aspects
            ${spring.version}
        
        
            org.springframework
            spring-tx
            ${spring.version}
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        
            org.springframework
            spring-web
            ${spring.version}
        
        
        
            org.springframework
            spring-test
            ${spring.version}
            test
        

        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        
        
            org.springframework
            spring-web
            ${spring.version}
        

        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        

        
        
            commons-dbcp
            commons-dbcp
            1.2.2
        

        
        
            com.alibaba
            druid
            0.2.23
        

        
        
            com.alibaba
            fastjson
            1.1.41
        

        
        
            log4j
            log4j
            ${log4j.version}
        
        
            org.slf4j
            slf4j-api
            ${slf4j.version}
        
        
            org.slf4j
            slf4j-log4j12
            ${slf4j.version}
        
        
            ch.qos.logback
            logback-classic
            1.1.2
        
        
            ch.qos.logback
            logback-core
            1.1.2
        
        
            org.logback-extensions
            logback-ext-spring
            0.1.1
        

        
        
            org.codehaus.jackson
            jackson-mapper-asl
            1.9.13
        

        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
        
            commons-io
            commons-io
            2.4
        
        
            commons-codec
            commons-codec
            1.9
        

        
        
            org.mybatis
            mybatis
            ${mybatis.version}
        

        
        
            org.mybatis
            mybatis-spring
            1.2.2
        
        
        
            javax.servlet
            javax.servlet-api
            3.0.1
        
        
            javax.servlet.jsp
            javax.servlet.jsp-api
            2.3.2-b01
        
        
        
            javax.servlet
            jstl
            1.2
        
        
        
            junit
            junit
            3.8.1
            test
        
    
    
        First
    

2 其他配置文件

以下四个配置文件(jdbc.properties, log4j.properties, spring-mvc.xml, spring-mybatis.xml)都创建在Java Resources -> src/main/resources文件夹下

  1. jdbc.properties

    driver=com.mysql.jdbc.Driver
    # test为数据库名
    url=jdbc:mysql://localhost:3306/test
    # 数据库访问用户名
    username=root
    # 数据库访问密码,如无密码则不填
    password=
    # 定义初始连接数
    initialSize=1
    # 定义最大连接数
    maxActive=20
    # 定义最大空闲
    maxIdle=20
    # 定义最小空闲
    minIdle=1
    # 定义最长等待时间
    maxWait=60000
    
  2. log4j.properties

    ### set log levels ###
    #log4j.rootLogger = debug , stdout , D , E
    log4j.rootLogger = debug , stdout , D
    
    ###  output to the console ###
    log4j.appender.stdout = org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target = System.out
    log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
    #log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
    log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
    
    ### Output to the log file ###
    log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/log.log
    log4j.appender.D.Append = true
    log4j.appender.D.Threshold = DEBUG 
    log4j.appender.D.layout = org.apache.log4j.PatternLayout
    log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
    
    ### Save exception information to separate file ###
    log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/error.log 
    log4j.appender.D.Append = true
    log4j.appender.D.Threshold = ERROR 
    log4j.appender.D.layout = org.apache.log4j.PatternLayout
    log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
    
  3. spring-mvc.xml ,注意包名,当前包名为com.vita

    
    
     
     
    
     
     
         
         
         
     
    
     
     
         
             
                 text/html;charset=UTF-8
             
         
     
     
     
         
             
                  
             
         
     
     
     
         
         
         
     
    
     
     
         
         
         
         
         
         
     
    
    
    
  4. spring-mybatis.xml ,注意包名,当前包名为com.vita

    
    
     
     
     
     
         
     
    
     
         
         
         
         
         
         
         
         
         
         
         
         
         
         
     
    
     
     
         
         
         
     
    
     
     
         
         
     
    
     
     
         
     
    
    
    

四 数据库代码自动生成

  1. 建库,建表,当前使用MySQL,建库test ,建表user

  2. 下载包

    mybatis-3.4.5.jar ,

    mybatis-generator-core-1.3.6.jar (包含在mybatis-generator-core-1.3.6.zip 中),

    mysql-connector-java-5.1.39-bin.jar (包含在mysql-connector-java-5.1.45.zip 中)

    工程中新建一个文件夹存放这些包,此处在工程根目录下建立generate 文件(文件名自取)以存放

  3. 在上一步骤中所建目录下(此处为generate ),新建文件generatorConfig.xml ,用以自动生成代码,如下:

        
    
    
     
     
     
         
             
             
             
         
         
         
         
         
             
         
         
         
             
             
         
         
         
             
         
         
         
             
         
         
         

    注意 中的包的版本号,对应下载包的版本,以及jdbcConnection 标签中的数据库参数设置

  4. 该目录下执行,生成代码

    java -jar mybatis-generator-core-1.3.6.jar -configfile generatorConfig.xml -overwrite
    

    注意mybatis-generator-core 包的版本,对应下载包的版本

    备注:代码自动生成这里通过命令行的方式,也可以通过eclipse的插件方式生成

    命令执行前应在目录下新建src 文件夹,否则执行时会提示找不到src 路径,

    执行后,刷新工程,当前目录下的srcgenerate\src)文件夹中会生成对应代码文件:

    com/vita/dao/UserMapper.java ,

    com/vita/domain/User.java ,

    com/vita/mapping/UserMapper.xml

五 编写代码

  1. Java Resources -> src/main/java 下新建包:com.vita.controller , com.vita.dao , com.vita.domain , com.vita.mapping , com.vita.service , com.vita.service.impl

  2. 将前面自动生成的代码文件复制到对应包下

  3. com.vita.service 下新建接口IUserService.java

    package com.vita.service;
    
    import com.vita.domain.User;
    
    public interface IUserService {
    
     public User getUserById(int id);
     
    }
    
  4. com.vita.service.impl 下新建IUserService 的实现类UserServiceImpl.java

    注意:添加@Service 注解,否则不被识别

    package com.vita.service.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.vita.dao.IUserDao;
    import com.vita.domain.User;
    import com.vita.service.IUserService;
    
    @Service
    public class UserServiceImpl implements IUserService {
     
     @Autowired
     private IUserDao userDao;
    
     public User getUserById(int id) {
         return userDao.selectByPrimaryKey(id);
     }
    
    }
    
  5. com.vita.controller 下新建UserController.java 控制器:

    注意:添加@Controller 注解,否则不被识别

    package com.vita.controller;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import com.vita.domain.User;
    import com.vita.service.impl.UserServiceImpl;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
     public UserController() {
         System.out.println("UserController");
     }
    
     @Resource
     private UserServiceImpl userService;
    
     @RequestMapping(value = "/showUser", method = RequestMethod.GET)
     public String toIndex(HttpServletRequest request, Model model) {
         System.out.println("UserController showUser");
         int id = Integer.parseInt(request.getParameter("id"));
         User user = userService.getUserById(id);
         System.out.println("user: " + user);
    //       request.setAttribute("user", user);
         model.addAttribute("user", user);
         return "showUser";
     }
    }
    
  6. Deployed Resources -> webapp/WEB-INF 目录下新建文件夹jsp (文件夹名自取),用以存放返回的页面,jsp 目录下新建showUser.jsp

    <%@ page isELIgnored="false" language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8" import="java.util.*,com.vita.domain.*"%>
    
    
    
    
    Title
    
    
     ${user.name}
     ${user.email}
    
    
    
  7. web.xml 配置如下:

    
    
    
     Archetype Created Web Application
    
     
         log4jConfigLocation
         classpath:log4j.properties
         加载日志文件
     
     
     
     
         contextConfigLocation
         classpath:spring-mybatis.xml
     
     
     
     
         encodingFilter
         org.springframework.web.filter.CharacterEncodingFilter
         
             encoding
             UTF-8
         
     
     
         encodingFilter
         /*
     
     
     
         org.springframework.web.util.Log4jConfigListener
     
     
     
     
         org.springframework.web.context.ContextLoaderListener
     
     
     
         org.springframework.web.util.IntrospectorCleanupListener
     
    
     
     
         SpringMVC
         org.springframework.web.servlet.DispatcherServlet
         
             contextConfigLocation
             classpath:spring-mvc.xml
         
         1
     
     
         SpringMVC
         
         /
     
     
     
     
         /index.jsp
     
    
    

六 结束

到此,demo工程搭建结束,Eclipse中启动Tomcat Server,即可访问:

例:http://localhost:8080/First/user/showUser?id=2


错误记录

web.xml 报错The content of element type "web-app" must match ...
  • 错误详情:The content of element type "web-app" must match "(icon?,display-name?,description?,distributable?,context-param*,filter*,filter-mapping*,listener*,servlet*,servlet-mapping*,session-config?,mime-mapping*,welcome-file-list?,error-page*,taglib*,resource-env-ref*,resource-ref*,security-constraint*,login-config?,security-role*,env-entry*,ejb-ref*,ejb-local-ref*)".

  • 错误原因:文档内容标签顺序不符合web-app_2_3.dtd规范

  • 解决方案:严格按照提示的顺序安放标签

    参考:

    web.xml 报错The content of element type "web-app" must match


StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vita.service.IUserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
  • 错误原因:XXXService 未加注解@Service

Servlet.service() for servlet [SpringMVC] in context with path [/First] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.vita.dao.IUserDao.selectByPrimaryKey] with root cause java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.vita.dao.IUserDao.selectByPrimaryKey
  • 错误原因:XXXMapper.xmlmapper 标签的namespace 错误

  • 例:

    参考:

    mybatis一个怪异的问题: Invalid bound statement not found


.jsp不显示(接收不到)数据(数据已从数据库取到)
  • 解决方案:

    • .jsp 上面添加 <%@ page isELIgnored="false" %> (测试可行)

    • 或者修改web.xml ,添加version 版本,如下:(未测试成功)

      
      
      
      

    参考:

    SSM框架——Spring+SpringMVC+Mybatis的搭建教程

你可能感兴趣的:(Maven + Spring + SpringMVC + MyBatis + MySQL框架搭建Java Web工程)