SpringMVC---CRUD实现

思路分析

  • 搭建环境
  • 逆向生层对应的类(model、mapper.xml、mapper.java)
  • 编写业务逻辑层
  • 编写web层(控制器)
  • 前端页面

一、环境搭建

1.1、导入项目所需依赖(pom.xml)


  4.0.0
  org.example
  liwen_zyssm
  war
  1.0-SNAPSHOT
  liwen_zyssm Maven Webapp
  http://maven.apache.org
 
  
    UTF-8
    1.8
    1.8
    3.7.0
 
    
    
    5.0.2.RELEASE
    
    3.4.5
    
    5.1.44
    
    5.1.2
    
    1.3.1
    
    2.1.1
    2.4.3
    
    2.9.1
    3.2.0
    1.7.13
    
    4.12
    4.0.0
    1.18.2
 
    1.1.0
    2.10.0
 
    2.9.0
    1.7.1.RELEASE
    2.9.3
    1.2
    1.1.2
    8.0.47
    1.3.3
    5.0.2.Final
 
    1.3.2
  
 
  
    
    
      org.springframework
      spring-core
      ${spring.version}
    
    
      org.springframework
      spring-beans
      ${spring.version}
    
    
      org.springframework
      spring-context
      ${spring.version}
    
    
      org.springframework
      spring-orm
      ${spring.version}
    
    
      org.springframework
      spring-tx
      ${spring.version}
    
    
      org.springframework
      spring-aspects
      ${spring.version}
    
    
      org.springframework
      spring-web
      ${spring.version}
    
 
    
      org.springframework
      spring-test
      ${spring.version}
    
 
 
    
    
      org.mybatis
      mybatis
      ${mybatis.version}
    
    
    
      mysql
      mysql-connector-java
      ${mysql.version}
    
    
    
      com.github.pagehelper
      pagehelper
      ${pagehelper.version}
    
    
    
      org.mybatis
      mybatis-spring
      ${mybatis.spring.version}
    
 
    
      org.springframework
      spring-context-support
      ${spring.version}
    
 
    
    
      org.mybatis.caches
      mybatis-ehcache
      ${mybatis.ehcache.version}
    
    
    
      net.sf.ehcache
      ehcache
      ${ehcache.version}
    
 
    
      redis.clients
      jedis
      ${redis.version}
    
    
      org.springframework.data
      spring-data-redis
      ${redis.spring.version}
    
    
      com.fasterxml.jackson.core
      jackson-databind
      ${jackson.version}
    
    
      com.fasterxml.jackson.core
      jackson-core
      ${jackson.version}
    
    
      com.fasterxml.jackson.core
      jackson-annotations
      ${jackson.version}
    
 
    
    
      org.apache.commons
      commons-dbcp2
      ${commons.dbcp2.version}
      
        
          commons-pool2
          org.apache.commons
        
      
    
    
      org.apache.commons
      commons-pool2
      ${commons.pool2.version}
    
 
    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    
 
    
 
    
    
    
    
      org.slf4j
      slf4j-api
      ${slf4j.version}
    
    
      org.slf4j
      jcl-over-slf4j
      ${slf4j.version}
      runtime
    
 
    
    
      org.apache.logging.log4j
      log4j-api
      ${log4j2.version}
    
    
      org.apache.logging.log4j
      log4j-core
      ${log4j2.version}
    
    
    
      org.apache.logging.log4j
      log4j-slf4j-impl
      ${log4j2.version}
    
    
    
      org.apache.logging.log4j
      log4j-web
      ${log4j2.version}
      runtime
    
 
    
    
      com.lmax
      disruptor
      ${log4j2.disruptor.version}
    
 
    
    
      junit
      junit
      ${junit.version}
      test
    
    
      javax.servlet
      javax.servlet-api
      ${servlet.version}
      provided
    
    
      org.projectlombok
      lombok
      ${lombok.version}
      provided
    
    
      jstl
      jstl
      ${jstl.version}
    
    
      taglibs
      standard
      ${standard.version}
    
    
      org.apache.tomcat
      tomcat-jsp-api
      ${tomcat-jsp-api.version}
    
    
      commons-fileupload
      commons-fileupload
      ${commons-fileupload.version}
    
 
    
      org.hibernate
      hibernate-validator
      ${hibernate-validator.version}
    
 
    
    
      org.apache.shiro
      shiro-core
      ${shiro.version}
    
    
      org.apache.shiro
      shiro-web
      ${shiro.version}
    
    
      org.apache.shiro
      shiro-spring
      ${shiro.version}
    
  
 
  
    liwen_zyssm
    
      
      
        src/main/java
        
          **/*.xml
        
      
      
      
        src/main/resources
        
          jdbc.properties
          *.xml
        
      
    
    
      
        org.apache.maven.plugins
        maven-compiler-plugin
        ${maven.compiler.plugin.version}
        
          ${maven.compiler.source}
          ${maven.compiler.target}
          ${project.build.sourceEncoding}
        
      
      
        org.mybatis.generator
        mybatis-generator-maven-plugin
        1.3.2
        
          
          
            mysql
            mysql-connector-java
            ${mysql.version}
          
        
        
          true
        
      
    
  

1.2、数据库配置信息

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

1.3、代码生成插件--配置文件(generatorConfig.xml)



 

    
    
 
    
    
 
    
    
        
        
            
             
        
 
        
        
            

        
 
        
        
            
            
        
 
        
        
        
        
            
            
            
            
            
            
            
            
        
 
        
        
            
            
        
 
        
        
        
        
        
            
            
        
 
        
        
        
        
        
        
        
        
        
        
        
        
        
        

1.4、spring与mybatis整合的配置文件 spring-mybatis.xml  



    
    
    
    
    
 
    
 
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
 
    
    
    
        
        
        
        
        
        
        
        
            
                
                    
                        
                            helperDialect=mysql
                        
                    
                
            
        
    
 
    
    
    
        
        
        
        
    
    
        
    
    
    

1.5、spring-context.xml 上下文配置文件  



 
    
    

 1.6、spring-mvc-xml: 配置Spring框架的一些关键组件和功能



    
    
 
    
    
 
    
    
        
        
        
        
    
 
    
    
    
    
 
    
    

1.7、配置web.xml 



  Archetype Created Web Application
  
  
  
    contextConfigLocation
    classpath:spring-context.xml
  
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
 
  
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    true
    
      encoding
      UTF-8
    
  
  
    encodingFilter
    /*
  
  
  
    SpringMVC
    org.springframework.web.servlet.DispatcherServlet
    
    
      contextConfigLocation
      classpath:spring-mvc.xml
    
    1
    
    true
  
  
    SpringMVC
    /
  

1.8、分页所需要的配置

1.8.1、分页工具类

package com.liwen.utils;
 
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
 
public class PageBean implements Serializable {
 
	private static final long serialVersionUID = 2422581023658455731L;
 
	//页码
	private int page=1;
	//每页显示记录数
	private int rows=10;
	//总记录数
	private int total=0;
	//是否分页
	private boolean isPagination=true;
	//上一次的请求路径
	private String url;
	//获取所有的请求参数
	private Map map;
	
	public PageBean() {
		super();
	}
	
	//设置请求参数
	public void setRequest(HttpServletRequest req) {
		String page=req.getParameter("page");
		String rows=req.getParameter("rows");
		String pagination=req.getParameter("pagination");
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		this.url=req.getContextPath()+req.getServletPath();
		this.map=req.getParameterMap();
	}
	public String getUrl() {
		return url;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public Map getMap() {
		return map;
	}
 
	public void setMap(Map map) {
		this.map = map;
	}
 
	public int getPage() {
		return page;
	}
 
	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(null!=page&&!"".equals(page.trim()))
			this.page = Integer.parseInt(page);
	}
 
	public int getRows() {
		return rows;
	}
 
	public void setRows(int rows) {
		this.rows = rows;
	}
	
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows.trim()))
			this.rows = Integer.parseInt(rows);
	}
 
	public int getTotal() {
		return total;
	}
 
	public void setTotal(int total) {
		this.total = total;
	}
	
	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}
 
	public boolean isPagination() {
		return isPagination;
	}
	
	public void setPagination(boolean isPagination) {
		this.isPagination = isPagination;
	}
	
	public void setPagination(String isPagination) {
		if(null!=isPagination&&!"".equals(isPagination.trim()))
			this.isPagination = Boolean.parseBoolean(isPagination);
	}
	
	/**
	 * 获取分页起始标记位置
	 * @return
	 */
	public int getStartIndex() {
		//(当前页码-1)*显示记录数
		return (this.getPage()-1)*this.rows;
	}
	
	/**
	 * 末页
	 * @return
	 */
	public int getMaxPage() {
		int totalpage=this.total/this.rows;
		if(this.total%this.rows!=0)
			totalpage++;
		return totalpage;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int getNextPage() {
		int nextPage=this.page+1;
		if(this.page>=this.getMaxPage())
			nextPage=this.getMaxPage();
		return nextPage;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int getPreivousPage() {
		int previousPage=this.page-1;
		if(previousPage<1)
			previousPage=1;
		return previousPage;
	}
 
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
				+ "]";
	}
}

