java之学习记录 5 - 1 - 部分代码记录

此文章只为个人学习的记录

当某些值无需更改并且常用的情况下 创建一个final class类,用到时直接调用

package com.lagou.base;

public final class Constants {
    // 本地的访问地址
    public static final String LOCAL_URL = "http://localhost";
}

当返回接口状态时,定义枚举(enum)类:

package com.lagou.base;

import com.alibaba.fastjson.JSONObject;

public enum StatusCode {
    SUCCESS(0,"success"),FAIL(1,"fail");
    // 定义属性
    private int code;
    private String message;

    StatusCode() {
    }

    StatusCode(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    // 重写toString() 将枚举对象转换为JSON
    @Override
    public String toString() {
        JSONObject object = new JSONObject();
        object.put("status",code);
        object.put("msg",message);
        return object.toString();
    }
}

过滤请求/返回的乱码

package com.lagou.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//Filter 解决乱码
@WebFilter("/*")
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse)servletResponse;

        //解决请求乱码
        request.setCharacterEncoding("UTF-8");

        //解决响应乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }


}

文件上传类

package com.lagou.web.servlet;

import com.lagou.utils.UUIDUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 创建磁盘文件工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 创建文件上传核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 设置上传文件的编码
            upload.setHeaderEncoding("utf-8");
            // 判断表单是否是文件上传
            boolean multipartContent = upload.isMultipartContent(req);
            // 是文件上传表单
            if (multipartContent){
                // 解析request -- 获取表单项集合
                List<FileItem> list = upload.parseRequest(req);
                if (list != null){
                    // 遍历集合 获取表单项
                    for (FileItem fileItem : list) {
                        // 判断当前表单项是不是普通表单项
                        boolean formField = fileItem.isFormField();
                        if (formField){
                            // 普通表单项
                            String fieldName = fileItem.getFieldName();
                            String fieldValue = fileItem.getString("utf-8");// 设置编码
                            System.out.println(fieldName+"="+fieldValue);
                        } else {
                            // 文件上传项
                            // 获取文件名
                            String filename = fileItem.getName();
                            // 拼接新的文件名 使用UUID保证不重复
                            String newFileName = UUIDUtils.getUUID() + "_" + filename;
                            // 获取输入流
                            InputStream in = fileItem.getInputStream();
                            // 创建输出流
                            // 获取项目的运行目录
                            String realPath = this.getServletContext().getRealPath("/");
                            // 截取到webapps的目录路径
                            String webappsPath = realPath.substring(0, realPath.indexOf("lagou_edu_home"));
                            // 拼接输出路径,将图片保存到upload
                            FileOutputStream out = new FileOutputStream(webappsPath+"/upload/"+newFileName);
                            // 使用IOUtils完成文件的copy
                            IOUtils.copy(in,out);
                            // 关闭流
                            out.close();
                            in.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


        // 判断是普通的表单项还是文件上传项
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

当form表单提交带有file文件上传:

@WebServlet("/courseSalesInfo")
public class CourseSalesInfoServlet extends HttpServlet {
    /*
    * 保存课程营销信息
    *   收集表单信息,封装到course对象中,将图片上传到tomcat服务器中
    * */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 创建Course对象
            Course course = new Course();
            // 创建Map集合,用来收集数据
            Map<String,Object> map = new HashMap<>();
            // 创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            // 解析request对象,获取表单项集合
            List<FileItem> list = fileUpload.parseRequest(req);
            // 遍历集合 判断哪些是普通的表单项,哪些是文件表单项
            for (FileItem item : list) {
                boolean formField = item.isFormField();
                if (formField){
                    // 普通表单项,获取表单项中的数据,保存到map
                    String fieldName = item.getFieldName();
                    String value = item.getString("utf-8");
                    System.out.println(fieldName + " "+ value);
                    map.put(fieldName,value);
                } else {
                    // 文件上传项
                    // 获取文件名
                    String fileName = item.getName();
                    String newFileName = UUIDUtils.getUUID() + "_" + fileName;
                    // 获取输入流
                    InputStream in = item.getInputStream();
                    // 获取webapp的目录路径
                    String realPath = this.getServletContext().getRealPath("/");
                    String webappsPath = realPath.substring(0, realPath.indexOf("lagou_edu_home"));
                    // 获取输出流
                    OutputStream out = new FileOutputStream(webappsPath+"/upload/"+newFileName);
                    IOUtils.copy(in,out);
                    out.close();
                    in.close();
                    // 将图片路径进行保存
                    map.put("course_img_url", Constants.LOCAL_URL+"/upload/"+newFileName);
                }
            }
            // 使用BeanUtils 将Map中的数据封装到course对象
            BeanUtils.populate(course,map);
            String dateFormart = DateUtils.getDateFormart();
            if (map.get("id") != null){
                // 修改操作
                // 补全信息
                course.setUpdate_time(dateFormart);
                // 业务处理
                CourseService cs = new CourServiceImpl();
                String result = cs.updateCourseSalesInfo(course);
                // 响应结果
                resp.getWriter().print(result);
            } else {
                // 新建操作
                // 补全信息
                course.setCreate_time(dateFormart);
                course.setUpdate_time(dateFormart);
                course.setStatus(1);
                // 业务处理
                CourseService cs = new CourServiceImpl();
                String result = cs.saveCourseSalesInfo(course);
                // 响应结果
                resp.getWriter().print(result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

当json数据请求时,接收处理(json数据请求以及普通数据请求封装。BaseServlet 封装请求类,执行操作的类继承这个封装类):

package com.lagou.base;

import com.alibaba.fastjson.JSON;

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

public class BaseServlet extends HttpServlet {
    /**
     * doGet方法作为一个调度器 根据请求功能的不同,调用对应的方法
     *  规定必须传递一个参数
     *  methodName=功能名
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数 要访问的方法名
        //String methodName = req.getParameter("methodName");
        String methodName = null;
        // 获取post请求的Content-type类型
        String contentType = req.getHeader("Content-Type");
        // 判断传递的数据是不是JSON格式
        if ("application/json;charset=utf-8".equals(contentType)){
            // 是JSON格式 调用getPostJSON
            String postJSON = getPostJSON(req);
            // 将JSON格式的字符串转化为map
            Map<String,Object> map = JSON.parseObject(postJSON, Map.class);
            // 从map集合中获取 methodName
            methodName = (String)map.get("methodName");
            // 将获取到的数据,保存到request域对象
            req.setAttribute("map",map);
        } else {
            methodName = req.getParameter("methodName");
        }
        // 判断执行对应的方法
        if (methodName != null){
            // 通过反射优化代码 提升代码的可维护性
            try {
                Class aClass = this.getClass();
                // 根据传入的方法名,获取对应的方法对象
                // 获取字节码文件对象s
                Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                // 调用method对象的invoke方法,执行对应的功能
                method.invoke(this,req,resp);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("请求的功能不存在");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /*
    * POST请求格式为:application/json;charset=utf-8
    * 使用该方法进行读取
    * */
    public String getPostJSON(HttpServletRequest request){
        try {
            // 从request中获取缓冲输入流对象
            BufferedReader reader = request.getReader();
            // 创建StringBuffer 保存读取出的数据
            StringBuffer sb = new StringBuffer();
            // 循环读取
            String line = null;
            while ((line = reader.readLine()) != null) {
                // 将每次读取的数据 追加到StringBuffer
                sb.append(line);
            }
            // 返回结果
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

当json数据接收后,操作类处理时:

@WebServlet("/courseContent")
public class CourseContentServlet extends BaseServlet {

    // 保存和修改章节信息
    public void saveOrUpdateSection(HttpServletRequest request,HttpServletResponse response){
        try {
            // 获取参数 从域对象中获取
            Map<String,Object> map = (Map)request.getAttribute("map");
            // 创建Course_Section
            Course_Section section = new Course_Section();
            // 使用BeanUtils工具类,将Map中的数据封装到section
            BeanUtils.populate(section,map);
            // 业务处理
            CourseContentService contentService = new CourseContentServiceImpl();
            // 判断是否携带id
            if (section.getId() == 0){
                // 新增操作
                String result = contentService.saveSection(section);
                // 响应结果
                response.getWriter().print(result);
            } else {
                // 修改操作
                String result = contentService.updateSection(section);
                response.getWriter().print(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

指定查询出的数据要转换的JSON字段

// SimplePropertyPreFilter 指定要转换的JSON字段 Course.class 数据表类
SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Course.class,"id","course_name","price","sort_num","status");
// courseList 查询出来的数据list集合
String s = JSON.toJSONString(courseList,filter);

生成唯一uuid封装类

/**
 * UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。
 *
 * UUID由以下几部分的组合:
 *  1.当前日期和时间,UUID的第一个部分与时间有关,如果你在生成一个UUID之后,过几秒又生成一个UUID,则第一个部分不同,其余相同。
 *  2.时钟序列。
 *  3.全局唯一的IEEE机器识别号,如果有网卡,从网卡MAC地址获得,没有网卡以其他方式获得。
 *
 */
public class UUIDUtils {

    //获取唯一ID的 方法
    public static String getUUID() {

        return UUID.randomUUID().toString().replace("-", "");
    }

}

获取当前时间封装类

package com.lagou.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {

    /**
     * 获取日期对象 格式化后的字符串
     * @return
     */
    public static String getDateFormart(){

        Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String format = sdf.format(date);

        return format;
    }
}

练习的后台项目结构

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值