SSM框架整合-实现CRUD,登录和分页操作

一.项目git地址:https://github.com/807028059/Test-User

二.项目结构:spring+springmvc+mybatis+maven+mysql+freemark+jetty

三.项目介绍:主要实现登录 crud以及分页效果

1.登录界面

SSM框架整合-实现CRUD,登录和分页操作_第1张图片

2.主页

SSM框架整合-实现CRUD,登录和分页操作_第2张图片

3.添加页面

SSM框架整合-实现CRUD,登录和分页操作_第3张图片

4.编辑页面

SSM框架整合-实现CRUD,登录和分页操作_第4张图片

四.搭建

1)准备配置文件

jar包依赖    这里推荐一个插件 mavenHelper.jar  可以自动检测jar包的冲突依赖关系  


  4.0.0
  com.zj
  Test-User
  war
  0.0.1-SNAPSHOT
  
    UTF-8
    UTF-8
    
    4.3.2.RELEASE
    1.7.2
  
  
    
    
      org.springframework
      spring-web
      ${spring.version}
    

    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    

    
    
      javax.servlet
      javax.servlet-api
      3.0.1
    

    
    
      org.springframework
      spring-test
      ${spring.version}
    

    
   


    
      junit
      junit
      4.12
    

    
    
      org.springframework
      spring-jdbc
      ${spring.version}
    

    
    
      org.springframework
      spring-tx
      ${spring.version}
    

    
      org.springframework
      spring-context-support
      ${spring.version}
    
    
    
      org.aspectj
      aspectjweaver
      1.8.9
    

    
    
      org.apache.tomcat
      tomcat-jdbc
      7.0.42
    

    
    
      org.mybatis
      mybatis
      3.4.1
    

    
    
      org.mybatis
      mybatis-spring
      1.3.0
    

    
    
      mysql
      mysql-connector-java
      5.1.39
    

    
    
      org.slf4j
      slf4j-log4j12
      ${slf4j.version}
    

    
      org.slf4j
      slf4j-api
      ${slf4j.version}
    

    
    
      com.github.miemiedev
      mybatis-paginator
      1.2.17
      
        
          mybatis
          org.mybatis
        
      
    

    
    
      org.freemarker
      freemarker
      2.3.21
    

    
    
      org.apache.commons
      commons-lang3
      3.3.2
    

    
    
      com.alibaba
      fastjson
      1.2.13
    

    
      com.fasterxml.jackson.core
      jackson-databind
      2.8.1
    

    
      org.codehaus.jackson
      jackson-mapper-asl
      1.9.12
    

    
    
      com.google.code.gson
      gson
      2.8.0
    

    
    
      com.github.axet
      kaptcha
      0.0.9
    

    
    
      org.springframework.session
      spring-session
      1.3.1.RELEASE
    

    
      redis.clients
      jedis
      2.9.0
    

    
      org.testng
      testng
      RELEASE
    

    
  
  
    Test-User
    

    
      
      
        org.apache.maven.plugins
        maven-compiler-plugin
        2.3.2
        
          1.7
          1.7
          UTF-8
          
            ${java.home}/lib/rt.jar
          
        
      

      
        org.eclipse.jetty
        jetty-maven-plugin
        9.2.1.v20140609
        
          
          
          
          
            
            
          
        
      
    

  

准备spring-mybatis.xml    spring集成对数据库的配置



    
    
    
    
        
    

    
    
        
            
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
            
        
    

    
    
    
        
        
        
        
        
        
    


    
    
        
        
    


    
    
        
    

    
    
        
            
            
            
            
            
            
            
            
        
    

    
    
        
        
        
    


准备spring-mvc.xml   配置视图  aop



    
    
    

    
    


    
    

    
    
        
        
        
            
                0.########## 
                true,false 
                square_bracket 
                true 
                0 
                UTF-8
                yyyy-MM-dd HH:mm:ss
                yyyy-MM-dd
                HH:mm:ss
            
        
        
            
                
            
        
    

    
    
        
        
        
    

    
    
        
            
            
        
    


准备mybatis.xml   配置实体层和分页插件




    
    
        
        
    

    
        
        
            
        
    

准备log4j.porperties

# Global logging configuration  
log4j.rootLogger=INFO,stdout,file  
# MyBatis logging configuration...
log4j.logger.com.sdrd.mapper=DEBUG  
#log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.Target=System.out  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] %c{1}:%L - %m%n  

