SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

spring相关概念及SSM框架在本文当中就不多述了,直接上干货!

一、用myEclipse初始化Web项目

       新建一个web project:

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现_第1张图片

二、创建包

controller        //控制类

service //服务接口
service.impl //服务实现类
dao //data access object(接口)
dao.impl //实现类

domain  //实体类

mappers  //mybatis的配置映射文件
        util             //工具类

         SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现_第2张图片

三、是maven方式引入类库

3.1启动tomcat服务

3.2给web项目添加maven支持(引入maven私服库)

   将web项目转化为maven项目:

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现_第3张图片

3.3引入依赖

spring

mybatis
spring mvc
c3p0类库
mysql

.......

3.4主要是编写pom.xml文件


  4.0.0
  com.liuhai
  eshopSSM
  0.0.1-SNAPSHOT
  war
  
  	1.2.17
  	1.7.7  
  
  
    src
    
      
        src
        
          **/*.java
        
      
    
    
      
        maven-compiler-plugin
        3.1
        
          1.7
          1.7
        
      
      
        maven-war-plugin
        2.3
        
          WebRoot
          false
          3.0
        
      
    
  
  
  	
		
			org.springframework
			spring-webmvc
			4.0.2.RELEASE
		
		
			org.springframework
			spring-jdbc
			4.0.2.RELEASE
		
		
			org.springframework
			spring-tx
			4.0.2.RELEASE
		
		
			org.springframework
			spring-context-support
			4.0.2.RELEASE
		
		
			org.springframework
			spring-orm
			4.0.2.RELEASE
		
		  
		
			mysql
			mysql-connector-java
			5.1.17
		
		
		
			com.mchange
			c3p0
			0.9.5.2
		
		  
		
			javax.servlet
			jstl
			1.2
		
		
			commons-io
			commons-io
			2.4
		
		
		  
            org.mybatis  
            mybatis  
            3.1.1  
        
           
          
            org.mybatis  
            mybatis-spring  
            1.2.0  
         
         
          
	       org.codehaus.jackson  
	       jackson-mapper-asl  
	       1.9.4  
         
         
          
            log4j  
            log4j  
            ${log4j.version}  
          
          
            org.slf4j  
            slf4j-api  
            ${slf4j.version}  
          
          
            org.slf4j  
            slf4j-log4j12  
            ${slf4j.version}  
          
        
          
          
            commons-fileupload  
            commons-fileupload  
            1.3.1  
          
          
            commons-io  
            commons-io  
            2.4  
         
          
         
        
		    net.sf.json-lib
		    json-lib
		    2.4
		
  

四、创建dao和service的基础类库

UserDao.java如下:

package com.liuhai.eshop.dao;

import java.util.List;
import java.util.Map;

import com.liuhai.eshop.domain.User;
/**
 * 用户DAO接口
 * @author Administrator
 *
 */
public interface UserDao {
	/**
	 * 用户登录
	 * @param user
	 * @return
	 */
	public User login(User user);
	/**
	 * 查询所有用户
	 * @return
	 */
	public List getAll();
	/**
	 * 根据条件查询用户
	 * @param user
	 * @return
	 */
	public User getUser(User user);
	/**
	 * 删除用户
	 * @param user
	 * @return
	 */
	public int delete(int id);
	/**
	 * 更新用户
	 * @param user
	 * @return
	 */
	public int update(User user);
	/**
	 * 添加用户
	 * @param user
	 * @return
	 */
	public int add(User user);
	/**
	 * 用户查询
	 * @param map
	 * @return
	 */
	public List find(Map map);
	/**
	 * 获取总记录数
	 * @param map
	 * @return
	 */
	public Long getTotal(Map map);
	/**
	 * 根据id查询用户
	 * @param id
	 * @return
	 */
	public User getUserById(int id);
}

UserService.java 用户service层接口如下:

package com.liuhai.eshop.service;

