想必作为Java开发来说,使用SpringMVC框架的应该是很熟悉,现在本人用IDEA搭建SpringMVC并用maven配置的一个小例子,记录下来,方便以后回头看看,写得不好的请指出,谢谢!
首先先准备好环境,本人使用的是jdk1.8.0_101,apache-tomcat-7.0.65,IntelliJIdea15,当然了无论使用版本不一样,但是都差不多的,可能不同的版本会有点不兼容,大家多试试就可以了。
1、用idea创建maven一个项目
此时已经创建好一个maven目录了
2、添加maven依赖
maven依赖代码如下,大致需要的包如下(表较全),根据不同的需求可以添加不同的依赖
4.0.0
demo
demo
war
1.0-SNAPSHOT
demo Maven Webapp
http://maven.apache.org
UTF-8
4.1.1.RELEASE
3.2.6
1.7.7
1.2.17
2.5.0
junit
junit
3.8.1
test
junit
junit
4.11
test
org.springframework
spring-test
${spring.version}
test
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-core
${spring.version}
org.springframework
spring-beans
${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
4.0.9.RELEASE
org.springframework
spring-tx
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.aspectj
aspectjrt
1.7.4
org.aspectj
aspectjweaver
1.7.4
cglib
cglib
3.1
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
1.2.2
mysql
mysql-connector-java
5.1.34
com.alibaba
druid
1.0.5
runtime
log4j
log4j
${log4j.version}
org.slf4j
slf4j-api
${slf4j.version}
org.slf4j
slf4j-log4j12
${slf4j.version}
javax.servlet
javax.servlet-api
3.0.1
provided
javax.servlet.jsp
jsp-api
2.2
provided
javax.servlet
jstl
1.2
org.codehaus.jackson
jackson-core-asl
1.9.13
org.codehaus.jackson
jackson-mapper-asl
1.9.13
com.fasterxml.jackson.core
jackson-annotations
${jackson.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
com.fasterxml.jackson.core
jackson-core
${jackson.version}
net.sf.json-lib
json-lib
2.1
jdk15
dom4j
dom4j
1.4
net.sf.ehcache
ehcache-core
2.6.9
net.sf.ehcache
ehcache-web
2.0.4
commons-fileupload
commons-fileupload
1.3.1
commons-io
commons-io
2.4
commons-codec
commons-codec
1.9
org.apache.commons
commons-collections4
4.0
org.apache.commons
commons-lang3
3.3.2
commons-beanutils
commons-beanutils
1.7.0
commons-logging
commons-logging
org.freemarker
freemarker
2.3.19
dom4j
dom4j
1.6.1
Demo
org.apache.maven.plugins
maven-compiler-plugin
1.6
src/main/java
**/*.xml
true
实体类:
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 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配置文件:
t.id,
t.username,
t.password,
t.sex,
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 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);
}
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 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);
}
}
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 find(User user, HttpServletRequest request){
Map 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";
}
}
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文件:
Spring Configuration
spring-mvc.xml文件:
Spring MVC Configuration
text/html;charset=UTF-8
text/json;charset=UTF-8
application/json;charset=UTF-8
此时tomcat就配置好了。
5、接下来创建静态资源文件
6、配置web.xml文件
Manager
配置Spring配置文件路径
contextConfigLocation
classpath:spring-*.xml
配置Spring上下文监听器
org.springframework.web.context.ContextLoaderListener
Introspector缓存清除监听器
org.springframework.web.util.IntrospectorCleanupListener
request监听器
org.springframework.web.context.request.RequestContextListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
log4jConfigLocation
classpath:log4j.properties
log4jRefreshInterval
1800000
org.springframework.web.util.Log4jConfigListener
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
SpringMVC
/
default
/static/*
30
8、index文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
IDEA搭建SpringMVC并用maven配置的小例子
<%----%>
然后运行tomcat成功之后,在浏览器输入http://localhost:8080/user/index有如下结果:
输入用户名user和密码123就会跳转至登录成功的页面:
说明一个简单的SSM框架整合开发的例子就算搭建好了。
此步骤在本人的电脑下可以运行正常,可能大家在试的时候会有报错,有什么问题的大家可以多多百度找解决方案哦。
项目已打包,点击打开链接