### direct messages to file file.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.file.DatePattern='.'yyyy-MM-dd'.log'   
log4j.appender.file.Threshold = INFO  
log4j.appender.file.append=true  
log4j.appender.file.File=./logs/info.log 
log4j.appender.file.layout=org.apache.log4j.PatternLayout  
log4j.appender.file.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss} %5p %c{1}:%L - %m%n

jdbc.porperties配置文件

JDBC.username=root
JDBC.password=root
JDBC.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
JDBC.driver=com.mysql.jdbc.Driver

这些文件都是放在resource下

SSM框架整合-实现CRUD,登录和分页操作_第5张图片

 

web.xml配置   web项目的入口  配置扫描以上文件产生联动



  Archetype Created Web Application
  
  
    contextConfigLocation
    classpath:spring-mybatis.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
    
    /
  

  
    /index.jsp
  


 

2)准备实体类

SSM框架整合-实现CRUD,登录和分页操作_第6张图片

因为要进行分页操作先定义一个BaseDto

package com.zj.model;

import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import org.apache.commons.lang3.StringUtils;

public class BaseDto {
    private Integer page;
    private Integer pageSize;
    private String sort;

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public PageBounds buildPageBounds(){
        if(this.page == null||this.page<1){
            this.page = 1;
        }
        if(this.pageSize==null||this.pageSize<1){
            this.pageSize = 2;
        }
        PageBounds pageBounds = new PageBounds(this.page,this.pageSize);
        if (StringUtils.isNotBlank(this.sort)) {
            pageBounds.setOrders(Order.formString(this.sort));
        }
        return pageBounds;
    }
}

接着定义User类和Student类

package com.zj.model;

import java.io.Serializable;

public class User implements Serializable{
    private Integer userId;
    private String userName;
    private String userPassword;
    private Integer uid;

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPassword() {
        return userPassword;
    }
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userPassword='" + userPassword + '\'' +
                ", uid=" + uid +
                '}';
    }
}
package com.zj.model;

public class Student extends BaseDto{
    private Integer id;
    private String name;
    private Integer gender;
    private Integer age;
    private Integer uid;

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender=" + gender +
                ", age=" + age +
                ", uid=" + uid +
                '}';
    }
}

建完以后大家是不是发现有个IsLogin的注解类  这个注解是用来进行登录验证的  想想看  进行crud的时候是不是要登录以后才能进行  那我们利用aop和注解实现这么一个功能   在crud的方法上加上这个标签就可以实现这个功能是不是就很简单  开始

 

定义一个注解的名字

package com.zj.model;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsLogin {

}

 然后给这个注解加上功能

SSM框架整合-实现CRUD,登录和分页操作_第7张图片

package com.zj.proxy;

import com.zj.exception.LoginException;
import com.zj.model.IsLogin;
import com.zj.model.User;
import javafx.fxml.LoadException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

@Component
@Aspect
public class LoginProxy {

    @Autowired
    private HttpSession session;

    @Pointcut(value = "@annotation(com.zj.model.IsLogin)")
    private void pointcut(){

    }

    @Before(value="pointcut()")
    public void beforeMethod(JoinPoint joinPoint){
        User user = (User) session.getAttribute("user");
        System.out.println("-------进行登录验证-------");
        if(user == null){
            throw new LoginException("请先登录");
        }
    }

}

接着来  定义一个结果类  什么操作都要有个结果 对吧  这样前台才好判断是不是执行成功或者失败 对吧

package com.zj.result;

public class ResultInfo {
    String mes;
    int code;
    public ResultInfo(){

    }
    public ResultInfo(String mes){
        this.mes = mes;
    }

    public String getMes() {
        return mes;
    }

    public void setMes(String mes) {
        this.mes = mes;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}

2)准备工具类和异常类

package com.zj.exception;

import com.alibaba.fastjson.JSON;
import com.zj.controller.BaseController;
import com.zj.result.ResultInfo;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class GlobalExceptionHandler extends BaseController {

    @ExceptionHandler(value = LoginException.class)
    public String handlerParamException(LoginException loginException, HttpServletRequest request,
                                        HttpServletResponse response,Model model){
        model.addAttribute("proPath", request.getContextPath());

        String xmlHttpRequest = request.getHeader("X-Requested-With");

        return "login";
    }
}
package com.zj.exception;

public class LoginException extends RuntimeException {

    private int errCode;