1.8.2、分页助手类

package com.liwen.tag;
 
import com.liwen.utils.PageBean;
 
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
 
public class PageTag extends BodyTagSupport{
	private PageBean pageBean;// 包含了所有分页相关的元素
	
	public PageBean getPageBean() {
		return pageBean;
	}
 
	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}
 
	@Override
	public int doStartTag() throws JspException {
//		没有标签体,要输出内容
		JspWriter out = pageContext.getOut();
		try {
			out.print(toHTML());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}
 
	private String toHTML() {
		StringBuffer sb = new StringBuffer();
//		隐藏的form表单---这个就是上一次请求下次重新发的奥义所在
//		上一次请求的URL
		sb.append("
"); sb.append(" "); // 上一次请求的参数 Map paramMap = pageBean.getMap(); if(paramMap != null && paramMap.size() > 0) { Set> entrySet = paramMap.entrySet(); for (Entry entry : entrySet) { // 参数名 String key = entry.getKey(); // 参数值 for (String value : entry.getValue()) { // 上一次请求的参数,再一次组装成了新的Form表单 // 注意:page参数每次都会提交,我们需要避免 if(!"page".equals(key)) { sb.append(" "); } } } } sb.append(""); // 分页条 sb.append("
    "); sb.append("
  • 首页
  • "); sb.append("
  • <
  • ");// less than 小于号 // sb.append("
  • 1
  • "); // sb.append("
  • 2
  • "); sb.append("
  • "+pageBean.getPage()+"
  • "); sb.append("
  • >
  • "); sb.append("
  • 尾页
  • "); sb.append("
  • 到第
  • "); sb.append("
  • 确定
  • "); sb.append("
  • 共"+pageBean.getTotal()+"条
  • "); sb.append("
"); // 分页执行的JS代码 sb.append(""); return sb.toString(); } }

1.8.3、tld文件


 

 
    liwen 1.1 core library
    liwen core
    1.1
    liwen
    http://jsp.veryedu.cn
 
    
        page
        com.liwen.tag.PageTag
        JSP
        
            pageBean
            true
            true
        
    
 

二、编写业务逻辑层(增删改查方法)

因为基本的增删改查都是插件自动生成的了,所以不需要再写了,这里加一个查询单个的sql

  

这里加了接口自然也是要加的

List listPager(User user);

业务逻辑层接口

package com.liwen.biz;
 
import com.liwen.model.User;
import com.liwen.utils.PageBean;
 
import java.util.List;
 
public interface UserBiz {
    int deleteByPrimaryKey(Long id);
 
    int insert(User record);
 
    int insertSelective(User record);
 
    User selectByPrimaryKey(Long id);
 
    int updateByPrimaryKeySelective(User record);
 
    int updateByPrimaryKey(User record);
 
    List listPager(User user, PageBean page);
}

实现接口

package com.liwen.biz.impl;
 
import com.liwen.biz.UserBiz;
import com.liwen.mapper.UserMapper;
import com.liwen.model.User;
import com.liwen.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.List;
 
/**
 * @author liwen
 */
@Service
public class UserBizImpl implements UserBiz {
    @Autowired
    private UserMapper userMapper;
 
    @Override
    public int deleteByPrimaryKey(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }
 
    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }
 
    @Override
    public int insertSelective(User record) {
        return userMapper.insertSelective(record);
    }
 
    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }
 
    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }
 
    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }
 
    @Override
    public List listPager(User user, PageBean page) {
        return userMapper.listPager(user);
    }
}

