我这边使用的是intellij idea15

1.new maven webapp project

2.添加groupId和artifactId

3.选择maven路径和maven仓库路径

最后确定之后,等1分钟左右时间,maven会自动补全项目结构。如果没有,自己新建src/main/java等结构吧

4.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>springmvcdemo</groupId>
<artifactId>springmvcdemo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springmvcdemo Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring.version>4.2.5.RELEASE</spring.version>
<aop.version>4.1.7.RELEASE</aop.version>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</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>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${aop.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</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-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</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-tx</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-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志框架 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--common-->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
<!-- mybatis包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<!--mybatis spring插件-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- mysql连接驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- 连接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency> <dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.5</version>
</dependency> <!-- urlrewrite伪静态-->
<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
<version>4.0.4</version>
</dependency>
</dependencies> <build>
<finalName>springmvcdemo</finalName>
<resources>
<!-- 先指定 src/main/resources下所有文件及文件夹为资源文件 -->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<inherited>true</inherited>
<executions>
<execution>
<id>war-exploded-on-test</id>
<phase>test</phase>
<goals>
<goal>exploded</goal>
</goals>
</execution>
</executions>
<configuration>
<outputDirectory>/data/www/deploy</outputDirectory>
<warName>${project.artifactId}</warName>
<webappDirectory>${project.build.directory}/springmvcDemo
</webappDirectory>
<archive>
<manifest>
<addDefaultImplementationEntries>true
</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

然后在src/main/resoures目录下分别新建配置文件目录:spring、mybatis、springmvc、properties

配置spring文件:在sping目录下新建applicationContext.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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 自动扫描 -->
<context:component-scan base-package="com.mlxs.mvc" /> <!-- 引入jdbc配置文件 -->
<!--<context:property-placeholder location="classpath:properties/jdbc.properties" />-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:properties/jdbc.properties"/>
</bean> <!-- sqlServer数据源-->
<bean id="sqlServerDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.sqlserver.driver}"/>
<property name="url" value="${jdbc.sqlserver.url}"/>
<property name="username" value="${jdbc.sqlserver.username}"/>
<property name="password" value="${jdbc.sqlserver.password}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
<property name="maxWait" value="${jdbc.maxWait}"/>
<property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}"/>
<property name="removeAbandoned" value="${jdbc.removeAbandoned}"/>
<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/>
<property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>
<property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}"/>
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>
</bean> <!-- mysql数据源-->
<bean id="mySqlDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.mysql.driver}"/>
<property name="url" value="${jdbc.mysql.url}"/>
<property name="username" value="${jdbc.mysql.username}"/>
<property name="password" value="${jdbc.mysql.password}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
<property name="maxWait" value="${jdbc.maxWait}"/>
<property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}"/>
<property name="removeAbandoned" value="${jdbc.removeAbandoned}"/>
<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/>
<property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>
<property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}"/>
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>
</bean> <!-- 数据源选择,targetDataSources中选择数据源,若找不到,则使用defaultTargetDataSource-->
<bean id="multipleDataSource" class="com.mlxs.mvc.common.MutipleDataSource">
<property name="defaultTargetDataSource" ref="mySqlDataSource"/>
<property name="targetDataSources">
<map>
<entry key="mySqlDataSource" value-ref="mySqlDataSource"/>
<entry key="sqlServerDataSource" value-ref="sqlServerDataSource"/>
</map>
</property>
</bean> <!-- 配置mybatis的sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="multipleDataSource" />
<!-- 自动扫描mappers.xml文件 ,要加上classpath:com/...-->
<property name="mapperLocations" value="classpath:mybatis/com.mlxs.mvc.mapper/*.xml"></property>
<!-- mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
</bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mlxs.mvc.mapper" />
<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="mySqlDataSource" />
</bean> <!-- 配置事务通知属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定义事务传播属性 -->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice> <!-- 配置事务切面 -->
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.mlxs.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
</beans>

添加数据源类com.mlxs.mvc.common.MutipleDataSource:

package com.mlxs.mvc.common;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
* MutipleDataSource:
*
* @author yangzhenlong
* @since 2016/7/13
*/
public class MutipleDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>(); public static void setDataSourceKey(String dataSource) {
dataSourceKey.set(dataSource);
} @Override
protected Object determineCurrentLookupKey() {
return dataSourceKey.get();
} }

在mybatis目录下添加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>
<!-- setting name="cacheEnable" value="true"/-->
<setting name="useGeneratedKeys" value="false"/>
<setting name="logImpl" value="LOG4J"/><!--增加mybatis日志-->
</settings>
<mappers>
<!--这里不需要添加mapper.xml文件,在spring的sqlSessionFactory中已经配置了自动扫描-->
</mappers>
</configuration>