    public int getErrCode() {
        return errCode;
    }

    public void setErrCode(int errCode) {
        this.errCode = errCode;
    }

    public LoginException(){

    }

    public LoginException(String mes) {
        super(mes);
    }


}
package com.zj.exception;

public class ParameterException extends RuntimeException {

    public ParameterException(){

    }

    public ParameterException(String mes){
        super(mes);
    }


}

 

package com.zj.util;

import com.zj.exception.ParameterException;

public class AssertUtil {

    public static void isNull(Object value){
        if(value == null){
            throw new ParameterException("不能空");
        }
    }
}

 

3)准备dao,service和controller的编写

再来写用户登陆的Dao层和对学生操作的Dao层

package com.zj.dao;

import com.zj.model.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserDao {
    @Select("select * from usertable where userName =#{userName} and userPassword =#{userPassword}")
    public User login(User user);

    /*测试*/
    List test();
}

 

package com.zj.dao;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.zj.model.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentDao {
    @Select("select a.* from student a,usertable b where a.uid=b.uid and limit #{limit}")
    PageList findListStudent(@Param(value = "limit") Integer limit);

    @Select("select * from student ")
    PageList findStudent(PageBounds pageBounds);


    @Select("select a.* from student a,usertable b where a.uid=b.uid and a.id=#{id}")
    Student findStudentById(@Param(value = "id") Integer id);

    @Update({"insert student(name,gender,age,uid) values(#{name},#{gender},#{age},#{uid})"})
    void addStudent(Student student);

    @Update({"UPDATE student set name=#{name},gender=#{gender},age=#{age} where id = #{id} and uid=#{uid}"})
    void updateStudent(Student student);

    @Delete("delete from student where id=#{id} and uid=#{uid}")
    void deleteStudent(@Param(value = "id") Integer id,@Param(value = "uid") Integer uid);
}

 

接着来service层

package com.zj.service;

import com.zj.dao.UserDao;
import com.zj.model.User;
import com.zj.util.RedisUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService{

    @Autowired
    private UserDao userDao;
    private Logger log = Logger.getLogger(UserService.class);
    RedisUtil r = new RedisUtil();

    public User login(User user,String id) {
        log.info("用户登录:"+user);
        return userDao.login(user);
    }
}
package com.zj.service;

import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.zj.dao.StudentDao;
import com.zj.model.Student;
import com.zj.result.ResultInfo;
import com.zj.util.AssertUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {

    @Autowired
    private StudentDao studentDao;
    private static Logger log = Logger.getLogger(StudentService.class);

    public ResultInfo addStudent(Integer uid,Student student){
        ResultInfo resultInfo = new ResultInfo();
        log.info("addStudent入参:"+resultInfo);
        if(student!=null){
            student.setUid(uid);
            studentDao.addStudent(student);
            resultInfo.setCode(200);
            resultInfo.setMes("添加成功");
            return resultInfo;
        }
        resultInfo.setCode(300);
        resultInfo.setMes("添加失败");
        return resultInfo;
    }

    public ResultInfo updateStudent(Student student,Integer uid){
        ResultInfo resultInfo = new ResultInfo();
        log.info("updateStudent入参:"+student.toString());
        if(student!=null){
            student.setUid(uid);
            studentDao.updateStudent(student);
            resultInfo.setCode(200);
            resultInfo.setMes("添加成功");
            return resultInfo;
        }
        resultInfo.setCode(300);
        resultInfo.setMes("添加失败");
        return resultInfo;
    }


    public void deleteStudent(Integer id,Integer uid){
        AssertUtil.isNull(id);
        studentDao.deleteStudent(id,uid);
        log.info("deleteStudents删除ID:"+id);
    }

    public Student findStudentById(Integer id,Integer uid){
        AssertUtil.isNull(id);
        log.info("findStudentById寻找ID:"+id);
        return studentDao.findStudentById(id);
    }


    public PageList findListStudent(Integer limit){

        PageList students = studentDao.findListStudent(limit);

        return students;
    }

    public PageList findStudent(Student student){
        PageList students = studentDao.findStudent(student.buildPageBounds());
        return students;
    }
}

再来controller层

首先来个BaseController  存储项目路径(tomcat启动的有用)

package com.zj.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;

public class BaseController {
    @ModelAttribute
    protected void preMethod(HttpServletRequest request, Model model) {
        String ctx = request.getContextPath();
        System.out.println("ctx------------->"+ctx);
        model.addAttribute("proPath",ctx);
    }
}

