想必作为Java开发来说,使用SpringMVC框架的应该是很熟悉,现在本人用IDEA搭建SpringMVC并用maven配置的一个小例子,记录下来,方便以后回头看看,写得不好的请指出,谢谢!
首先先准备好环境,本人使用的是jdk1.8.0_101,apache-tomcat-7.0.65,IntelliJIdea15,当然了无论使用版本不一样,但是都差不多的,可能不同的版本会有点不兼容,大家多试试就可以了。
1、用idea创建maven一个项目
此时已经创建好一个maven目录了
2、添加maven依赖
maven依赖代码如下,大致需要的包如下(表较全),根据不同的需求可以添加不同的依赖
<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>demo</groupId>
<artifactId>demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- spring版本号 -->
<spring.version>4.1.1.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.6</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<!-- jackson包版本 -->
<jackson.version>2.5.0</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!--单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!--spring单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- springMVC核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring核心包 -->
<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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.0.9.RELEASE</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- AOP begin -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<!-- AOP end -->
<!-- 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>
<!-- Mysql数据库驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- connection pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.5</version>
<scope>runtime</scope>
</dependency>
<!-- 日志文件管理包 -->
<!-- log 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>
<!-- log end -->
<!--servlet-->
<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>
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.1</version>
<classifier>jdk15</classifier>
</dependency>
<!-- 用dom4j解析xml文件 -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.4</version>
</dependency>
<!-- ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.9</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-web</artifactId>
<version>2.0.4</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>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<!-- commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.7.0</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.19</version>
</dependency>
<!-- dom4j读取XML -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<finalName>Demo</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
<!-- 解决Maven项目编译后classes文件中没有.xml问题 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
实体类:
package com.springmvc.entity;
import java.io.Serializable;
/**
* Created by Vitelon on 2017-03-30
* 用户实体类.
*/
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**用户ID*/
private String id;
/**用户名*/
private String username;
/**密码*/
private String password;
/**姓名*/
private String sex;
public User() {
}
public User(String id, String username, String password, String sex) {
this.id = id;
this.username = username;
this.password = password;
this.sex = sex;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
public String getSex() {
return sex;
}
public void setSex(String name) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
dao接口:
package com.springmvc.dao;
import com.springmvc.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by Vitelon on 2017-03-30
* 用户dao接口.
*/
@Repository("UserDao")
public interface UserDao {
/**
* Created by Vitelon on 2017-03-22
* 根据用户名和密码查询用户
* @param username
* @param password
* @return
*/
public User findByUsernameAndPwd(@Param("username") String username, @Param("password") String password);
/**
* Created by Vitelon on 2017-03-30
* 获取用户
* @return
*/
public List<User> find(User User);
/**
* Created by Vitelon on 2017-03-30
* 新增
* @param User
*/
public void add(User User);
/**
* Created by Vitelon on 2017-03-30
* 修改
* @param User
*/
public void update(User User);
/**
* Created by Vitelon on 2017-03-30
* 删除
* @param id
*/
public void delete(String id);
}
mapper配置文件:
<?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.springmvc.dao.UserDao">
<parameterMap id="parameterMap" type="com.springmvc.entity.User"></parameterMap>
<resultMap id="resultMap" type="com.springmvc.entity.User">
<result property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="sex" column="sex"/>
</resultMap>
<sql id="columnSql">
<trim suffixOverrides=",">
t.id,
t.username,
t.password,
t.sex,
</trim>
</sql>
<select id="findByUsernameAndPwd" resultMap="resultMap">
SELECT
<include refid="columnSql"></include>
FROM t_user t
WHERE t.username = #{username} and t.password = #{password}
</select>
</mapper>
service接口:
package com.springmvc.service;
import com.springmvc.entity.User;
import java.util.List;
/**
* Created by Vitelon on 2017-03-30
* 用户service接口
*/
public interface UserService {
/**
* Created by Vitelon on 2017-03-22
* 根据用户名和密码查询用户
* @param username
* @param password
* @return
*/
public User findByUsernameAndPwd(String username, String password);
/**
* Created by Vitelon on 2017-03-30
* 获取用户
* @return
*/
public List<User> find(User User);
/**
* Created by Vitelon on 2017-03-30
* 新增
* @param User
*/
public void add(User User);
/**
* Created by Vitelon on 2017-03-30
* 修改
* @param User
*/
public void update(User User);
/**
* Created by Vitelon on 2017-03-30
* 删除
* @param id
*/
public void delete(String id);
}
service实现类:
package com.springmvc.service.impl;
import com.springmvc.dao.UserDao;
import com.springmvc.entity.User;
import com.springmvc.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by Vitelon on 2017-03-30
* 用户service实现类
*/
@Service("UserService")
public class UserServiceImpl implements UserService {
@Resource(name = "UserDao")
private UserDao userDao;
public User findByUsernameAndPwd(String name, String pwd) {
return userDao.findByUsernameAndPwd(name, pwd);
}
public List<User> find(User user){
return userDao.find(user);
}
public void add(User user) {
userDao.add(user);
}
public void update(User user) {
userDao.update(user);
}
public void delete(String id) {
userDao.delete(id);
}
}
controller控制器:
package com.springmvc.controller;
import com.springmvc.entity.User;
import com.springmvc.service.UserService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Controller
@RequestMapping("/user")
public class ViewController {
private Logger logger = Logger.getLogger(ViewController.class);
@Resource(name = "UserService")
private UserService userService;
@RequestMapping("/index")
public String index(){
return "index";
}
@RequestMapping("/find")
@ResponseBody
public Map<String,Object> find(User user, HttpServletRequest request){
Map<String,Object> map = new HashedMap();
System.out.println("你已通过springMVC进入controller方法。。。。");
logger.info("你已通过springMVC进入controller方法。。。。");
User loginuser = userService.findByUsernameAndPwd(user.getUsername(),user.getPassword());
if(loginuser != null){
map.put("result","success");
}else {
map.put("result","fail");
}
return map;
}
@RequestMapping("/success")
public String success(){
System.out.println("登录成功。。。。");
logger.info("登录成功。。。。");
return "success";
}
}
配置resources文件:
dbconfig.properties文件:
#MySQL
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=root
#oracle
#jdbc.driver=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc:oracle:thin:@localhost:3306:test
#jdbc.username=root
#jdbc.password=123456
数据库demo.sql文件:
/*
Date: 2017-04-11 19:49:03
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` varchar(11) NOT NULL,
`username` varchar(40) NOT NULL,
`password` varchar(40) NOT NULL,
`sex` varchar(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', 'user', '123', '男');
log4j.properties文件:
#日志输出级别
log4j.rootLogger=debug,stdout,D,E
#设置stdout的日志输出控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#输出日志到控制台的方式,默认为System.out
log4j.appender.stdout.Target = System.out
#设置使用灵活布局
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#灵活定义输出格式
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%c (%rms)] - %m%n
#每天产生一个日志文件
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
#设置的输出日志
log4j.appender.D.File=E:/Workspaces/IDEA15/demo/src/main/webapp/WEB-INF/logs/all/log.txt
#设置的日志最大限制
log4j.appender.D.MaxFileSize=6000KB
#最多只保存20个备份文件
log4j.appender.D.MaxBackupIndex=20
#输出INFO级别以上的日志
og4j.appender.D.Threshold=debug
log4j.appender.D.Append = true
log4j.appender.D.ImmediateFlush = true
#log4j.appender.D.DatePattern ='.'yyyy-MM-dd
#设置使用灵活布局
log4j.appender.D.layout=org.apache.log4j.PatternLayout
#灵活定义输出格式
log4j.appender.D.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%l (%rms)] - %m%n
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E:/Workspaces/IDEA15/demo/src/main/webapp/WEB-INF/logs/error/error.txt
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
#log4j.appender.E.DatePattern = '_'yyyyMMdd'.log'
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%l (%rms)] - %m%n
spring-context.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
default-lazy-init="true">
<description>Spring Configuration</description>
<!-- 开启注解处理器 -->
<context:annotation-config/>
<!-- 开启组件自动扫描;使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。 -->
<context:component-scan base-package="com.springmvc"><!-- base-package 如果多个,用“,”分隔 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--<!– 自动扫描 –>-->
<!--<context:component-scan base-package="com.vitelon.v"/>-->
<!--引入属性文件 -->
<context:property-placeholder location="classpath:dbconfig.properties" />
<!-- dataSource 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</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/springmvc/sql/*.xml"/>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.springmvc.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 对dataSource 数据源进行事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事务管理 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 对insert,create,update,modify,delete,remove 开头的方法进行事务管理,只要有异常就回滚 -->
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
<tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
<tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
<tx:method name="modify*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
<tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
<!-- find,get,select,count开头的方法,开启只读,提高数据库访问性能 -->
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="select*" read-only="true" />
<tx:method name="count*" read-only="true" />
<!-- 对其他方法 使用默认的事务管理 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!-- 事务 aop 配置 -->
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(public * com.springmvc.service..*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config>
<!-- 配置使Spring采用CGLIB代理 --><!-- 开启基于@AspectJ切面的注解处理器 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
</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: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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<description>Spring MVC Configuration</description>
<!-- 启用spring mvc 注解, 默认的注解映射的支持 -->
<mvc:annotation-driven/>
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.springmvc"/>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="zh_CN" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- 支持返回json(避免IE在ajax请求时,返回json出现下载文件 ) -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射, 配置一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0" />
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
</list>
</property>
</bean>
<!-- 默认的视图解析器 -->
<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="3">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="contentType" value="text/html" />
<property name="prefix" value="/WEB-INF/page/"/>
<property name="suffix" value=".jsp"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
</bean>
<!-- 配置springMVC处理上传文件的信息 -->
<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>
<!-- Bean解析器,级别高于默认解析器,寻找bean对象进行二次处理 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0"/>
<!-- 对静态资源文件的访问, 将无法mapping到Controller的path交给default servlet handler处理 -->
<mvc:default-servlet-handler />
<!-- 静态资源映射 -->
<mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/>
</beans>
4、配置tomcat
此时tomcat就配置好了。
5、接下来创建静态资源文件
6、配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 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">
<display-name>Manager</display-name>
<context-param>
<description>配置Spring配置文件路径</description>
<param-name>contextConfigLocation</param-name>
<!-- 如果是监听多个文件,可用‘,’隔开 -->
<param-value>classpath:spring-*.xml</param-value>
</context-param>
<listener>
<description>配置Spring上下文监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<description>Introspector缓存清除监听器</description>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<listener>
<description>request监听器</description>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- 配置Spring字符编码过滤器 -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--log4j配置文件加载-->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!--启动一个watchdog线程每1800秒扫描一下log4j配置文件的变化-->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>1800000</param-value>
</context-param>
<!--spring log4j监听器-->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- Spring MVC 核心控制器 DispatcherServlet 配置开始 -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 可以通过contextConfigLocation来自定义SpringMVC配置文件的位置,如不指定,则默认在WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,
此时文件名必须为[<servlet-name>]-servlet.xml,否则会出错-->
<!--以下init-param是自定义SpringMVC的配置文件的位置 -->
<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>
<!-- Spring MVC 核心配置结束 -->
<!-- 激活Tomcat的defaultServlet来处理静态文件 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
<!-- session 时间 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
7、在WEB-INF下创建文件夹page,主要放jsp文件
8、index文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>IDEA搭建SpringMVC并用maven配置的小例子</title>
</head>
<%--<link rel="stylesheet" href="/asset/css/style.css"/>--%>
<script type="text/javascript" src="/plugs/js/jquery-1.7.2.js"></script>
<body>
<form id="userForm" action="/user/find" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password">
<button type="button" οnclick="login()">登录</button>
</form>
</body>
<script>
function login() {
$.ajax({
type: 'post',
url: $('#userForm').attr('action'),
data: $('#userForm').serialize(),
dataType: 'json',
success: function(data){
if (data.result = "success"){
alert("登录成功");
location.href='/user/success';
}else{
alert("用户名或者密码错误!");
}
}
});
}
</script>
</html>
项目结构大致如下:
然后运行tomcat成功之后,在浏览器输入http://localhost:8080/user/index有如下结果:
输入用户名user和密码123就会跳转至登录成功的页面:
说明一个简单的SSM框架整合开发的例子就算搭建好了。
此步骤在本人的电脑下可以运行正常,可能大家在试的时候会有报错,有什么问题的大家可以多多百度找解决方案哦。
项目已打包,点击打开链接