在spingmvc目录下添加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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<mvc:annotation-driven /> <!-- 使用注解的包,包括子集 -->
<context:component-scan base-package="com.mlxs.mvc.controller" /> <!-- 解决js,css,images访问不到的问题-->
<!--<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/template/**" location="/template/" />--> <!-- 文件上传配置注意:这里申明的id必须为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="500000"/>
</bean> <!-- 简单的异常处理 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 映射目录为/WEB-INF/jsp/error/upload_error.jsp -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error/upload_error</prop>
</props>
</property>
</bean> <!-- 配置JSP视图 -->
<bean id="internalResourceViewResolver" 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"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="order" value="1"/>
</bean>
</beans>

在properties目录下添加jdbc.properties和log4j.properties文件:

jdbc.properties:

#============================================================================
# MySQL
#============================================================================
jdbc.mysql.driver=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://localhost:3307/test?useUnicode=true&characterEncoding=utf8
jdbc.mysql.username=root
jdbc.mysql.password=root #============================================================================
# MS SQL Server
#============================================================================
jdbc.sqlserver.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.sqlserver.url=jdbc:sqlserver://127.0.0.1:1433;database=angular-demo;
jdbc.sqlserver.username=root
jdbc.sqlserver.password=root #============================================================================
# ORACLE
#============================================================================
jdbc.orcl.driver=oracle.jdbc.OracleDriver
jdbc.orcl.url=jdbc:oracle:thin:@localhost::angular-demo
jdbc.orcl.username=root
jdbc.orcl.password=root #============================================================================
# common settings
#============================================================================
jdbc.initialSize=
jdbc.minIdle=
jdbc.maxIdle=
jdbc.maxActive=
jdbc.maxWait=
jdbc.defaultAutoCommit=false
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=
jdbc.testWhileIdle=true
jdbc.timeBetweenEvictionRunsMillis=
jdbc.numTestsPerEvictionRun=
jdbc.minEvictableIdleTimeMillis=

log4j.properties:

##define output style
ConversionPattern=%d %-5p [%t] %c - %m%n log4j.rootLogger=DEBUG,Console
log4j.logger.com.cnblogs.lzrabbit=DEBUG
log4j.logger.org.springframework=ERROR
log4j.logger.org.mybatis=ERROR
log4j.logger.org.apache.ibatis=ERROR
log4j.logger.org.quartz=ERROR
log4j.logger.org.apache.axis2=ERROR
log4j.logger.org.apache.axiom=ERROR
log4j.logger.org.apache=ERROR
log4j.logger.httpclient=ERROR
#log4j.additivity.org.springframework=false
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Threshold=DEBUG
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=${ConversionPattern}
#log4j.appender.Console.encoding=UTF- #org.apache.log4j.DailyRollingFileAppender
log4j.appender.DailyFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DailyFile.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.DailyFile.File=${myApp.root}/logs/daily.log
log4j.appender.DailyFile.Append=true
log4j.appender.DailyFile.Threshold=DEBUG
log4j.appender.DailyFile.layout=org.apache.log4j.PatternLayout
log4j.appender.DailyFile.layout.ConversionPattern=${ConversionPattern}
log4j.appender.DailyFile.encoding=UTF- # %c 输出日志信息所属的类的全名
# %d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy-MM-dd HH:mm:ss},
# 输出类似:-- ::
# %f 输出日志信息所属的类的类名
# %l 输出日志事件的发生位置,即输出日志信息的的语句处于它所在的类的第几行
# %m 输出代码中指定的信息,如log(message)中的message
# %n 输出一个回车换行符,Windows平台为"rn",Unix平台为"n"
# %p 输出优先级,即DEBUG.INFO,WARN,ERROR,FATAL.如果是调用debug()输出的,则为DEBUG,以此类推
# %r 输出自应用启动到输出该日志信息所耗费的毫秒数
# %t 输出产生该日志的线程名

在webapp/WEB-INF/web.xml中配置:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"> <display-name>Archetype Created Web Application</display-name>
<description>testSpringMVC</description> <!--加载spring配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.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> <!-- urlrewrite-->
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping> <!-- 日志记录 -->
<context-param>
<!-- 日志配置文件路径 -->
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:properties/log4j.properties</param-value>
</context-param>
<context-param>
<!-- 日志页面的刷新间隔 -->
<param-name>log4jRefreshInterval</param-name>
<param-value>6000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener> <!-- Spring监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- Spring MVC配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 自定义spring mvc的配置文件名称和路径 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <error-page>
<error-code>404</error-code>
<location>/error/404</location>
</error-page> <error-page>
<error-code>500</error-code>
<location>/error/500</location>
</error-page> <welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
<welcome-file>/index.htm</welcome-file>
<welcome-file>/index.html</welcome-file>
</welcome-file-list>
</web-app>

好了,现在所有的配置都完成了,下面就是写model、dao(我这里是mapper,对应mybatis的mapper类)、service、controller类:

1.com.mlxs.mvc.model.User:

package com.mlxs.mvc.model;

/**
* User:
*
* @author yangzhenlong
* @since 2016/7/13
*/
public class User {
private int id;
private String loginName;
private String loginPwd;
private String realName;
private int sex;
private int age;
private String phone;
private String address;
private String remark; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getLoginName() {
return loginName;
} public void setLoginName(String loginName) {
this.loginName = loginName;
} public String getLoginPwd() {
return loginPwd;
} public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
} public String getRealName() {
return realName;
} public void setRealName(String realName) {
this.realName = realName;
} public int getSex() {
return sex;
} public void setSex(int sex) {
this.sex = sex;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getRemark() {
return remark;
} public void setRemark(String remark) {
this.remark = remark;
}
}