import java.util.List;
import java.util.Map;
import com.liuhai.eshop.domain.User;

public interface UserService {
	  public List getAll();
	  public User getUser(User user);
	  public int delete(int id);
	  public int update(User user);
	  public int add(User user);
	  public List find(Map map);
	  public Long getTotal(Map map);
	  public User getUserById(int id);
}

UserServiceImpl.java 用户service实现层如下:

package com.liuhai.eshop.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.liuhai.eshop.dao.UserDao;
import com.liuhai.eshop.domain.User;
import com.liuhai.eshop.service.UserService;
@Service(value="userService")
public class UserServiceImpl implements UserService {
	private UserDao userDao;
    @Resource
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
	@Override
	public List getAll() {
		return userDao.getAll();
	}

	@Override
	public User getUser(User user) {
		   return userDao.getUser(user);
	}

	@Override
	public int delete(int id) {
		return userDao.delete(id);
	}

	@Override
	public int update(User user) {
		 return userDao.update(user);
	}

	@Override
	public int add(User user) {
		  return userDao.add(user);
	}

	@Override
	public List find(Map map) {
		 return userDao.find(map);
	}

	@Override
	public Long getTotal(Map map) {
		 return userDao.getTotal(map);
	}
	public User getUserById(int id){
		return userDao.getUserById(id);
	}
}

user实体类如下:

package com.liuhai.eshop.domain;

import java.io.Serializable;

/**
 * 用户实体
 * @author Administrator
 *
 */
public class User implements Serializable{
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String userName;
	private String password;
	private Integer age;
	private String trueName;
	private String email;
	private String phone;
	private String roleName;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getTrueName() {
		return trueName;
	}
	public void setTrueName(String trueName) {
		this.trueName = trueName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getRoleName() {
		return roleName;
	}

public void setRoleName(String roleName) {

this.roleName = roleName; } }

五、配置spring配置文件、jdbc和日志属性文件、myBatis的mapper.xml文件

     5.1  spring配置文件applicationContext.xml如下:



	
	
	
	
	
	
	
	
	
		
		
		
		
		
		
		
		
	
      
      
          
          
          
     
      
    
    	
    	
    
	
	
		
	


5.2 jdbc属性文件jdbc.properties如下:

jdbc.driverclass=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/eshop
jdbc.username=root
jdbc.password=123456
c3p0.pool.size.max=10
c3p0.pool.size.min=2
c3p0.pool.size.init=3
c3p0.pool.size.increment=2

hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=none

5.3 日志属性文件log4j.properties如下:

log4j.rootLogger=INFO,Console,File  
#定义日志输出目的地为控制台  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#可以灵活地指定日志输出格式,下面一行是指定具体的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  

log4j.logger.java.sql.ResultSet=INFO  
log4j.logger.org.apache=INFO  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG  
  
#文件大小到达指定尺寸的时候产生一个新的文件  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定输出目录  
log4j.appender.File.File = logs/ssm.log  
#定义文件最大大小  
log4j.appender.File.MaxFileSize = 10MB  
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志  
log4j.appender.File.Threshold =INFO  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n 

5.4 myBatis的mapper.xml文件(UserMapper.xml)




	 
    
    
	
