搭建框架 SpringMVC+Spring+Mybatis ,Maven环境、 需要MySQL 数据库支持,使用的编程工具Eclipse
搭建完毕后的项目架构如下:
点击【finish】
新建完毕,项目报错,并且缺少目录。修改如下:
目录结构为:
src/main/resources
src/main/java
src/test/resources
src/test/java
【右键项目】-->【Build Path】-->【ConfigureBuild Path】
会看见所有的目录,没有看见的目录拉其滚动条就可看见
然后点击【Apply】--> 【OK】即可。
如果没有出现,则重复以上步骤,然后将目录收缩,再进行【Apply】。
最后项目结构如下:
以上结构还需要添加一些东西,选中【项目右键】--> 【Build Path】--> 【new Source Folder】--> 【输入文件夹名称】--> 【Finish】.
这里新建src/test/resources
目录如下:
默认项目的编译级别是1.5 ,有一些JDK的新特性可能会报错,所以需要更换项目的编译级别。修改如下:
【右键项目】-->【Properties】
选择【Java Compiler】
去掉选择,更换编译版本
选择【Project Facets】然后修改Java版本,因为安装的是JDK1.8 所以选择1.8
然后点击【Apply】-->【OK】
结果工程还是报错,因为缺少类javax.servlet.http.HttpServlet,此类在javax包中。
在pom.xml中加入以下依赖:
jstl
jstl
1.2
javax.servlet
servlet-api
2.5
provided
javax.servlet
jsp-api
2.0
provided
查看项目:
右键项目,选择[properties] -->[Deployment Assembly] 如下图:
此处列表是部署项目时,文件发布的路径。删除红色区域内条目;此处删除test的两项,是因为test是测试使用,并不需要部署。
创建表的脚本:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(40) NOT NULL,
`password` VARCHAR(255) NOT NULL,
`age` INT(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*Data for the table `user` */
INSERT INTO `user`(`id`,`user_name`,`password`,`age`) VALUES (1,'测试','sfasgfaf',24);
4.0.2.RELEASE
3.2.6
1.7.7
1.2.17
junit
junit
4.12
test
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-oxm
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-test
${spring.version}
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
1.2.2
javax
javaee-api
7.0
provided
mysql
mysql-connector-java
5.1.30
commons-dbcp
commons-dbcp
1.2.2
jstl
jstl
1.2
log4j
log4j
${log4j.version}
com.alibaba
fastjson
1.1.41
org.slf4j
slf4j-api
${slf4j.version}
org.slf4j
slf4j-log4j12
${slf4j.version}
org.codehaus.jackson
jackson-mapper-asl
1.9.13
commons-fileupload
commons-fileupload
1.3.1
commons-io
commons-io
2.4
commons-codec
commons-codec
1.9
org.apache.tomcat.maven
tomcat7-maven-plugin
8080
/
tomcat7
student
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_test
username=root
password=123456
#\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570
initialSize=0
#\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570
maxActive=20
#\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2
maxIdle=20
#\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2
minIdle=1
#\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4
maxWait=60000
#\u5B9A\u4E49LOG\u8F93\u51FA\u7EA7\u522B
log4j.rootLogger=INFO,Console,File
#\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6
log4j.appender.File = org.apache.log4j.RollingFileAppender
#\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55
log4j.appender.File.File = logs/ssm.log
#\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F
log4j.appender.File.MaxFileSize = 10MB
# \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
项目架构:
package cn.ssm.student.service;
import cn.ssm.student.entity.User;
public interface UserService {
public User getById(int userId);
}
package cn.ssm.student.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.ssm.student.entity.User;
import cn.ssm.student.mapper.UserMapper;
import cn.ssm.student.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Transactional(readOnly=true)
public User getById(int userId) {
return userMapper.selectByPrimaryKey(userId);
}
}
项目架构:
测试代码:
package cn.ssm.student.service;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.ssm.student.entity.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })
public class UserServiceTest {
protected static Logger logger = Logger.getLogger(UserServiceTest.class);
@Autowired
private UserService userService;
@Test
public void testGetById() {
User user = userService.getById(1);
System.out.println(user);
}
}
text/html;charset=UTF-8
Archetype Created Web Application
contextConfigLocation
classpath:spring-mybatis.xml
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
encodingFilter
/*
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
SpringMVC
/
index.jsp
内置tomcat运行,启动时为:tomcat7:run 因为在pom.xml中配置了tomcat插件的名字。
启动项目:
启动成功:
页面的el表达式原样输出
原因是因为maven生成的web.xml版本太低了,2.5之前web.xml文件中的头定义中,el表达式默认是忽略不解析的,故需要显示声明解析el表达式
方案1,在jsp文件头上添加如下:
<%@ pageisELIgnored="false" %>(测试通过)
但总不可能每个页面都加上这个,页面多了就显得重复多余了,下面的是统一解决的办法!
方案二:
改变xml的版本
Archetype Created Web Application
contextConfigLocation
classpath:spring-mybatis.xml
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
encodingFilter
/*
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
SpringMVC
*.do
/index.jsp
方案3 ,在web.xml文件中如下定义:
*.jsp
false
true
页面预览
添加界面效果如图:
输入内容,并提交
Controller层:
// 添加
@RequestMapping("/add")
public String add(User user) {
userService.add(user);
// 重定向到查询所有用户
return "redirect:getAll.do";
}
// 查询所有的用户
@RequestMapping("/getAll")
public String getAll(Model model) {
List list = userService.getAll();
model.addAttribute("userList", list);
return "show";
}
Service层:
@Transactional
public void add(User user) {
userMapper.insert(user);
}
add.jsp :
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
Insert title here
查看所有页面代码(show.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
测试
${user.id} ${user.userName} 删除 更新
新增
在浏览器中输入地址:http://localhost:8080/student/getById.do?id=2
Controller层:
// 查询某一个用户
@RequestMapping("/getById")
public String getById(Integer id, Model model) {
User user = userService.getById(id);
model.addAttribute("user", user);
// 转发到showUser.jsp页面
return "showUser";
}
Service层
@Transactional(readOnly = true)
public User getById(int userId) {
return userMapper.selectByPrimaryKey(userId);
}
showUser.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
查询单个用户
${user.id} ${user.userName}
查询所有用户,地址:http://localhost:8080/student/getAll.do
点击王武后面的【更新】
进入更新页面,修改其名字,然后【提交】:
结果:
Controller层:
@RequestMapping("/update")
public String update(User user){
userService.updateById(user);
// 更新成功,重定向查询所有
return "redirect:getAll.do";
}
//更新之前
@RequestMapping("/proupdate")
public String proUpdate(Integer id,Model model){
User user = userService.getById(id);
model.addAttribute("user",user);
return "update";
}
Service层:
@Transactional(readOnly = true)
public User getById(int userId) {
return userMapper.selectByPrimaryKey(userId);
}
@Transactional
public void updateById(User user) {
userMapper.updateByPrimaryKey(user);
}
update.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
点击【删除】
Controller层:
// 删除某一个用户
@RequestMapping("/delete")
public String delete(Integer id,Model model) {
userService.deleteById(id);
// 重定向到查询所有的用户
return "redirect:getAll.do";
}
Service层:
@Transactional
public void deleteById(int userId) {
userMapper.deleteByPrimaryKey(userId);
}
import org.mybatis.generator.ant.GeneratorAntTask;
public class Start {
private static final String CONFIG_FILE_PATH="config/generatorConfig.xml";
public static void main(String[] args) {
try {
GeneratorAntTask task = new GeneratorAntTask();
task.setConfigfile(CONFIG_FILE_PATH);
task.setOverwrite(true);
task.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成结果:
http://blog.csdn.net/zhshulin/article/details/37956105#