接着用户和学生的controller层

package com.zj.controller;

import com.zj.model.User;
import com.zj.result.ResultInfo;
import com.zj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
@RequestMapping("user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    /*
    * 登录操作
    * */
    @RequestMapping("login")
    @ResponseBody
    public ResultInfo login(User user, HttpServletRequest request, HttpSession session){
        ResultInfo resultInfo = new ResultInfo();
        String id = request.getSession().getId();
        User acc= userService.login(user,id);
        System.out.println("sessioid---------------->"+id);
        if(acc!=null){
            //存session
            session.setAttribute("user", acc);
            resultInfo.setCode(200);
            resultInfo.setMes("登陆成功");
            return resultInfo;
        }
        resultInfo.setCode(300);
        resultInfo.setMes("登录失败");
        return resultInfo;
    }

    /*
    * 跳转主页
    * */
    @RequestMapping("index")
    public String index(HttpServletRequest request, HttpSession session){
        User user = (User)session.getAttribute("user");
        if(user!=null){
            return "redirect:/student/main";
        }
        return "login";
    }

    /*
    * 登出操作
    * */
    @RequestMapping("out")
    public String out(HttpSession session){
        session.removeAttribute("user");
        return "login";
    }

    /*
    * 生成验证码
    * */
    @RequestMapping("yzm")
    public void sendYzm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 图片高度
        final int IMG_HEIGHT = 100;
        // 图片宽度
        final int IMG_WIDTH = 25;
        // 验证码长度
        final int CODE_LEN = 4;

        // 用于绘制图片,设置图片的长宽和图片类型(RGB)
        BufferedImage bi = new BufferedImage(IMG_HEIGHT, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);
        // 获取绘图工具
        Graphics graphics = bi.getGraphics();
        graphics.setColor(new Color(100, 230, 200)); // 使用RGB设置背景颜色
        graphics.fillRect(0, 0, 100, 30); // 填充矩形区域

        // 验证码中所使用到的字符
        char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();
        String captcha = ""; // 存放生成的验证码
        Random random = new Random();
        for(int i = 0; i < CODE_LEN; i++) { // 循环将每个验证码字符绘制到图片上
            int index = random.nextInt(codeChar.length);
            // 随机生成验证码颜色
            graphics.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(255)));
            // 将一个字符绘制到图片上,并制定位置(设置x,y坐标)
            graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
            captcha += codeChar[index];
        }
        // 将生成的验证码code放入sessoin中
        request.getSession().setAttribute("code", captcha);
        // 通过ImageIO将图片输出
        ImageIO.write(bi, "JPG", response.getOutputStream());
    }

    /*
    * 验证码校验
    * */
    @RequestMapping("check")
    @ResponseBody
    public ResultInfo checkYzm(HttpServletRequest request, HttpServletResponse response){
        ResultInfo resultInfo = new ResultInfo();
        // 获取存放在session中的验证码
        String code = (String) request.getSession().getAttribute("code");
        // 获取页面提交的验证码
        String inputCode = request.getParameter("code");
        if(code.toLowerCase().equals(inputCode.toLowerCase())) { // 验证码不区分大小写
            // 验证成功,跳转到成功页面
            resultInfo.setCode(200);
        } else { // 验证失败
            resultInfo.setCode(300);
            resultInfo.setMes("验证码错误");
        }
        return resultInfo;
    }
}

 

package com.zj.controller;

import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.zj.model.IsLogin;
import com.zj.model.Student;
import com.zj.model.User;
import com.zj.result.ResultInfo;
import com.zj.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("student")
public class StudentController extends BaseController{
    @Autowired
    private StudentService studentService;

    /*
    * 添加操作
    * */
    @RequestMapping("add")
    @ResponseBody
    @IsLogin
    public ResultInfo addStudent(HttpServletRequest request,Student student){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        int uid = user.getUid();
        return studentService.addStudent(uid,student);
    }

    /*
    * 跳转添加视图
    * */
    @RequestMapping("addView")
    @IsLogin
    public String addView(){
        return "addView";
    }


    /*
    * 跳转主页
    * */
    @RequestMapping("main")
    @IsLogin
    public String findListStudent(Student student, Model model){
        PageList students = studentService.findStudent(student);
        model.addAttribute("students",students);
        model.addAttribute("pagenator",students.getPaginator());
        model.addAttribute("student",student);
        return "main";
    }