		insert into users values(null,#{userName},#{password},#{age},#{trueName},#{email},#{phone},#{roleName})
	
    
        
        
        
        
        
		
		
		
    
    
    
    
	
	
		delete from users where id = #{id}
	
	
	
		update users
		
			age = #{age},
			userName = #{userName},
			password = #{password},
			trueName = #{trueName},
			email = #{email},
			phone = #{phone},
			roleName = #{roleName},
		
		where id = #{id}
	

六、创建测试类,测试数据源是否通了

    以上spring框架及spring+mybatis配置基本完成,再就是创建测试类测试数据源是否通

 首先创建一个mysql库的,再建立users表,创建测试类TestSpring.java如下:

   

package com.liuhai.eshop;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.liuhai.eshop.domain.User;
import com.liuhai.eshop.service.UserService;

public class TestSpring {
	@Test
	public void TestUserService() throws Exception{
		@SuppressWarnings("resource")
		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService us=(UserService) ac.getBean("userService");
		User user=new User();
		user.setAge(1);
		user.setUserName("zhangsan");
		user.setPassword("123456");
		user.setTrueName("张三");
		us.add(user);
	}
}
最后查询users表中是否有新插入的数据。

七、整合SpringMVC

7.1、配置spring-mvc.xml

配置里面的注释也很详细,在此就不说了,主要是自动扫描控制器,视图模式,注解的启动这三个



	
	  
	
      
      
          
              
                text/html;charset=UTF-8  
              
          
      
     
     
      
          
              
                   
              
          
      
	
		
		
	
	
		 
		
		  
		
		  
		
	

7.2、配置web.xml文件

         这里面对applicationContext.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合,之前2框架整合不需要在此处进行任何配置。配置一样有详细注释,不多解释了。


  
    
    web 测试页面
      
    
    	contextConfigLocation
    	classpath:applicationContext.xml
    
    
    
    	encodingFilter
    	org.springframework.web.filter.CharacterEncodingFilter
    	true
    	
    		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
    	true
    
    
    	springMVC
    	  
    	*.do
    
    
    
        default
        *.css
    
    
        default
        *.gif
    
    
        default
        *.png
    
    
        default
        *.jpg
    
    
        default
        *.js
    
    
    	/index.jsp  
    

7.3 新建控制类controller及jsp页面之间交互

    在这里使用jsp页面引入easyui集成并实现增删改查功能

userManage.jsp如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


  
    
    
    My JSP 'userManage.jsp' starting page
    
	
	
	    
	
	
	
    
    
    
    
	
  
  
  
    
编号 用户名 密码 真实姓名 邮件 联系电话 角色
添加 修改 删除
用户名: 查询
用户名: * 密码: *
真实姓名: * 邮箱: *
联系电话: * 用户角色: *

UserController.java

package com.liuhai.eshop.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liuhai.eshop.domain.User;
import com.liuhai.eshop.service.UserService;
import com.liuhai.eshop.util.PageBean;
import com.liuhai.eshop.util.ResponseUtil;
import com.liuhai.eshop.util.StringUtil;

@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger log=LoggerFactory.getLogger(UserController.class);
	@Resource
	private UserService userService;
	
	@RequestMapping("/showUser.do")
	public String toIndex(HttpServletRequest request,Model model){
		System.out.println("liuhaitest");
		return "showUser";
	}
	// /user/test.do?id=1
    @RequestMapping(value="/test.do",method=RequestMethod.GET)  
    public String test(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt(request.getParameter("id"));  
        System.out.println("userId:"+userId);
        User user=null;
        if (userId==1) {
             user = new User();  
             user.setAge(11);
             user.setId(1);
             user.setPassword("123");
             user.setUserName("javen");
        }
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "index";  
    }  
    // /user/showUser.do?id=1
    @RequestMapping(value="/showUser.do",method=RequestMethod.GET)  
    public String toindex(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt(request.getParameter("id"));  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "showUser";  
    }  
    
 // /user/showUser2.do?id=1
    @RequestMapping(value="/showUser2.do",method=RequestMethod.GET)  
    public String toIndex2(@RequestParam("id") String id,Model model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "showUser";  
    }  

    // /user/jsontype.do?id=1
    @RequestMapping(value="/jsontype.do",method=RequestMethod.GET)  
    public @ResponseBody User getUserInJson(@RequestParam("id") String id,Map model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.info(user.toString());
        return user;  
    }  
    // /user/jsontype2.do?id=1
    @RequestMapping(value="/jsontype2.do",method=RequestMethod.GET)  
    public ResponseEntity  getUserInJson2(@RequestParam("id") String id,Map model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.info(user.toString());
        return new ResponseEntity(user,HttpStatus.OK);  
    } 
    
    //文件上传页面
    @RequestMapping(value="/upload.do")
    public String showUploadPage(){
        return "file";
    }
    //文件上传
    @RequestMapping(value="/doUpload.do",method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{
        if (!file.isEmpty()) {
            log.info("Process file:{}",file.getOriginalFilename());
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename()));
        return "succes";
    }
    /**
     * 用户管理页面
     * @return
     */
    @RequestMapping(value="/userManage.do")
    public String userManagePage(){
        return "userManage";
    }
	/**
	 * 添加或者修改
	 * @param user
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save.do")
	public String save(User user,HttpServletResponse res) throws Exception{
		//操作记录条数,初始化为0
		int resultTotal = 0;
		if (user.getId() == null) {
			resultTotal = userService.add(user);
		}else{
			resultTotal = userService.update(user);
		}
		JSONObject jsonObject = new JSONObject();
		if(resultTotal > 0){   //说明修改或添加成功
			jsonObject.put("success", true);
		}else{
			jsonObject.put("success", false);
		}
		ResponseUtil.write(res, jsonObject);
		return null;
	}
	/**
	 * 用户分页查询
	 * @param page
	 * @param rows
	 * @param s_user
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list.do")
	public String list(@RequestParam(value="page",required=false) String page,@RequestParam(value="rows",required=false) String rows,User s_user,HttpServletResponse res) throws Exception{
		PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		Map map=new HashMap();
		map.put("userName", StringUtil.formatLike(s_user.getUserName()));
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List userList=userService.find(map);
		Long total=userService.getTotal(map);
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(userList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(res, result);
		return null;
	}
	/**
	 * 删除用户
	 * @param ids
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete.do")
	public String delete(@RequestParam(value="ids") String ids,HttpServletResponse res) throws Exception{
		String[] idStr = ids.split(",");
		JSONObject jsonObject = new JSONObject();
		for (String id : idStr) {
			userService.delete(Integer.parseInt(id));
		}
		jsonObject.put("success", true);
		ResponseUtil.write(res, jsonObject);
		return null;
	}
}

7.4其它工具类及jsp页面

   分页Model类PageBean.java

package com.liuhai.eshop.util;
/**
 * 分页Model类
 * @author Administrator
 *
 */
public class PageBean {
	private int page; // 第几页
	private int pageSize; // 每页记录数
	private int start;  // 起始页
	public PageBean(int page, int pageSize) {
		super();
		this.page = page;
		this.pageSize = pageSize;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getStart() {
		return (page-1)*pageSize;
	}
}

  用于返回json数据ResponseUtil.java

package com.liuhai.eshop.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
/***
 * 主要用于返回json数据
 * @author Administrator
 */
public class ResponseUtil {
	public static void write(HttpServletResponse response,Object object)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(object);
		out.flush();
		out.close();
	}
}

字符串工具类StringUtil.java如下:

package com.liuhai.eshop.util;
/***
 * 字符串工具类
 * @author Administrator
 *
 */
public class StringUtil {
	 /**
     * 判断是否是空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str){
        if(str==null||"".equals(str.trim())){
            return true;
        }else{
            return false;
        }
    }
    
    /**
     * 判断是否不是空
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str){
        if((str!=null)&&!"".equals(str.trim())){
            return true;
        }else{
            return false;
        }
    }
    
    /**
     * 格式化模糊查询
     * @param str
     * @return
     */
    public static String formatLike(String str){
        if(isNotEmpty(str)){
            return "%"+str+"%";
        }else{
            return null;
        }
    }
}

上传文件file.jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>




Insert title here


    

上传文件

八、项目结果及目录

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现_第4张图片SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现_第5张图片

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现_第6张图片





















     





你可能感兴趣的:(系统框架)