小刘

小刘 查看完整档案

填写现居城市  |  填写毕业院校  |  填写所在公司/组织填写个人主网站
编辑
_ | |__ _ _ __ _ | '_ \| | | |/ _` | | |_) | |_| | (_| | |_.__/ \__,_|\__, | |___/ 个人简介什么都没有

个人动态

小刘 提出了问题 · 2月24日

解析json数据,创建dom元素,怎么使用setAttribute添加传递参数的函数?

创建一个class为'btn-solve-container'的div,然后添加一个点击事件,传递参数,怎么实现?


 data: {
    class: 'btn-solve-container',
 'onclick': "openSolvePage("+item['company']+")"
 }
for (attrName in data) {
    if (data.hasOwnProperty(attrName)) {
        // 给 elem 添加属性
 elem.setAttribute(attrName, data[attrName])
    }
}
function openSolvePage(data) {
  console.log('openSolvePage data == ', data)
  var jobMask = document.getElementsByClassName('job-mask')[0]
  jobMask.style.display = 'block'
}

关注 2 回答 1

小刘 提出了问题 · 2月22日

MyBatis这种分组查询应该如何写返回的类,我写成整数为什么报错?

<select id="getCount" resultType="java.lang.Integer">
 SELECT classify,sum(status) total,sum(case status when 1 then status else null end) success,sum(case status when 0 then status else null end) fail
    FROM abbott_message_board
    WHERE classify is not null
    GROUP BY classify
</select>

关注 2 回答 1

小刘 提出了问题 · 2月2日

使用java动态创建html页面,为什么无法读取这个文件?

image

package com.abbott.common.utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class HtmlUtil {
    public static void exportHtml() {
        //用于存储html字符串
 StringBuilder stringHtml = new StringBuilder();
 try {
            //打开文件
 PrintStream printStream = new PrintStream(new FileOutputStream("./Data/test.html"));
 //输入HTML文件内容
 stringHtml.append("<html><head>");
 stringHtml.append("<meta http-equiv="Content-Type" content="text/html; charset=GBK">");
 stringHtml.append("<title>测试报告文档</title>");
 stringHtml.append("</head>");
 stringHtml.append("<body>");
 stringHtml.append("<div>hello</div>");
 stringHtml.append("</body></html>");
 try{
                //将HTML文件内容写入文件中
 printStream.println(stringHtml.toString());
 }catch (Exception e) {
                e.printStackTrace();
 }
        } catch(FileNotFoundException e){
            e.printStackTrace();
 }
    }
    public static void main(String[] args) {
        HtmlUtil.exportHtml();
 }
}

关注 3 回答 2

小刘 提出了问题 · 2月2日

用js动态生成的div怎么才能让爬虫被爬到?

没有用框架,在html页面局部动态渲染数据

以下的这段代码中,我会在类名为zp-main-center的div中,动态生成resume-tabs-wrapper的div,这些动态生成的div无法被爬虫到,请问怎么才能被爬虫爬到?

<div class="zp-main-center clearfix content-container" data-v-05cb87d6="">

    <div class="resume-tabs-wrapper clearfix zp-tabs tabs-container">
      <span class="resume-tabs-item fl resume-tabs-item-active" title="技术负责人 12年 天津"> 技术负责人1 12年 北京 </span>
    </div>

    <div class="resume-tabs-wrapper clearfix zp-tabs tabs-container">
      <span class="resume-tabs-item fl resume-tabs-item-active" title="技术负责人 12年 天津"> 技术负责人2 12年 北京 </span>
    </div>

    <div class="resume-tabs-wrapper clearfix zp-tabs tabs-container">
      <span class="resume-tabs-item fl resume-tabs-item-active" title="技术负责人 12年 天津"> 技术负责人3 12年 北京 </span>
    </div>


    <div class="resume-tabs-wrapper clearfix zp-tabs tabs-container">
      <span class="resume-tabs-item fl resume-tabs-item-active" title="技术负责人 12年 天津"> 技术负责人4 12年 北京 </span>
    </div>

    <div class="resume-tabs-wrapper clearfix zp-tabs tabs-container">
      <span class="resume-tabs-item fl resume-tabs-item-active" title="技术负责人 12年 天津"> 技术负责人5 12年 北京 </span>
    </div>

