学习杂物(二)java学习笔记

来源:互联网 发布:清华大学法学院 知乎 编辑:程序博客网 时间:2024/04/29 04:03

1、Sql concat用法(字符串链接函数)

concat(字段1,字段2,字段3...)把字段1,字段2,字段3...的结果连起来例如表:  name        Nana        password    123456concat(name,password)结果为:'Nana123456'

2、一个棘手的bug,错误没有走接口,直接在前台报错,以下为错误信息:

Failed to load resource: the server responded with a status of 400 ()

原因:接收数据的两个不同实体存在相同的字段,但该字段一个为int型,另一个为Integer类型而造成的数据类型不对错误的请求引起的页面控制台报错

*PS:接口的实体类最好不要为基本类型

3、关于跨域访问的web.xml的配置:

<!--跨域访问--><filter>    <filter-name>CORS</filter-name>      <filter-class>        com.thetransactioncompany.cors.CORSFilter    </filter-class>      <init-param>          <param-name>cors.allowOrigin</param-name>          <param-value>*</param-value>      </init-param>      <init-param>          <param-name>cors.supportedMethods</param-name>          <param-value>            GET, POST, HEAD, PUT, DELETE        </param-value>      </init-param>      <init-param>          <param-name>cors.supportedHeaders</param-name>          <param-value>            Accept, Origin, X-Requested-With, Content-Type, Last-Modified        </param-value>      </init-param>      <init-param>          <param-name>cors.exposedHeaders</param-name>          <param-value>Set-Cookie</param-value>      </init-param>      <init-param>          <param-name>cors.supportsCredentials</param-name>          <param-value>true</param-value>      </init-param>  </filter>  <filter-mapping>      <filter-name>CORS</filter-name>      <url-pattern>/*</url-pattern>  </filter-mapping><!-- 跨域访问 -->

4、关于上传下载改名删除服务器指定路径内文件的方法

package esci.web.utils;import org.apache.log4j.Logger;import org.jeecgframework.core.common.controller.BaseController;import org.jeecgframework.web.demo.entity.test.FileMeta;import org.springframework.util.FileCopyUtils;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.text.SimpleDateFormat;import java.util.Date;import java.util.LinkedList;import java.util.List;/** * 文件上传下载 * * @author XL */public class FileOperateUtil extends BaseController {    private static final Logger logger = Logger.getLogger(FileOperateUtil.class);    /**     * update-begin--Author:huangzq  Date:20151125 for:[732]【常用示例】上传文件下载报错     */    private static LinkedList<FileMeta> files = new LinkedList<FileMeta>();    /**     * update-end--Author:huangzq  Date:20151125 for:[732]【常用示例】上传文件下载报错     */    private static FileMeta fileMeta = null;    /**     * 文件上传     *     * @param     * @return     */    public static LinkedList<FileMeta> upload(List<MultipartFile> mpfList) {        files = new LinkedList<FileMeta>();        logger.info("upload-》1. build an iterator");        //Iterator<String> itr = request.getFileNames();        //      MultipartFile mpf = null;        if (mpfList == null || mpfList.size() == 0) {            return new LinkedList<FileMeta>();        }        logger.info("upload-》2. get each file");        for (MultipartFile mpf : mpfList) {            //while (itr.hasNext()) {            logger.info("upload-》2.1 get next MultipartFile");            //mpf = request.getFile(itr.next());            logger.info(mpf.getOriginalFilename() + " uploaded! " + files.size());            //System.out.println(mpf.getOriginalFilename() + " uploaded! " + files.size());            logger.info("2.2 if files > 10 remove the first from the list");            if (files.size() >= 10)                files.pop();            logger.info("2.3 create new fileMeta");            //获取文件原名            String fileName = mpf.getOriginalFilename();            String realName = rename(fileName);            fileMeta = new FileMeta();            fileMeta.setFileName(fileName);            fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");            fileMeta.setFileType(mpf.getContentType());            fileMeta.setRealName(realName);            try {                fileMeta.setBytes(mpf.getBytes());                String path = "/upload/";                //String realPath = request.getSession().getServletContext().getRealPath("/") +  path ;// 文件的硬盘真实路径                String realPath = "../webapps" + path;                // 检查文件路径是否存在                File file = new File(realPath);                if (!file.exists()) {                    file.mkdirs();                }                fileMeta.setUploadPath(path + realName);                logger.info("upload-》文件的硬盘真实路径" + realPath);                String savePath = realPath + realName;// 文件保存全路径                logger.info("upload-》文件保存全路径" + savePath);                FileCopyUtils.copy(mpf.getBytes(), new File(savePath));                logger.info("copy file to local disk (make sure the path e.g. D:/temp/files exists)");            } catch (IOException e) {                e.printStackTrace();            }            logger.info("2.4 add to files");            files.add(fileMeta);            logger.info("success uploaded=" + files.size());        }        // result will be like this        // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]        return files;    }    /**     * 文件下载     *     * @param     * @param response     * @param filePath     * @param fileName     */    public static void download(HttpServletResponse response, String filePath, String fileName) {        response.setContentType("UTF-8");        response.setCharacterEncoding("UTF-8");        BufferedInputStream br = null;        OutputStream out = null;        try {            //String realPath = request.getSession().getServletContext().getRealPath("/");            String realPath = "../webapps";            File f = new File(realPath + filePath);            if (!f.exists()) {                response.sendError(404, "File not found!");            }            br = new BufferedInputStream(new FileInputStream(f));            byte[] buf = new byte[1024];            int len = 0;            response.reset();            response.setContentType("application/x-msdownload");            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));            out = response.getOutputStream();            while ((len = br.read(buf)) > 0)                out.write(buf, 0, len);        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (br != null) {                    br.close();                }                if (out != null) {                    out.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }    /**     * 将上传的文件进行重命名     *     * @param name     * @return     */    private static String rename(String name) {        Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")                .format(new Date()));        Long random = (long) (Math.random() * now);        String fileName = now + "" + random;        if (name.indexOf(".") != -1) {            fileName += name.substring(name.lastIndexOf("."));        }        return fileName;    }    /**     * 删除服务器上的指定文件     *     * @param     */    public static void delete(String filePath) {        try {            // 文件路径            //String path = "../webapps/" + filePath;            String path = "http://115.28.153.3:8082" + filePath;            File f = new File(path);            if (f.exists()) {                f.delete();            }        } catch (Exception e) {            e.printStackTrace();        }    }}

5、关于时间的运算和转换

//实体取出时间Date time = entity.getTime();//time和当前时间的差值long timeDifference = new Date().getTime() - time.getTime();
0 0
原创粉丝点击