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
<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.vita</groupId>
    <artifactId>First</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>First Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <!-- spring版本号 -->
        <spring.version>4.0.5.RELEASE</spring.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.2.1</mybatis.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <mysql.version>5.1.35</mysql.version>
    </properties>

    <dependencies>
        <!-- 导入java ee jar,该包已被移除,找不到,故导入会报错,注释以提醒 -->
        <!-- <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency> -->

        <!-- 添加Spring依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</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>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring单元测试依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- spring webmvc相关jar -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>

        <!-- alibaba data source 相关jar包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>0.2.23</version>
        </dependency>

        <!-- alibaba fastjson 格式化对 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>

        <!-- logback start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.logback-extensions</groupId>
            <artifactId>logback-ext-spring</artifactId>
            <version>0.1.1</version>
        </dependency>

        <!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <!-- 上传组件包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</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.2.2</version>
        </dependency>
        <!-- 添加servlet3.0核心包 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.2-b01</version>
        </dependency>
        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--单元测试依赖 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>First</finalName>
    </build>
</project>

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

    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
     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-3.1.xsd    
                            http://www.springframework.org/schema/context    
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                            http://www.springframework.org/schema/mvc    
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
     <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
     <context:component-scan base-package="com.vita.controller" />
    
     <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
     <bean id="viewResolver"
         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
         <property name="prefix" value="/WEB-INF/jsp/" />
         <property name="suffix" value=".jsp" />
     </bean>
    
     <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
     <bean id="mappingJacksonHttpMessageConverter"
         class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
         <property name="supportedMediaTypes">
             <list>
                 <value>text/html;charset=UTF-8</value>
             </list>
         </property>
     </bean>
     <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
     <bean
         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
         <property name="messageConverters">
             <list>
                 <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
             </list>
         </property>
     </bean>
     <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
     <bean
         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
         <property name="prefix" value="/WEB-INF/jsp/" />
         <property name="suffix" value=".jsp" />
     </bean>
    
     <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
     <bean id="multipartResolver"
         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- 默认编码 -->
         <property name="defaultEncoding" value="utf-8" />
         <!-- 文件大小最大值 -->
         <property name="maxUploadSize" value="10485760000" />
         <!-- 内存中的最大值 -->
         <property name="maxInMemorySize" value="40960" />
     </bean>
    
    </beans>
    
  4. spring-mybatis.xml ,注意包名,当前包名为com.vita

    <?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:p="http://www.springframework.org/schema/p"
     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-3.1.xsd    
                            http://www.springframework.org/schema/context    
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                            http://www.springframework.org/schema/mvc    
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
     <!-- 自动扫描 -->
     <context:component-scan base-package="com.vita.service" />
     <!-- 引入配置文件 -->
     <bean id="propertyConfigurer"
         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="location" value="classpath:jdbc.properties" />
     </bean>
    
     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
         destroy-method="close">
         <property name="driverClassName" value="${driver}" />
         <property name="url" value="${url}" />
         <property name="username" value="${username}" />
         <property name="password" value="${password}" />
         <!-- 初始化连接大小 -->
         <property name="initialSize" value="${initialSize}"></property>
         <!-- 连接池最大数量 -->
         <property name="maxActive" value="${maxActive}"></property>
         <!-- 连接池最大空闲 -->
         <property name="maxIdle" value="${maxIdle}"></property>
         <!-- 连接池最小空闲 -->
         <property name="minIdle" value="${minIdle}"></property>
         <!-- 获取连接最大等待时间 -->
         <property name="maxWait" value="${maxWait}"></property>
     </bean>
    
     <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <property name="dataSource" ref="dataSource" />
         <!-- 自动扫描mapping.xml文件 -->
         <property name="mapperLocations" value="classpath:com/vita/mapping/*.xml"></property>
     </bean>
    
     <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         <property name="basePackage" value="com.vita.dao" />
         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
     </bean>
    
     <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
     <bean id="transactionManager"
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource" />
     </bean>
    
    </beans>
    

四 数据库代码自动生成

  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 ,用以自动生成代码,如下:

    <?xml version="1.0" encoding="UTF-8"?>    
    <!DOCTYPE generatorConfiguration    
      PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"    
      "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    <generatorConfiguration>
     <!-- 数据库驱动 -->
     <classPathEntry location="mysql-connector-java-5.1.45-bin.jar" />
     <context id="DB2Tables" targetRuntime="MyBatis3">
         <commentGenerator>
             <property name="suppressDate" value="true" />
             <!-- 是否去除自动生成的注释 true:是 : false:否 -->
             <property name="suppressAllComments" value="true" />
         </commentGenerator>
         <!--数据库链接URL,用户名、密码 -->
         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
             connectionURL="jdbc:mysql://localhost:3306/test" userId="root"
             password="">
         </jdbcConnection>
         <javaTypeResolver>
             <property name="forceBigDecimals" value="false" />
         </javaTypeResolver>
         <!-- 生成模型的包名和位置 -->
         <javaModelGenerator targetPackage="com.vita.domain"
             targetProject="src">
             <property name="enableSubPackages" value="true" />
             <property name="trimStrings" value="true" />
         </javaModelGenerator>
         <!-- 生成映射文件的包名和位置 -->
         <sqlMapGenerator targetPackage="com.vita.mapping"
             targetProject="src">
             <property name="enableSubPackages" value="true" />
         </sqlMapGenerator>
         <!-- 生成DAO的包名和位置 -->
         <javaClientGenerator type="XMLMAPPER"
             targetPackage="com.vita.dao" targetProject="src">
             <property name="enableSubPackages" value="true" />
         </javaClientGenerator>
         <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
         <table tableName="user" domainObjectName="User"
             enableCountByExample="false" enableUpdateByExample="false"
             enableDeleteByExample="false" enableSelectByExample="false"
             selectByExampleQueryId="false"></table>
     </context>
    </generatorConfiguration>
    

    注意<classPathEntry location="mysql-connector-java-5.1.45-bin.jar" /> 中的包的版本号,对应下载包的版本,以及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.*"%>
    <!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</title>
    </head>
    <body>
     ${user.name}
     ${user.email}
    </body>
    </html>
    
  7. 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>
     <display-name>Archetype Created Web Application</display-name>
    
     <context-param>
         <param-name>log4jConfigLocation</param-name>
         <param-value>classpath:log4j.properties</param-value>
         <description>加载日志文件</description>
     </context-param>
     
     <!-- Spring和mybatis的配置文件 -->
     <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:spring-mybatis.xml</param-value>
     </context-param>
     
     <!-- 编码过滤器 -->
     <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>
     
     <listener>
         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
     </listener>
     
     <!-- Spring监听器 -->
     <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
     <!-- 防止Spring内存溢出监听器 -->
     <listener>
         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
     </listener>
    
     <!-- Spring MVC servlet -->
     <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>
     </servlet>
     <servlet-mapping>
         <servlet-name>SpringMVC</servlet-name>
         <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
         <url-pattern>/</url-pattern>
     </servlet-mapping>
     
     <!-- 起始欢迎界面 -->
     <welcome-file-list>
         <welcome-file>/index.jsp</welcome-file>
     </welcome-file-list>
    </web-app>
    

六 结束

到此,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

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

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

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

      <?xml version="1.0" encoding="UTF-8"?>
      
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
          id="WebApp_ID" version="3.0" metadata-complete="true">
      

    参考:

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,214评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,307评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,543评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,221评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,224评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,007评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,313评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,956评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,441评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,925评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,018评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,685评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,234评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,240评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,464评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,467评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,762评论 2 345

推荐阅读更多精彩内容