    /*
    * 删除操作
    * */
    @RequestMapping("delete/{id}")
    @IsLogin
    public String deleteStudent(@PathVariable Integer id,@PathVariable Integer uid){
        studentService.deleteStudent(id,uid);
        return "redirect:/student/main";
    }

    /*
    * 跳转编辑页面
    * */
    @RequestMapping("updateView/{id}")
    @IsLogin
    public String updateView(@PathVariable Integer id,Model model,HttpSession session){
        User user = (User) session.getAttribute("user");
        Student student = studentService.findStudentById(id,user.getUid());
        model.addAttribute("student",student);
        return "update";
    }


    /*
    * 编辑操作
    * */
    @RequestMapping("update")
    @ResponseBody
    public ResultInfo updateStudent(Student student, HttpServletRequest request, HttpSession session){
        User user = (User) session.getAttribute("user");
        /*if(user == null){
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.setCode(300);
            resultInfo.setMes("请先登录");
            return resultInfo;
        }*/
        return  studentService.updateStudent(student,user.getUid());
    }

}

其实我这不规范  对逻辑的处理都应该放在service层的  懒得改了...  有兴趣的同学自行修改

 

因为前台使用的freemark所以  页面的展示数据我通过TemplateDirectiveModel实现

package com.zj.directive;

import com.alibaba.fastjson.JSON;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;

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

public abstract class BaseDirective implements TemplateDirectiveModel{

    //获取参数值
    public  T getParameter(String paramName,Map params,Class clazz)
            throws TemplateException{
        BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build();
        //获取参数
        TemplateModel templateModel = (TemplateModel) params.get(paramName);
        T value = (T) beansWrapper.unwrap(templateModel, clazz);

        return value;
    }

    //输出
    public void setVariable(Environment env, TemplateDirectiveBody body,String key,Object value)
            throws TemplateException,IOException{
        BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build();
        TemplateModel templateModel = beansWrapper.wrap(value);
        env.setVariable(key, templateModel);
        // 输出
        if (body != null) {
            body.render(env.getOut());
        } else {
            env.getOut().write(JSON.toJSONString(value));
        }
    }
}
package com.zj.directive;

import com.alibaba.fastjson.JSON;
import com.zj.model.Student;
import com.zj.model.User;
import com.zj.service.StudentService;
import com.zj.service.UserService;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class StudentDirective extends BaseDirective{

    @Autowired
    private StudentService studentService;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {

        Integer limit = getParameter("limit", params, Integer.class);

        List students = studentService.findListStudent(limit);

        setVariable(env,body,"students",students);

    }
}

 

4)全部完成后  进行前台页面的编写

SSM框架整合-实现CRUD,登录和分页操作_第8张图片

登录页




    Login page
    
    
    


验证码 看不清?
${requestScope.msg}

主页



    Main
    
    



    
[#if students?has_content] [#list students as student] [/#list] [#else] [/#if]
编号 姓名 级别 年龄 操作
${student.id} ${student.name} ${student.gender} ${student.age} [#--购买|--] 编辑| 删除
无数据...
[#if pagenator.totalPages>1] [#if pagenator.isFirstPage()] [#else] 首页 [/#if] [#if pagenator.hasPrePage] 上一页 [#else]   [/#if] [#list pagenator.slider(3) as slider ] [#if slider==pagenator.page ] ${slider} [#else] ${slider} [/#if] [/#list] [#if pagenator.hasNextPage] 下一页 [#else]   [/#if] [#if pagenator.isLastPage()]   [#else] 末页 [/#if] [/#if]
添加 退出

添加页



    Main
    
    



姓名
级别
年龄

编辑页



    Main
    
    



姓名
级别
年龄

五.数据库的表新建

用的mysql  两张表

CREATE TABLE `usertable` (
  `userId` int(11) DEFAULT NULL,
  `userName` varchar(255) DEFAULT NULL,
  `userPassword` varchar(255) DEFAULT NULL,
  `uid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `student` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `gender` int(11) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `uid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

 

六.完成

以上搭建完成后  最后配置jetty运行

SSM框架整合-实现CRUD,登录和分页操作_第9张图片

 

七.结语

写的比较粗糙  大致介绍了ssm框架的基本操作  关于ssm结合xml进行sql编写的配置请看

https://blog.csdn.net/weixin_41634885/article/details/82022187

 

有问题留言

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(SSM)