</div>

关注 2 回答 1

小刘 提出了问题 · 2月2日

为什么无法打开这个文件?java.io.FileNotFoundException

image

package com.abbott.common.utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class HtmlUtil {
    public static void exportHtml() {
        //用于存储html字符串
 StringBuilder stringHtml = new StringBuilder();
 try {
            //打开文件
 PrintStream printStream = new PrintStream(new FileOutputStream("./Data/test.html"));
 //输入HTML文件内容
 stringHtml.append("<html><head>");
 stringHtml.append("<meta http-equiv="Content-Type" content="text/html; charset=GBK">");
 stringHtml.append("<title>测试报告文档</title>");
 stringHtml.append("</head>");
 stringHtml.append("<body>");
 stringHtml.append("<div>hello</div>");
 stringHtml.append("</body></html>");
 try{
                //将HTML文件内容写入文件中
 printStream.println(stringHtml.toString());
 }catch (Exception e) {
                e.printStackTrace();
 }
        } catch(FileNotFoundException e){
            e.printStackTrace();
 }
    }
    public static void main(String[] args) {
        HtmlUtil.exportHtml();
 }
}

关注 4 回答 4

小刘 提出了问题 · 2月1日

我想知道为什么这个管理系统登录页面加载速度怎么优化?现在太慢了

体验地址

代码地址

登录页面代码

<template>
  <!--<div class="login" :style="'background-image:url('+ Background +');'">-->
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px" class="login-form">
      <h3 class="title">
        ABBOTT 后台管理系统
      </h3>
      <el-form-item prop="username">
        <el-input v-model.trim="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model.trim="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="isShowCode">
        <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          ![](codeUrl)
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;color: #ffffff">
        记住我
      </el-checkbox>
      <el-form-item style="width:100%;" v-if="loginMode === 'tourist'">
        <div class='btn-login-container'>
          <div class="btn-retry-container">
            <div class="btn-retry" @click="handleLogin">重新登录</div>
          </div>
          <div class="btn-tourist-container">
            <div class="btn-tourist" @click="handleTourist">游客模式</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item style="width:100%;" v-if="loginMode === 'normal'">
        <el-button :loading="loading" type="primary" size="medium" style="width:100%;" @click.native.prevent="handleLogin">
          <span v-if="!loading">{{userText}}</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>

      <div class="user-info-container">
        <div class='username-container'>账号【{{usernameDefault}}】</div>
        <div class='password-container'>密码【{{passwordDefault}}】</div>
      </div>
    </el-form>
    <!--  底部  -->
    <!--<div v-if="$store.state.settings.showFooter" id="el-login-footer">-->
      <!--<span v-html="$store.state.settings.footerTxt" />-->
      <!--<span> ⋅ </span>-->
      <!--<a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank">{{ $store.state.settings.caseNumber }}</a>-->
    <!--</div>-->
  </div>
</template>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
import Background from '@/assets/images/background.png'
import Helper from '@/utils/helper'
import {getLogin} from '@/api/login'