2.com.mlxs.mvc.mapper.UserMapper:

package com.mlxs.mvc.mapper;

import com.mlxs.mvc.model.User;

import java.util.List;

/**
* UserMapper:
*
* @author yangzhenlong
* @since 2016/7/13
*/
public interface UserMapper {
public int save(User user);
public int delete(int id);
public int update(User user);
public User queryByUser(User user);
public List<User> queryAll();
}

3.com.mlxs.mvc.service.UserService

package com.mlxs.mvc.service;

import com.mlxs.mvc.model.User;

import java.util.List;

/**
* UserService:
*
* @author yangzhenlong
* @since 2016/7/13
*/
public interface UserService { public List<User> queryAll();
}

3.1com.mlxs.mvc.service.impl.UserServiceImpl

package com.mlxs.mvc.service.impl;

import com.mlxs.mvc.mapper.UserMapper;
import com.mlxs.mvc.model.User;
import com.mlxs.mvc.service.UserService;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import java.util.List; /**
* UserServiceImpl:
*
* @author yangzhenlong
* @since 2016/7/13
*/
@Service
public class UserServiceImpl implements UserService { @Resource
UserMapper userMapper;
public List<User> queryAll() {
return userMapper.queryAll();
}
}

4.com.mlxs.mvc.controller.UserController:

package com.mlxs.mvc.controller;

