项目知识—SSM之前

1、用UML(用例图)去实现逻辑块分析

2、开发的生命周期

项目知识—SSM之前_第1张图片

3、业务流程图

项目知识—SSM之前_第2张图片

4、分页里面的逻辑五参数

package com.qf.dbutils;

import lombok.*;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageUtils {
    //当前页
    private Integer currentPageNo;
    //页量
    private Integer pageSize;
    //总记录数
    private Integer totalCount;
    //总页数
    private Integer totalPageSize;
    //集合
    private List userList;

}

5、非空工具类:StringUtils.isEmpty(mark)

6、狗皮膏药:pageContext.request.contextPath

7、分页的设置

首页 上一页 下一页 末页 共${userPageUtils.totalPageSize}页 当前为${userPageUtils.currentPageNo}/${userPageUtils.totalPageSize}

8、href='javaScript:void(0)'去掉原有的功能

9、$("#tv_table").append(text);追加

$("#tv_table").html(text);覆盖

10、$jsonList.each(function (){遍历

12、servlet类(jstl实现)

@WebServlet(name = "registerServlet", urlPatterns = "/registerServlet")
public class RegisterServlet extends BaseServlet {
    //实例化service对象
    private RegisterService registerService = new RegisterServiceImpl();

    public void selectRegister(HttpServletRequest request, HttpServletResponse response) {
        //获取前端的数据
        String rid = request.getParameter("rid");
        String dname = request.getParameter("dname");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String currentPageNo = request.getParameter("currentPageNo");
        String pageSize = request.getParameter("pageSize");
        PageUtils pageUtils = registerService.selectByPage(rid, dname, startTime, endTime, currentPageNo, pageSize);

        //回显数据
        if (!StringUtils.isEmpty(rid)) {
            request.setAttribute("rid", rid);
        }
        if (!StringUtils.isEmpty(dname)) {
            request.setAttribute("dname", dname);
        }
        if (!StringUtils.isEmpty(startTime)) {
            request.setAttribute("startTime", startTime);
        }
        if (!StringUtils.isEmpty(endTime)) {
            request.setAttribute("endTime", endTime);
        }


        //写入作用域中
        request.setAttribute("pageUtils", pageUtils);

        try {
            //转发回去
            request.getRequestDispatcher("registration/index.jsp").forward(request, response);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}

13、servlet类(json实现)(多)

@WebServlet(name = "UserServlet",urlPatterns = "/UserServlet")
public class UserServlet extends BaseServlet {
    //实例化service对象
    private UserService userService = new UserServiceImpl();


    public void selectAllPage(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        
        PrintWriter pw = resp.getWriter();

        //获取前端传递的数据
        String currentPageNo = req.getParameter("currentPageNo");
        String pageSize = req.getParameter("pageSize");
        PageUtils userPageUtils = userService.selectByPage(currentPageNo, pageSize);
        //将对象转为json对象
        String s = JSON.toJSONString(userPageUtils);
        System.out.println(s);
        //写入到前端
        pw.print(s);
        pw.close();


    }

    public void deleteByUid(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        //获取前端传递的数据
        String uid = req.getParameter("uid");
        //调用service方法
        userService.deleteById(uid);
        //重定向
        resp.sendRedirect("UserServlet?mark=selectAllPage");

    }


}

15、Dao层里面的动态拼接查询

package com.qf.dao.impl;

import com.alibaba.druid.util.StringUtils;
import com.mysql.cj.log.Log;
import com.qf.dao.UserDao;
import com.qf.dto.User;
import com.qf.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    //获取QueryRunner对象
    private QueryRunner qr = DBUtils.DB.getQr();

    /**
     * 条件查询
     * @param dname
     * @param uname
     * @param currentPageNo
     * @param pageSize
     * @return
     */
    @Override
    public List slectAllByCond(String dname, String uname,
                                     Integer currentPageNo, Integer pageSize) throws SQLException {
        //写sql语句,利用StringBuffer实现动态拼接
        StringBuffer sb = new StringBuffer();
        //固定语句
        sb.append("select u.*,d.dname as dname from user u inner join depart d on u.did=d.did where 1=1  ");

        //定义集合来拼接数据
        List resultList = new ArrayList<>();

        //非空判断
        if (!StringUtils.isEmpty(dname)){
            sb.append("and d.dname=?  ");
            //添加数据
            resultList.add(dname);
        }
        if (!StringUtils.isEmpty(uname)){
            sb.append("and u.uname like ?   ");
            //添加数据
            resultList.add("%"+dname+"%");
        }

        //拼接分页
        sb.append("limit ?,? ");
        //因为数据库从0开始
        resultList.add((currentPageNo-1)*pageSize);
        resultList.add(pageSize);

        //执行查询
        List userList = qr.query(sb.toString(), new BeanListHandler(User.class), resultList.toArray());

        return userList;
    }

    @Override
    public Integer selectCount(String dname, String uname) {
        //写sql语句,利用STringBuffer实现动态拼接
        StringBuffer sb = new StringBuffer();
        //固定语句
        sb.append("select count(1) from user u inner join depart d on u.did=d.did where 1=1  ");

        //定义集合用于存数据
        List dataList = new ArrayList<>();

        //非空判断
        if (!StringUtils.isEmpty(dname)){
            //添加语句进去
            sb.append("and d.dname=?  ");
            //添加数据
            dataList.add(dname);
        }

        if (!StringUtils.isEmpty(uname)){
            //添加语句
            sb.append("and u.uname like ?");
            //添加数据
            dataList.add("%"+uname+"%");
        }
        Long count = null;
        try {
            //对数据集合进行非空判断
            //执行带条件的查询
            //执行无条件的查询
             count = (dataList != null && dataList.size() > 0) ? qr.query(sb.toString(), new ScalarHandler<>(), dataList.toArray())
                    : qr.query(sb.toString(), new ScalarHandler<>());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        
        //非空判断
        return count ==null?0:Integer.parseInt(count+"");
    }
}

17、时间的分析

        (1)数据库里面是date类型(2009-09-09)那么后端可以用String去返回

        (2)数据库里面是dateTime类型(2009-09-09 10:00:00)那么后端可以用Date或者LocalDateTime去返回

18、${}获取作用域、ajax用$()

19、当实体类跟数据库的对象对应不上的时候,可以在dao层实现转换

//写sql语句
        String sql = "insert into user(uid,uname,uage,ubirth,udesc,did) values(?,?,?,?,?,?)";
        int did = 0;
        //根据dname判断对应的did
        if ("人事部".equals(user.getDname())){
            did=1;
        }else if ("行政部".equals(user.getDname())){
            did=2;
        }

20、这里可以去截取form表单的值,当然也可以改为button之后使用

 var dname="";
    var uname="";

    $("#myForm").submit(function (e){
       //阻止表单的默认提交方式
        e.preventDefault();

        //获取部门名称和员工名称
        dname =  $('#tv_select').val();
        uname =  $('#tv_name').val();

       //提交跳转
        selectCurrentPage(1,dname,uname);

    });

21、这里在一开始的时候,由页面向后端发请求,并发数据过去,后端返回过来的数据会在sussess的函数的data中,然后继续执行逻辑,包括填充页数

 //为了一开始存进去
    selectCurrentPage(1,dname,uname);

    function selectCurrentPage(currentPageNo,dname,uname) {
        //发送ajax请求
        $.ajax({
            url: "UserServlet",
            data: {"currentPageNo": currentPageNo, "mark": "selectUser","dname":dname,"uname":uname},
            type: "post",
            dataType: "text",
            success: callBack,
            error: function () {
                alert("请求错误!!!");
            }

        });
    }

    function callBack(data) {
        // alert(data);
        // $("#tv_table").html("");
        // $("#div_fy").html("");

        //转为前端可以识别的json
        var jsondata = JSON.parse(data);

        //将json转为jquery对象
        var $jsonList = $(jsondata.userList);

        var text = "编号 部门名称 名称 年龄 生日 描述 操作";

        //拼接
        $jsonList.each(function () {
            text += "";
            text += "" + this.uid + "";
            text += "" + this.dname + "";
            text += "" + this.uname + "";
            text += "" + this.uage + "";
            text += "" + this.ubirth + "";
            text += "" + this.udesc + "";
            text += "去修改  " +
                "删除";

            text += "";

        });
        //添加上去
        $("#tv_table").html(text);


//包括填充页数

22、这里在你点击上一页的时候,传值进去继续执行ajax

 if ((jsondata.currentPageNo) > 1) {
            t += "上一页  ";
        }

23、这里的href='javaScript:void(0)'是禁止a标签本身的跳转功能

24、在点击增加的时候,跳转到register界面,preventDefault阻止默认提交,然后调用方法去执行,成功之后就跳转到主页面

$("#sub_form").submit(function (e){
    //阻止表单的默认提交方式
    e.preventDefault();

    //获取uid,dname,uname...
    var uid = $('#uid').val();
    var dname = $('#dname').val();
    var uname = $('#uname').val();
    var uage = $('#uage').val();
    var ubirth = $('#ubirth').val();
    var udesc = $('#udesc').val();

    //调用函数
    insertMsg(1,uid,dname,uname,uage,ubirth,udesc);

});

25、在修改的时候,传入到servlet然后去根据uname查询到记录,返回到更新界面,更新界面去回显值(修修改改)

编号:

text += "去修改  "

回显之后,提交ajax,使用ajax成功之后返回到主页面

26、在用each方法的时候 只能先把他转为jquery对象才能使用,不然用不了

$jsonList.each(function () {,

 function callBack(data) {
        // alert(data);
        // $("#tv_table").html("");
        // $("#div_fy").html("");
        alert(data)
        //转为前端可以识别的json
        var jsondata = JSON.parse(data);
        // alert(jsondata)

        //将json转为jquery对象
        var $jsonList = $(jsondata.userList);

        var text = "编号 部门名称 名称 年龄 生日 描述 操作";

        //拼接
        $jsonList.each(function () {

而你在用json对象的时候可以直接去通过点来获取

 function callBack01(data){
        var jsondata = JSON.parse(data);

        //跳转到主界面
        alert("查找成功!!!");

        //填充数据
        $("#uid").val(jsondata.uid);
        $("#dname").val(jsondata.dname);

27、删除的时候就直接跟servlet交互就行了

"删除";

28、EL表达式读取值

项目知识—SSM之前_第3张图片

这里也可以用get获取

注意:${userPageUtils.userList}获取req.setAttribute("userPageUtils",userPageUtils)那些值的

29、form表单的提交方式

//将data转换为前端可以识别的json var jsondata = JSON.parse(data); //将json转为jquery(方便用jquery的each方法) var $jsonList = $(jsondata.userList);

30、去掉a标签原有的功能        去修改  删除"; text += ""; });

写法二 

var $jsonList = $(jsondata.userList);  
  
var text = "编号 部门名称 名称 年龄 生日 描述 操作";  
  
//拼接  
$jsonList.each(function(index, element) {  
    text += "";  
    text += "" + element.uid + "";  
    text += "" + element.dname + "";  
    text += "" + element.uname + "";  
    text += "" + element.uage + "";  
    text += "" + element.ubirth + "";  
    text += "" + element.udesc + "";  
    text += "去修改  删除";  
    text += "";  
});

34、这边的jsp写了(//试试)

text += "去修改

另一边的jsp可以直接接收

项目知识—SSM之前_第4张图片

35、生成验证码工具类

package com.qf.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * 生成验证码工具类
 */
@SuppressWarnings("all")
public class VerifyCodeUtils {
    // 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();

    /**
     * 使用系统默认字符源生成验证码
     *
     * @param verifySize 验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     *
     * @param verifySize 验证码长度
     * @param sources    验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成随机验证码文件,并返回验证码值
     *
     * @param w
     * @param h
     * @param outputFile
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 输出随机验证码图片流,并返回验证码值
     *
     * @param w
     * @param h
     * @param os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定验证码图像文件
     *
     * @param w
     * @param h
     * @param outputFile
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
        if (outputFile == null) {
            return;
        }
        File dir = outputFile.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch (IOException e) {
            throw e;
        }
    }

    /**
     * 输出指定验证码图片流
     *
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
                Color.ORANGE, Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h - 4);

        // 绘制干扰线
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        float yawpRate = 0.05f;// 噪声率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使图片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h - 4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
                    (w / verifySize) * i + fontSize / 2, h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }
    }


    public static void main(String[] args) throws IOException {
        File dir = new File("E:/verifies");
        int w = 200, h = 80;
        for (int i = 0; i < 50; i++) {
            String verifyCode = generateVerifyCode(4);
            File file = new File(dir, verifyCode + ".jpg");
            outputImage(w, h, file, verifyCode); }
    }

}

38、图片文件上传(多)

(1)方式一

/**
     * 新增
     *
     * @param request
     * @return
     */
    @Override
    public ResultVo addUser(HttpServletRequest request) throws Exception {
        //实例化结果集对象
        ResultVo resultVo = new ResultVo();

        //实例化user对象
        User user = new User();

        //获取服务器文件夹路径
        String realPath = request.getServletContext().getRealPath("WEB-INF/upload");


        //构建文件对象
        File f = new File(realPath);

        //判断是否是第一次创建文件夹/是否存在
        if (!f.exists()) {
            //不存在则创建文件夹
            f.mkdirs();
        }

        //判断是否以文件上传的格式进行提交
        boolean multipartContent = ServletFileUpload.isMultipartContent(request);

        if (multipartContent) {
            //是文件上传格式
            //获取文件工厂对象
            FileItemFactory factory = new DiskFileItemFactory();

            //获取文件上传核心对象
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

            //获取所有的条目
            List fileItemList = servletFileUpload.parseRequest(request);

            //对集合进行判断
            if (fileItemList != null && fileItemList.size() > 0) {
                for (FileItem fileItem : fileItemList) {
                    //判断条目是普通文本还是文件
                    //普通文件
                    if (fileItem.isFormField()) {
                        //判断普通类型
                        //获取name属性值
                        String fieldName = fileItem.getFieldName();
                        if ("name".equals(fieldName)) {
                            user.setName(fileItem.getString("UTF-8"));
                        } else if ("sex".equals(fieldName)) {
                            user.setSex(Integer.parseInt(fileItem.getString("UTF-8")));
                        } else if ("phone_number".equals(fieldName)) {
                            user.setPhone_number(fileItem.getString("UTF-8"));
                        } else if ("area".equals(fieldName)) {
                            user.setArea(fileItem.getString("UTF-8"));
                        } else if ("username".equals(fieldName)) {
                            user.setUsername(fileItem.getString("UTF-8"));
                        } else if ("password".equals(fieldName)) {
                            user.setPassword(fileItem.getString("UTF-8"));
                        }

                    } else {
                        //是文件对象
                        //获取文件名称
                        String fileItemName = fileItem.getName();

                        //判断类型
                        //是图片类型
                        if (fileItemName.endsWith("png") || fileItemName.endsWith("jpeg") || fileItemName.endsWith("jpg")) {

                            //构建唯一的文件对象
                            fileItemName = System.currentTimeMillis() + fileItemName;
                            File f1 = new File(f, fileItemName);

                            //设置图片
                            user.setPhoto(fileItemName);

                            //向服务器写入文件
                            fileItem.write(f1);

                        } else {
                            //不是图片类型
                            resultVo.setData(null);
                            resultVo.setMessage("图片上传格式不正确!");
                            resultVo.setStatus(400);
                            return resultVo;

                        }

                    }
                }

            }

            //将数据插入到数据库
            user.setCreate_time(LocalDateTime.now());
            user.setManager(1);

            //执行查询
            int num = userDao.addUser(user);

            resultVo.setData(num > 0 ? true : false);
            resultVo.setMessage(num > 0 ? "注册成功" : "注册失败");
            resultVo.setStatus(num > 0 ? 200 : 400);

        } else {
            //不是文件上传的格式
            resultVo.setData(null);
            resultVo.setMessage("文件上传格式不对");
            resultVo.setStatus(400);
        }

        return resultVo;
    }

39、模糊查询问题

     if (!StringUtils.isEmpty(realname)) {
            //如果不为空,则添加条件
            sb.append(" and realname like ? ");
            dataList.add("'%"+realname+"%'");
        }

        在Java中,dataList.add("%"+realname+"%"); 这行代码是正确的,因为字符串的拼接在Java中是通过+操作符完成的。这里,%字符被当作普通字符对待,而不是SQL中的通配符。

40、查询的时候是可以多加字段的,他只是select或者说只是映射而已,新增的时候给他限定的构造器就可以了,获取到了之后再查order如何再set回去就可以拼接显示了

package com.qf.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 售后
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Reject implements Serializable {
    private Integer id;
    private Integer uid;
    private Integer oid;
    private String reason;
    private LocalDateTime time;

    //订单信息
    private Order order;

    public Reject(Integer id, Integer uid, Integer oid, String reason, LocalDateTime time) {
        this.id = id;
        this.uid = uid;
        this.oid = oid;
        this.reason = reason;
        this.time = time;
    }
}

41、null passed where not-null expected,string转integer类型的时候,不能直接转

应该

productVo.setState(StringUtils.isEmpty(state)?null:Integer.parseInt(state));

42、获取到的string类型的uid,增加的时候就用这个方法

rejectVo.setUid(StringUtils.isEmpty(uid)?null:Integer.parseInt(uid));

除非是必填的就Integer.parseInt(uid)

43、新增功能字段类型是String的话,参数不用额外+“”

44、如果参数很多的话,可以把参数封装成一个实体类

package com.qf.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class RejectVo implements Serializable {

    private Integer uid;
    private Integer oid;
    private String startTime;
    private String endTime;
    private Integer currentPageNo;
    private Integer pageSize;
}

45、项目流程

(1)写数据库、引入maven依赖、properties

(2)写工具类

        (DBUtils数据库连接、PageUtils分页,JsonUtils返回结果集成json,resultVo结果集封装,BaseServlet封装)

       

项目知识—SSM之前_第5张图片

项目知识—SSM之前_第6张图片

 还有一些参数多的用去封装 

项目知识—SSM之前_第7张图片

(2)写实体类(不一定要对应表)

(3)写dao层 

(4)写service层(一般返回ResultVo结果集对象)

(5)写Servlet去调用

46、调用数据库类DBUTils

package com.qf.utils;


import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.Getter;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

@Getter
public enum DBUtils {

    /**
     * 数据库枚举项
     */
    DB;

    private QueryRunner qr;

    DBUtils(){
        try {
            //实例化properties
            Properties pro = new Properties();

            //通过反射加载配置文件
            InputStream is = DBUtils.class.getResourceAsStream("db.properties");

            //加载到配置文件
            pro.load(is);

            //实例化数据库连接池获取数据源对象
            DataSource ds = DruidDataSourceFactory.createDataSource(pro);

            //实例化queryRunner对象
            qr = new QueryRunner(ds);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

 47、BaseServlet(servlet的基类)

package com.qf.servlet;

import com.alibaba.druid.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * servlet的基类
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //设置编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        //获取前端传递的方法名称
        String methodName = req.getParameter("mark");
        //进行非空判断
        if (StringUtils.isEmpty(methodName)){
            throw new RuntimeException("方法名不存在!");
        }

        try {
            //有方法名称
            //获取class对象
            Class cla = this.getClass();

            //获取方法
            Method method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

            //执行方法
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

    }
}

47、PageUtils分页的基类

package com.qf.utils;

import lombok.*;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageUtils {
    //当前页
    private Integer currentPageNo;
    //页量
    private Integer pageSize;
    //总记录数
    private Integer totalCount;
    //总页数
    private Integer totalPageSize;
    //集合
    private List userList;

}

48、ResultVo结果集工具类的封装

package com.qf.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 结果集工具类封装
 * @param 
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResultVo {
    //状态码
    private Integer status;

    //提示信息
    private String message;

    //数据
    private T data;

}

49、JonUtils结果集转json工具类

package com.qf.utils;

import com.alibaba.fastjson.JSON;

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

/**
 * 返回结果集的工具类
 */
public class JsonUtils {

    public static   void  writeJsonString(HttpServletResponse response,ResultVo resultVo) throws IOException {
        PrintWriter pw = response.getWriter();

        //将数据转为json格式
        String s = JSON.toJSONString(resultVo);
        //写入到前端
        pw.print(s);
        pw.close();
    }
}

50、关于批量获取前端传递的数据,导入beanUtils依赖

  public void updateProduct(HttpServletRequest request ,HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
        //从前端获取参数
        Map parameterMap = request.getParameterMap();
        //实例化商品对象
        Product product = new Product();
        BeanUtils.populate(product,parameterMap);

实体类属性顺序必须对应

51、postman用法

项目知识—SSM之前_第8张图片

你可能感兴趣的:(java)