export default {
  name: "Login",
  data() {
    return {
      Background: Background,
      codeUrl: '',
      cookiePass: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: ''
      },
      usernameDefault: 'admin321',
      passwordDefault: '123456',
      userText: '登 录',
      loginRules: {
        username: [
            {
              required: true,
              trigger: 'blur',
              message: '用户名不能为空'
            }
        ],
        password: [
            { required: true, trigger: 'blur', message: '密码不能为空' }
        ],
        code: [
            { required: true, trigger: 'change', message: '验证码不能为空' }
        ]
      },
      loading: false,
      redirect: undefined,
      isShowCode: false,
      loginMode: 'normal'
    }
  },
  watch: {
    user: val => {
      console.log('watch form val ======= ', val);
    }
  },
  computed: {
    ...mapState({
      user: state=>state.user,
      app: state=>state.app
    })
  },
  mounted () {
    const _this = this
    let imgBackground = new Image()
    imgBackground.src = Background;
    imgBackground.onreadystatechange = function() {
      console.log('onreadystatechange imgBackground.readyState == ', imgBackground.readyState)
      if(imgBackground.readyState==="complete"||imgBackground.readyState==="loaded"){
        console.log('背景图加载完')
        // p1.innerHTML = 'readystatechange:loaded'
      }
    }
  },
  methods: {
    ...mapActions('user', [
      'actionsChangeUserInfo'
    ]),
    ...mapActions('app', [
      'actionsChangeAppDataGlobal',
      'actionsChangeUserDataGlobal'
    ]),
    ...mapGetters('user', [
      'getterCount'
    ]),
    handleLogin () {
      let _this = this

      _this.$refs.loginForm.validate(valid => {
        // console.log( 'valid == ', valid);
        const user = {
          username: Helper.trimStr(_this.loginForm.username),
          password: Helper.trimStr(_this.loginForm.password),
          rememberMe: _this.loginForm.rememberMe,
          code: _this.loginForm.code,
          uuid: _this.loginForm.uuid
        }

        // let url = 'http://39.105.168.44:9091/abo/login'

        if(valid) {

          if( user['username'] === 'admin778899') {
            if ( user['password'] === '123') {
              _this.$router.push('/admin')
            } else {
              _this.$message({
                message: '本地密码错误',
                type:'error',
                duration: '3000'
              })
            }
          } else {
            let url = '/reqJava/user/v1/login'
            let dataReq = {
              "username": user['username'],
              "password": user['password']
            }

            // console.log('login dataReq ==', dataReq)
            // getLogin(dataReq).then(res=>{
            //   _this.handleResData(res)
            // }, err=>{
            //   _this.$message({
            //     message: err,
            //     type:'error',
            //     duration: '5000'
            //   })
            // })

            /**
             * 200 - 请求成功
             * 301 - 资源(网页等)被永久转移到其它URL
             * 404 - 请求的资源(网页等)不存在
             * 500 - 内部服务器错误(如:网络无法连接)
             */
            getLogin(dataReq).then( res=>{
              // console.log('getLogin res == ', res)
              _this.handleResData(res)
            }).catch( err =>{
              console.log('getLogin err == ', err)
              _this.$message({
                message: err.status + ' - ' + err.statusText,
                type:'error',
                duration: '3000'
              })
              _this.loginMode = 'tourist'
            })

          }

        } else {
          _this.$message({
            message: '输入格式错误',
            type:'error',
            duration: '3000'
          })
        }

      })
    },
    handleTourist () {
      let _this = this
      console.log('使用游客模式')
      let userInfoState = {
        authorization: 1,
        device: null,
        id: 10009,
        password: null,
        username: "tourist"
      };
      _this['actionsChangeUserInfo'](userInfoState)
      _this.$router.push('/admin')
    },
    handleResData (dataRes) {
      let _this = this
      console.log(dataRes)
      if( dataRes.data.code === '0001' ) {
        let userInfoState = {};
        // userInfoState = dataRes.data.data.data
        userInfoState = dataRes.data.data
        // console.log('userInfoState == ', userInfoState)
        _this['actionsChangeUserInfo'](userInfoState.data)
        _this['actionsChangeAppDataGlobal'](userInfoState.data)
        _this['actionsChangeUserDataGlobal'](userInfoState)
        _this.$router.push('/admin')
      } else {
        _this.$message({
          message: dataRes.data.detail,
          type:'error',
          duration: '3000'
        })
        _this.loginMode = 'tourist'
        // _this.userText = '游 客 模 式 登 录'
        // _this.usernameDefault = 'admin'
        // _this.passwordDefault = '123'
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-size: cover;
    background: linear-gradient(to right,#9D0006, #9D1751, #3D266D);
  }
  .title {
    margin: 0 auto 30px auto;
    text-align: center;
    /*color: #707070;*/
    color: #ffffff;
  }

  .login-form {
    border-radius: 6px;
    /*background: #ffffff;*/
    width: 385px;
    padding: 25px 25px 25px 25px;
    .el-input {
      height: 38px;
      input {
        height: 38px;
      }
    }
    .input-icon{
      height: 39px;width: 14px;margin-left: 2px;
    }
    background: #B882C9;
  }
  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }
  .login-code {
    width: 33%;
    display: inline-block;
    height: 38px;
    float: right;
    img{
      cursor: pointer;
      vertical-align:middle
    }
  }
  .user-info-container {
    display: flex;
    font-size: 16px;
    color: #ffffff;
    .username-container {
      width: 50%;
      /*background: #409EFF;*/
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .password-container {
      width: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .btn-login-container {
    display: flex;
    .btn-retry-container {
      width: 50%;
      box-sizing: border-box;
      padding-right: 10px;
      .btn-retry {
        width: 100%;
        background: #409EFF;
        white-space: nowrap;
        cursor: pointer;
        font-weight: 500;
        color: #FFF;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .btn-tourist-container {
      width: 50%;
      box-sizing: border-box;
      padding-left: 10px;
      /*background: #409EFF;*/
      height: 100%;
      .btn-tourist {
        width: 100%;
        background: #409EFF;
        white-space: nowrap;
        cursor: pointer;
        font-weight: 500;
        color: #FFF;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

</style>
<template>
 <!--<div class="login" :style="'background-image:url('+ Background +');'">-->
 <div class="login">
 <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px" class="login-form">
 <h3 class="title">
 ABBOTT 后台管理系统
      </h3>
 <el-form-item prop="username">
 <el-input v-model.trim="loginForm.username" type="text" auto-complete="off" placeholder="账号">
 <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
 </el-input> </el-form-item> <el-form-item prop="password">
 <el-input v-model.trim="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
 <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
 </el-input> </el-form-item> <el-form-item prop="code" v-if="isShowCode">
 <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
 <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
 </el-input> <div class="login-code">
 <img :data-original="codeUrl" @click="getCode">
 </div> </el-form-item> <el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;color: #ffffff">
 记住我
      </el-checkbox>
 <el-form-item style="width:100%;" v-if="loginMode === 'tourist'">
 <div class='btn-login-container'>
 <div class="btn-retry-container">
 <div class="btn-retry" @click="handleLogin">重新登录</div>
 </div> <div class="btn-tourist-container">
 <div class="btn-tourist" @click="handleTourist">游客模式</div>
 </div> </div> </el-form-item> <el-form-item style="width:100%;" v-if="loginMode === 'normal'">
 <el-button :loading="loading" type="primary" size="medium" style="width:100%;" @click.native.prevent="handleLogin">
 <span v-if="!loading">{{userText}}</span>
 <span v-else>登 录 中...</span>
 </el-button> </el-form-item>
 <div class="user-info-container">
 <div class='username-container'>账号【{{usernameDefault}}】</div>
 <div class='password-container'>密码【{{passwordDefault}}】</div>
 </div> </el-form> <!--  底部  -->
 <!--<div v-if="$store.state.settings.showFooter" id="el-login-footer">--> <!--<span v-html="$store.state.settings.footerTxt" />--> <!--<span> ⋅ </span>--> <!--<a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank">{{ $store.state.settings.caseNumber }}</a>--> <!--</div>--> </div>
</template>
<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
import Background from '@/assets/images/background.png'
import Helper from '@/utils/helper'
import {getLogin} from '@/api/login'
export default {
  name: "Login",
 data() {
    return {
      Background: Background,
 codeUrl: '',
 cookiePass: '',
 loginForm: {
        username: '',
 password: '',
 rememberMe: false,
 code: '',
 uuid: ''
 },
 usernameDefault: 'admin321',
 passwordDefault: '123456',
 userText: '登 录',
 loginRules: {
        username: [
            {
              required: true,
 trigger: 'blur',
 message: '用户名不能为空'
 }
        ],
 password: [
            { required: true, trigger: 'blur', message: '密码不能为空' }
        ],
 code: [
            { required: true, trigger: 'change', message: '验证码不能为空' }
        ]
      },
 loading: false,
 redirect: undefined,
 isShowCode: false,
 loginMode: 'normal'
 }
  },
 watch: {
    user: val => {
      console.log('watch form val ======= ', val);
 }
  },
 computed: {
    ...mapState({
      user: state=>state.user,
 app: state=>state.app
 })
  },
 mounted () {
    const _this = this
 let imgBackground = new Image()
    imgBackground.src = Background;
 imgBackground.onreadystatechange = function() {
      console.log('onreadystatechange imgBackground.readyState == ', imgBackground.readyState)
      if(imgBackground.readyState==="complete"||imgBackground.readyState==="loaded"){
        console.log('背景图加载完')
        // p1.innerHTML = 'readystatechange:loaded'
 }
    }
  },
 methods: {
    ...mapActions('user', [
      'actionsChangeUserInfo'
 ]),
 ...mapActions('app', [
      'actionsChangeAppDataGlobal',
 'actionsChangeUserDataGlobal'
 ]),
 ...mapGetters('user', [
      'getterCount'
 ]),
 handleLogin () {
      let _this = this
 _this.$refs.loginForm.validate(valid => {
        // console.log( 'valid == ', valid);
 const user = {
          username: Helper.trimStr(_this.loginForm.username),
 password: Helper.trimStr(_this.loginForm.password),
 rememberMe: _this.loginForm.rememberMe,
 code: _this.loginForm.code,
 uuid: _this.loginForm.uuid
 }
        // let url = 'http://39.105.168.44:9091/abo/login'
 if(valid) {
          if( user['username'] === 'admin778899') {
            if ( user['password'] === '123') {
              _this.$router.push('/admin')
            } else {
              _this.$message({
                message: '本地密码错误',
 type:'error',
 duration: '3000'
 })
            }
          } else {
            let url = '/reqJava/user/v1/login'
 let dataReq = {
              "username": user['username'],
 "password": user['password']
            }
            // console.log('login dataReq ==', dataReq)
 // getLogin(dataReq).then(res=>{ //   _this.handleResData(res) // }, err=>{ //   _this.$message({ //     message: err, //     type:'error', //     duration: '5000' //   }) // })
 /**
 * 200 - 请求成功 * 301 - 资源(网页等)被永久转移到其它URL * 404 - 请求的资源(网页等)不存在 * 500 - 内部服务器错误(如:网络无法连接) */ getLogin(dataReq).then( res=>{
              // console.log('getLogin res == ', res)
 _this.handleResData(res)
            }).catch( err =>{
              console.log('getLogin err == ', err)
              _this.$message({
                message: err.status + ' - ' + err.statusText,
 type:'error',
 duration: '3000'
 })
              _this.loginMode = 'tourist'
 })
          }
        } else {
          _this.$message({
            message: '输入格式错误',
 type:'error',
 duration: '3000'
 })
        }
      })
    },
 handleTourist () {
      let _this = this
 console.log('使用游客模式')
      let userInfoState = {
        authorization: 1,
 device: null,
 id: 10009,
 password: null,
 username: "tourist"
 };
 _this['actionsChangeUserInfo'](userInfoState)
      _this.$router.push('/admin')
    },
 handleResData (dataRes) {
      let _this = this
 console.log(dataRes)
      if( dataRes.data.code === '0001' ) {
        let userInfoState = {};
 // userInfoState = dataRes.data.data.data
 userInfoState = dataRes.data.data
 // console.log('userInfoState == ', userInfoState)
 _this['actionsChangeUserInfo'](userInfoState.data)
        _this['actionsChangeAppDataGlobal'](userInfoState.data)
        _this['actionsChangeUserDataGlobal'](userInfoState)
        _this.$router.push('/admin')
      } else {
        _this.$message({
          message: dataRes.data.detail,
 type:'error',
 duration: '3000'
 })
        _this.loginMode = 'tourist'
 // _this.userText = '游 客 模 式 登 录'
 // _this.usernameDefault = 'admin' // _this.passwordDefault = '123' }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
 .login {
    display: flex;
 justify-content: center;
 align-items: center;
 height: 100%;
 background-size: cover;
 background: linear-gradient(to right,#9D0006, #9D1751, #3D266D);
 }
  .title {
    margin: 0 auto 30px auto;
 text-align: center;
 /*color: #707070;*/
 color: #ffffff;
 }
  .login-form {
    border-radius: 6px;
 /*background: #ffffff;*/
 width: 385px;
 padding: 25px 25px 25px 25px;
 .el-input {
      height: 38px;
 input {
        height: 38px;
 }
    }
    .input-icon{
      height: 39px;width: 14px;margin-left: 2px;
 }
    background: #B882C9;
 }
  .login-tip {
    font-size: 13px;
 text-align: center;
 color: #bfbfbf;
 }
  .login-code {
    width: 33%;
 display: inline-block;
 height: 38px;
 float: right;
 img{
      cursor: pointer;
 vertical-align:middle
 }
  }
  .user-info-container {
    display: flex;
 font-size: 16px;
 color: #ffffff;
 .username-container {
      width: 50%;
 /*background: #409EFF;*/
 display: flex;
 align-items: center;
 justify-content: center;
 }
    .password-container {
      width: 50%;
 display: flex;
 align-items: center;
 justify-content: center;
 }
  }
  .btn-login-container {
    display: flex;
 .btn-retry-container {
      width: 50%;
 box-sizing: border-box;
 padding-right: 10px;
 .btn-retry {
        width: 100%;
 background: #409EFF;
 white-space: nowrap;
 cursor: pointer;
 font-weight: 500;
 color: #FFF;
 border-radius: 4px;
 display: flex;
 align-items: center;
 justify-content: center;
 }
    }
    .btn-tourist-container {
      width: 50%;
 box-sizing: border-box;
 padding-left: 10px;
 /*background: #409EFF;*/
 height: 100%;
 .btn-tourist {
        width: 100%;
 background: #409EFF;
 white-space: nowrap;
 cursor: pointer;
 font-weight: 500;
 color: #FFF;
 border-radius: 4px;
 display: flex;
 align-items: center;
 justify-content: center;
 }
    }
  }
</style>

关注 3 回答 3

小刘 赞了回答 · 1月27日

解决为什么从数据库获取Timestamp类型数据类型和打印出来的不一样,如何进行转换

首先,通过打印(System.out.println)输出到屏幕上的内容实际上调用了 TimestamptoString() 方法。通过查看其源码,我们可以发现已经被重写过了(所以打印出来是不一样的):

@SuppressWarnings("deprecation")
public String toString() {
    int year = super.getYear() + 1900;
    int month = super.getMonth() + 1;
    ...
    char[] buf = new char[25 + yearSize - trailingZeros];
    Date.formatDecimalInt(year, buf, 0, yearSize);
    buf[yearSize] = '-';
    Date.formatDecimalInt(month, buf, yearSize + 1, 2);
    ...
}

其次楼主确实是想把 2021-01-26T22:52:00.000+0000 给转成 2021-01-27 10:52:00 的话,可以采用如下写法:

Timestamp ts = new Timestamp(new Date().getTime()); //2021-01-27 15:05:07.724 
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter.format(ts)); //2021-01-27 15:05:07

但是如果出现跨时区使用的话,还需要注意下时区问题。

关注 1 回答 2

小刘 赞了回答 · 1月27日

解决为什么从数据库获取Timestamp类型数据类型和打印出来的不一样,如何进行转换

js获取日期及日期相关js方法 积累总结

image

java中应该也有类似js这种时间转换格式的方法吧。

关注 1 回答 2

小刘 提出了问题 · 1月27日

解决为什么从数据库获取Timestamp类型数据类型和打印出来的不一样,如何进行转换

我想将"2021-01-26T22:52:00.000+0000"转换成正确的时间""2021-01-27 10:52:00"

image

这是从数据库获取的接口数据

{
    "code": "200",
    "status": "success",
    "message": "tenantMessage",
    "result": null,
    "detail": "添加tenantMessage",
    "data": {
        "technology": [
            {
                "id": 115,
                "title": "HTTPS原理(三次握手)",
                "userID": 500,
                "content": "客户端向服务器发送HTTPS请求,服务器将公钥以证书的形式发送到客户端(服务器端存放私钥和公钥)",
                "createDate": "2021-01-26T22:52:00.000+0000",
                "updateDate": "2021-01-26T22:52:00.000+0000",
                "tags": null,
                "qrCodePath": "upload/article/115/1611651120474/qr_161165112048364.png",
                "url": "http://www.xinlizhiyouni.com/myself/article/detail_phone.html?id=115"
            }
       ]
   }
}
package cn.spring.inter.controller;

import cn.spring.inter.bean.ResponseData;
import cn.spring.inter.entity.TechnologyArticle;
import cn.spring.inter.service.TechnologyArticleService;
import cn.spring.inter.utils.ExchangeConstants;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


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

@RestController
public class TechnologyArticleController {
    @Autowired
    private TechnologyArticleService technologyArticleService;

    @RequestMapping(value = "/v1/technologyArticle", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseData getAll(
            @RequestParam(value = "start", required = false, defaultValue = "0") Integer start,
            @RequestParam(value = "dataLength", required = false, defaultValue = "100") Integer dataLength,
            @RequestParam(value = "sort", required = false, defaultValue = "desc") String sort
    ) {
//        System.out.println("start="+start+"/dataLength="+dataLength);
        ResponseData responseData = new ResponseData();
        JSONObject jsonResultObject = new JSONObject();
        responseData.setCode("200");
        responseData.setStatus("success");
        responseData.setMessage("tenantMessage");
        responseData.setDetail("添加tenantMessage");
        List<TechnologyArticle> technologyArticleList = technologyArticleService.selectAll(start, dataLength, sort);

//        String oldDateStr = "2021-01-26T22:52:00.000+0000";
//        String dateStrNew = ExchangeConstants.dealDateFormat(oldDateStr);
//        System.out.println("dateStrNew == " + dateStrNew);

        List<JSONObject> objTechnologyArticleList = new ArrayList<>();

        for(TechnologyArticle technologyArticle: technologyArticleList){
            JSONObject objTechnologyArticle = new JSONObject();
            System.out.println(technologyArticle.getCreateDate());
//            System.out.println(ExchangeConstants.dealDateFormat());
//            objTechnologyArticle.put("createDate", );
//            objTechnologyArticleList.add(objTechnologyArticle);
        }

        jsonResultObject.put("technology", objTechnologyArticleList);

        responseData.setData(jsonResultObject);
        return responseData;
    }
}



package cn.spring.inter.entity;

import cn.spring.inter.utils.ExchangeConstants;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Entity
@Table(name = "technology_article")
public class TechnologyArticle {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "userID")
    private int userID;

    @Column(name = "content")
    private String content;

    @Column(name = "create_date")
    private Timestamp createDate;

    @Column(name = "update_date")
    private Timestamp updateDate;

    @Column(name = "tags")
    private String tags;

    @Column(name = " qr_code_path")
    private String qrCodePath;

    @Column(name = "url")
    private String url;

    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getUserID() {
        return userID;
    }

    public void setUserID(int userID) {
        this.userID = userID;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Timestamp getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Timestamp createDate) {
        this.createDate = createDate;
    }

    public Timestamp getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Timestamp updateDate) {
        this.updateDate = updateDate;
    }

    public String getTags() {
        return tags;
    }

    public void setTags(String tags) {
        this.tags = tags;
    }

    public String getQrCodePath() {
        return qrCodePath;
    }

    public void setQrCodePath(String qrCodePath) {
        this.qrCodePath = qrCodePath;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

解决方案

for(TechnologyArticle technologyArticle: technologyArticleList){
            JSONObject objTechnologyArticle = new JSONObject();
//            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(technologyArticle.getCreateDate()));
//            System.out.println(ExchangeConstants.dealDateFormat());
            objTechnologyArticle.put("id", technologyArticle.getId());
            objTechnologyArticle.put("title", technologyArticle.getTitle());
            objTechnologyArticle.put("content", technologyArticle.getContent());
            objTechnologyArticle.put("qrCodePath", technologyArticle.getQrCodePath());
            objTechnologyArticle.put("url", technologyArticle.getUrl());
            objTechnologyArticle.put("tags", technologyArticle.getTags());
            objTechnologyArticle.put("createDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(technologyArticle.getCreateDate()));
            objTechnologyArticle.put("updateDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(technologyArticle.getUpdateDate()));
            objTechnologyArticleList.add(objTechnologyArticle);
        }

关注 1 回答 2

小刘 赞了回答 · 1月26日

解决使用el-table报错Duplicate keys detected: '[object Object]'

element-ui官网文档显示
row-key支持多层访问,直接写id.value就可以。

关注 2 回答 2

认证与成就

  • 获得 27 次点赞
  • 获得 189 枚徽章 获得 3 枚金徽章, 获得 40 枚银徽章, 获得 146 枚铜徽章

擅长技能
编辑

(゚∀゚ )
暂时没有

开源项目 & 著作
编辑

(゚∀゚ )
暂时没有

注册于 2017-09-28
个人主页被 2k 人浏览