这是适合新手搭建的最简单的SSM整合框架
这是我的下载资源网址:http://download.csdn.net/my/uploads
首先整合框架的话,至少需要了解一下这几个框架
它是为了解决企业应用开发的复杂性而创建的。Spring 使用基本的 JavaBean 来完成以前只可能由 EJB 完成的事情。然而, Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java 应用都可以从 Spring 中受益。 简单来说, Spring 是一个轻量级的控制反转(IoC )和面向切面( AOP )的容器框架。
创建数据库、表db_zsl t_user user_t【最下面有sql语句】
1.项目整体结构
2.添加相关jar 包
3.项目整体结构出来了
4.创建model【User】
package com.lyt.model;
/**
* 用户
* @author 李银涛
*
*/
public class User {
private int id;
private String userName;
private String age;
@Override
public String toString() {
return "User [id=" + id + ", age=" + age + ", userName=" + userName
+ "]";
}
public User(){
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public User(int id, String age, String userName) {
super();
this.id = id;
this.age = age;
this.userName = userName;
}
}
5.创建DAO接口【在mybatis中 mapper就相当于dao】
package com.lyt.mapper;
import java.util.List;
import com.lyt.model.User;
/**
* 做为 DAO的接口
* @author 李银涛
*/
public interface UserMapper {
void save(User user);
boolean update(User user);
boolean delete(int id);
User findById(int id);
List findAll();
}
insert into t_user(user_name,user_age) values(#{userName},#{age})
update t_user set user_name=#{userName},user_age=#{age} where user_id=#{id}
delete from t_user where user_id=#{id}
---------------------------------------------------
7.mybatis与Spring整合【spring-common.xml】放在src的根目录下
对于Mybatis和Spring的整合是这篇博文的重点,需要配置的内容在下面有详细的解释。
配置log4j.properties
### set log levels ###
log4j.rootLogger = info , Console , D
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.Statement=INFO
log4j.logger.java.sql.PreparedStatement=INFO
#output2file
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D\:/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO \#\# \u00E8\u00BE\u0093\u00E5\u0087\u00BAinfo\u00E7\u00BA\u00A7\u00E5\u0088\u00AB\u00E4\u00BB\u00A5\u00E4\u00B8\u008A\u00E7\u009A\u0084\u00E6\u0097\u00A5\u00E5\u00BF\u0097
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
10.整合Springmvc
配置【spring-mvc.xml】放在src根目录下
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:spring-common.xml,classpath:spring-mvc.xml
springMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-common.xml,classpath:spring-mvc.xml
1
springMVC
/
org.springframework.web.util.IntrospectorCleanupListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
index.jsp
package com.lyt.service;
import java.util.List;
import com.lyt.model.User;
public interface UserService {
void save(User user);
boolean update(User user);
boolean delete(int id);
User findById(int id);
List findAll();
}
【UserServiceImpl.java】
package com.lyt.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lyt.mapper.UserMapper;
import com.lyt.model.User;
import com.lyt.service.UserService;
@Service
@Transactional
// 此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。
public class UserServiceImpl implements UserService {
@Resource
private UserMapper mapper;
/**
* 根据 id 删除 数据
*/
public boolean delete(int id) {
return mapper.delete(id);
}
/**
* 查询User的全部数据
*/
public List findAll() {
List findAllList = mapper.findAll();
return findAllList;
}
/**
* 根据 id 查询 对应数据
*/
public User findById(int id) {
User user = mapper.findById(id);
return user;
}
/**
* 新增数据
*/
public void save(User user) {
mapper.save(user);
}
/**
* 根据 id 修改对应数据
*/
public boolean update(User user) {
return mapper.update(user);
}
}
13.建立Controller【UserController.java】
package com.lyt.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.lyt.model.User;
import com.lyt.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 获取所有用户列表
* @param request
* @return
*/
@RequestMapping("/getAllUser")
public String getAllUser(HttpServletRequest request,Model model){
List user = userService.findAll();
model.addAttribute("userList", user);
request.setAttribute("userList", user);
return "/allUser";
}
/**
* 跳转到添加用户界面
* @param request
* @return
*/
@RequestMapping("/toAddUser")
public String toAddUser(){
return "/addUser";
}
/**
* 添加用户并重定向
* @param user
* @param request
* @return
*/
@RequestMapping("/addUser")
public String addUser(User user,Model model){
userService.save(user);
return "redirect:/user/getAllUser";
}
/**
*编辑用户
* @param user
* @param request
* @return
*/
@RequestMapping("/updateUser")
public String updateUser(User user,HttpServletRequest request,Model model){
if(userService.update(user)){
user = userService.findById(user.getId());
request.setAttribute("user", user);
model.addAttribute("user", user);
return "redirect:/user/getAllUser";
}else{
return "/error";
}
}
/**
* 根据id查询单个用户
* @param id
* @param request
* @return
*/
@RequestMapping("/getUser")
public String getUser(int id,HttpServletRequest request,Model model){
request.setAttribute("user", userService.findById(id));
model.addAttribute("user", userService.findById(id));
return "/editUser";
}
/**
* 删除用户
* @param id
* @param request
* @param response
*/
@RequestMapping("/delUser")
public void delUser(int id,HttpServletRequest request,HttpServletResponse response){
String result = "{\"result\":\"error\"}";
if(userService.delete(id)){
result = "{\"result\":\"success\"}";
}
response.setContentType("application/json");
try {
PrintWriter out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
至此 大部分架构以及代码已经搭建完成
我们来做前台页面--修改index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
首页
进入用户管理页
addUser.jsp内容
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
添加用户
<%=path%>添加用户<%=basePath%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
用户列表
添加用户
姓名
年龄
操作
${user.userName }
${user.age }
编辑
删除
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
编辑用户
添加用户
让你们看下界面运行,地址:http://localhost:8088/SpringMVC_Spring_mybatis/
首页:
点击编辑进去:
点击添加进去:
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50515
Source Host : localhost:3306
Source Database : db_zsl
Target Server Type : MYSQL
Target Server Version : 50515
File Encoding : 65001
Date: 2016-05-16 16:10:51
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) NOT NULL,
`user_age` varchar(20) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('2', '朱佳鹏', '25');
INSERT INTO `t_user` VALUES ('3', '傻狍子', '150');
INSERT INTO `t_user` VALUES ('4', 'jiuqiyuliang', '23');
INSERT INTO `t_user` VALUES ('5', 'jiuqiyuliang', '23');
INSERT INTO `t_user` VALUES ('6', 'jiuqiyuliang', '23');
INSERT INTO `t_user` VALUES ('7', 'jiuqiyuliang', '23');
INSERT INTO `t_user` VALUES ('9', 'liyintao123', '23123');
-- ----------------------------
-- Table structure for `user_t`
-- ----------------------------
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
`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;
-- ----------------------------
-- Records of user_t
-- ----------------------------
INSERT INTO `user_t` VALUES ('1', '测试', 'sfasgfaf', '24');