import com.mlxs.mvc.model.User;
import com.mlxs.mvc.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import javax.annotation.Resource;
import java.util.List; /**
* UserController:
*
* @author yangzhenlong
* @since 2016/7/13
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
UserService userService; @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
public String list(ModelMap modelMap){
List<User> userList = userService.queryAll();
modelMap.addAttribute("userList", userList);
return "userlist";
}
}

然后要添加mapper类对应的maper.xml文件:在resources/mybatis目录下添加:com.mlxs.mvc.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.mlxs.mvc.mapper.UserMapper">
<insert id="save" parameterType="com.mlxs.mvc.model.User">
INSERT INTO `test`.`user`(`id`,`login_name`,`login_pwd`,`real_name`,`sex`,`age`,`phone`,`address`,`remark`)
VALUES ( NULL,
#{loginName},#{loginPwd},#{realName},#{sex},#{age},#{phone},#{address},#{remark});
</insert> <select id="queryAll" resultType="com.mlxs.mvc.model.User">
SELECT id,
login_name loginName,
login_pwd loginPwd,
real_name realName,
sex,
age,
phone,
address,
remark
FROM test.user
</select>
</mapper>

对应的数据表DDL语句:

CREATE TABLE `user` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`login_name` varchar(64) DEFAULT NULL,
`login_pwd` varchar(64) DEFAULT NULL,
`real_name` varchar(64) DEFAULT NULL,
`sex` tinyint(2) DEFAULT NULL COMMENT '性别(1男,2女)',
`age` int(3) DEFAULT NULL COMMENT '年龄',
`phone` varchar(11) DEFAULT NULL COMMENT '电话',
`address` varchar(128) DEFAULT NULL COMMENT '地址',
`remark` text COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

表中添加数据:

最后,在WEB-INF目录下新建jsp目录,再新建userlist.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户列表</title>
<style>
table tr td{
width:100px;
}
</style>
</head>
<body>
用戶列表頁面
<table style="border:1px solid red;background-color:#eee;"> <tr width="100%">
<td>Id</td>
<td>登录名</td>
<td>密码</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>电话</td>
<td>地址</td>
<td>备注</td>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.loginName}</td>
<td>${user.loginPwd}</td>
<td>${user.realName}</td>
<td>${user.sex==1?'男':'女'}</td>
<td>${user.age}</td>
<td>${user.phone}</td>
<td>${user.address}</td>
<td>${user.remark}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

配置server,启动tomcat,访问controller地址:http://localhost:8080/user/list,查看结果:

项目osc git地址:http://git.oschina.net/yangzhenlong/springmvcdemo

使用idea15搭建基于maven的springmvc-mybatis框架的更多相关文章

  1. java实现微信支付宝等多个支付平台合一的二维码支付(maven+spring springmvc mybatis框架)

    首先申明,本人实现微信支付宝等支付平台合多为一的二维码支付,并且实现有效时间内支付有效,本人采用的框架是spring springmvc mybatis 框架,maven管理.其实如果支付,不需要my ...

  2. 基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建

    基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建 前言 最近做回后台开发,重新抓起以前学过的SSM(Spring+Sp ...

  3. 使用intellij idea搭建MAVEN+springmvc+mybatis框架

    原文:使用intellij idea搭建MAVEN+springmvc+mybatis框架 1.首先使用idea创建一个maven项目 2.接着配置pom.xml,以下为我的配置 <projec ...

  4. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建一:建立MAVEN Web项目

    一:创建maven web项目er

  5. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建三:配置spring并测试

    这一部分的主要目的是 配置spring-service.xml  也就是配置spring  并测试service层 是否配置成功 用IntelliJ IDEA 开发Spring+SpringMVC+M ...

  6. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(1 构建目录环境和依赖)

    引言:在用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建一   的基础上 继续进行项目搭建 该部分的主要目的是测通MyBatis 及Spring-dao ...

  7. SSM(Spring+SpringMVC+Mybatis)框架环境搭建(整合步骤)(一)

    1. 前言 最近在写毕设过程中,重新梳理了一遍SSM框架,特此记录一下. 附上源码:https://gitee.com/niceyoo/jeenotes-ssm 2. 概述 在写代码之前我们先了解一下 ...

  8. Spring+SpringMvc+Mybatis框架集成搭建教程

    一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼 ...

  9. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建四:配置springmvc

    在用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建三:配置spring并测试的基础上 继续进行springmvc的配置 一:配置完善web.xml文件

随机推荐

  1. LazyMan的Promise解法

    背景 见上一篇. 面向对象的链式调用中,掺杂了 一个一部动作, 对于这种工作链, 是非同步执行的链. LazyMan("Hank").sleep(1).eat("dinn ...

  2. Ubuntu Kylin 14.04下配置JDK1.8

    1.源码包准备: 首先到官网下载jdk,http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.h ...

  3. 基于DevExpress ImageSlider实现图片轮播效果

    工具:DevExpress版本为15.2.7 1.控件类型全称:DevExpress.XtraEditors.Controls.ImageSlider 2.控件所在程序集:DevExpress.Xtr ...

  4. 使用hbuilder编辑器实现移动app打包

    作为一枚web前端来讲,需要了解的东西太多,需要学习的也太多了,那天因为公司需求,就研究了下移动网站打包成app的方法,这种东西好像是H5出来后就有推出的,因为性功能不行,就没怎么关注,但现在移动互联 ...

  5. Web攻防之XSS,CSRF,SQL注入

    摘要:对Web服务器的攻击也可以说是形形色色.种类繁多,常见的有挂马.SQL注入.缓冲区溢出.嗅探.利用IIS等针对Webserver漏洞进行攻击.本文结合WEB TOP10漏洞中常见的SQL注入,跨 ...

  6. Hybrid技术的设计与实现(转)

    浅谈Hybrid技术的设计与实现 前言 随着移动浪潮的兴起,各种APP层出不穷,极速的业务扩展提升了团队对开发效率的要求,这个时候使用IOS&Andriod开发一个APP似乎成本有点过高了,而 ...

  7. Samba快速配置

    Samba是linux,unix,windows之间进行交互操作的软件组件,Sanma是基于GPL协议的自由开源软件. 快速配置samba文件服务器 1.关闭防火墙和SELinux [root@cen ...

  8. SSO

  9. 闲鱼demo

    编程是一种美德,是促使一个人不断向上发展的一种原动力 -----–以下是正文------- 最近好多app的底部标签导航使用以下形式了,所以我们就来学习一下它是如何实现的. 先看效果: 中间的&quo ...

  10. Linux命令的返回码列表

    转自:http://blog.chinaunix.net/uid-10347480-id-3263127.html 在 Linux 下,不管你是启动一个桌面程序也好,还是在控制台下运行命令,所有的程序 ...