编写切面

如果需要分页则需进行代码,在spring-mvc-xml文件中已经配置了aop代理,如果注释掉将不会进行分页

package com.liwen.aspect;
 
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liwen.utils.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
 
import java.util.List;
 
/**
 * @author liwen
 */
@Aspect //代表当前为切面类
@Component //代表当前类交给spring进行管理
public class PageAspect {
    @Around("execution(* *..*Biz.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable {
        PageBean pageBean = null;
        //获取目标方法的所有参数
        Object[] args1 = args.getArgs();
        for (Object param:args1) {
            if (param instanceof PageBean){
                pageBean = (PageBean) param;
                break;
            }
        }
 
        if(pageBean!=null && pageBean.isPagination())
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
 
        //执行目标方法
        Object proceed = args.proceed();
        if(pageBean!=null && pageBean.isPagination()){
            PageInfo info = new PageInfo((List) proceed);
            pageBean.setTotal((int) info.getTotal());
        }
        return proceed;
    }
}

三、编写web控制层

package com.liwen.web;
 
import com.liwen.biz.UserBiz;
import com.liwen.model.User;
import com.liwen.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import javax.servlet.http.HttpServletRequest;
import java.util.List;
 
/**
 * @author liwen
 */
@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserBiz userBiz;
 
    /*新增方法*/
    @RequestMapping("/add")
    public String save(User user, HttpServletRequest request) {
        userBiz.insertSelective(user);
        return "redirect:list";
    }
 
    /*删除方法*/
    @RequestMapping("/del/{id}")
    public String del(@PathVariable("id") Long id, HttpServletRequest request) {
        userBiz.deleteByPrimaryKey(id);
        return "redirect:/users/list";
    }
 
    /*修改方法*/
    @RequestMapping("/edit")
    public String edit(User user, HttpServletRequest request) {
        userBiz.updateByPrimaryKeySelective(user);
        return "redirect:list";
    }
 
    /*查询方法*/
    @GetMapping("/list")
    public ModelAndView list(User user, HttpServletRequest request) {
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List users = userBiz.listPager(user, pageBean);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("users", users);
        modelAndView.addObject("pageBean", pageBean);
        modelAndView.setViewName("user/list");
 
        return modelAndView;
    }
 
    /*数据回显*/
    @RequestMapping("/preSave")
    public String preSave(User user, HttpServletRequest request) {
        if (user != null && user.getId() != null && user.getId() != 0) {
            User u = userBiz.selectByPrimaryKey(user.getId());
            request.setAttribute("u", u);
        }
        return "user/edit";
    }
}

四、前端页面

主界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="z" uri="http://jsp.veryedu.cn" %>


    
    
    
    
    博客列表
    


<%----%>
新增
用户ID 用户名 账号 密码 权限
${u.id } ${u.name } ${u.loginname } ${u.pwd } ${u.rid } 修改 删除

预编辑界面

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


    用户编辑、新增公共页面


用户id:
用户名:
账号:
密码:
权限:

你可能感兴趣的:(spring,maven,spring,cloud,mybatis,junit,log4j,java)