项目三习得(IDEA、SpringBoot)

除了文件上传,都是用Ajax做的。感觉很好

功能:
头像上传与显示
滚动分页
单击某人详细资料(id的传值)
转年龄格式

头像上传与显示

Controller
  • 形参的名字不要变
  • 最关键是uploadFile.transferTo(),使文件上传简便了许多
  • 上传文件后存入数据库,我加了一个/img/,因为我是存在服务器中的img路径下的,记得在项目中一定要先创建一个img,
    其实不我怎么懂服务器和我IDEA中项目到底怎样的关系。我抱着试一试的态度,发现创建了一个img后,上传的内容也可以从这儿取到,
    所以才在数据库中存入地址中加了img,到时候在前端中可以直接
    <img src="/img/..." />
image.png
//文件上传
    @RequestMapping("/up")
    public String up(MultipartFile uploadFile, HttpSession session) throws IOException {
        //获取上传文件名称
        String fileName = uploadFile.getOriginalFilename();
        //uuid+后缀名,给文件重新取名
        String finalFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        //最后存储的路径,是本地的服务器中
        String path = session.getServletContext().getRealPath("img")+ File.separator + finalFileName;
        System.out.println(path);
        //上传
        File file = new File(path);
        uploadFile.transferTo(file);

        //上传成功后,将地址存入数据库,让前端可以直接拿图片
        String idPic = "/img/" + finalFileName;
        User user = new User();
        user.setIdPic(idPic);
        //获取id值
        user.setUserId(2);
        userService.updateUser(user);

        return "success";
    }
页面
image.png
<form  action="/up" enctype="multipart/form-data" method="post" style="display: none;" id="show_up">
    <input type="file" name="uploadFile"/>
    <input type="submit"/>
</form>
页面进阶版
image.png

image.png
Ajax
  • 将原来的图片删除,再添加进去
//个人基本资料回显
function show_myself(){
    $.ajax({
        url: "/getUserById",
        type: "post",
        dataType: "json",
        success: function(userById){

            //获取图片路径
            $(".logo").remove();
            var str = "<div class=\"logo\" style=\"background-image:url(&quot;"+ userById[0].idPic +"&quot;);\" data-v-8dc533f6>\n</div>";
            $("#insert_img").prepend(str);

        },
        error: function(){
            alert("Error");
        }
    })
}

滚动分页

Controller
        //取第几页
        int pageIndex = Integer.parseInt(rq.getParameter("page"));
        //设置每页显示10条数据
        PageHelper.startPage(pageIndex,10);
        //调用方法
        List<User> allUser = userService.getUserByCondition(user);
        //获取总页数,传递给前端
        //为了之后不重复显示相同内容
        if(pageIndex == 1){
            PageInfo<User> pageInfo = new PageInfo<User>(allUser);
            int pages = pageInfo.getPages();
            rq.getSession().setAttribute("pages", pages);
        }
Ajax
  • 如果pageIndex==pages,就不再重复显示
  • 滚动后页数++,再重新show()调用Controller
  • show()方法是获取数据库的值后,append到页面,不清楚原有内容,所以第二页时候会把第二页的内容继续append进去
  • 注意:Controller我将pages存在了session中,页面写了一个hidden取这个值,再用js取得这个值放入Ajax中
/*-------------------------------------滚动分页-------------------------------------*/
function rollPage(){

    $(window).scroll(function () {
        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
        //$(window).height()获取当前窗体的高度
        //$(document).height()获取当前文档的高度
        var bot = 500; //bot是底部距离的高度
        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
            //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时;
            //我们需要去异步加载数据了
            if(pageIndex == pages){
                return false;
            }
            pageIndex++;
            show();
        }
    });
}

单击某人详细资料(id的传值)

image.png
  • 因为我首页是展示所有user表中的交友信息,然后需要通过点击某人的信息后进入查看详细信息。展示信息我是通过Ajax实现。那么点击后展现详细信息也要通过Ajax实现,那id值要怎么传呢?
  • 首先有个hidden,存放每个人的id,点击后Ajax获取id值,传给实现跳转的Controller(因为我只需要跳转到详细页面,详细页面中也是有Ajax实现详细信息的,此刻他就是需要接收一个id)
    ...
注意一定得用on,因为是动态append光靠click获取不到。on是你append的父标签,他是固定的,然后click后面写你要点击事件的类
$("#show").on("click",".all_box>img",function(){

        var id = $(this).next().val();
        location.href = "/personalInfo.html?userId="+id;
 })
 @RequestMapping("/personalInfo.html")
    public String personalInfo(@RequestParam(value="userId", required=false, defaultValue = "none")String userId, Model model){
        if(!userId.equals("none")){
            model.addAttribute("userId",userId);
        }
        return "personalInfo";
    }

存到域中后,personalInfo中有个hidden取值,然后再js取值至Ajax

(日期)

//个人展示窗口信息显示
function show_myself(){
    var userId = $("#userId").val();

    $.ajax({
        url: "/getUserById",
        type: "post",
        data: {userId: userId},
        dataType: "json",
        success: function(userById){

            //获取当前年
            var myDate = new Date();
            var year=myDate.getFullYear();
            //获取出生年,得到年龄
            var birthday = userById[0].birthday;
            var birthYear = birthday.split("-")[0];
            var age = year - birthYear;
...
    /*--------------------------------根据个人id查看信息--------------------------------*/
    @ResponseBody
    @RequestMapping("/getUserById")
    public Collection<User> getUserById(HttpServletRequest rq,@RequestParam(value="userId", required=false, defaultValue = "none")String userId){

        //单击某人信息时查看详情
        if(!userId.equals("none")){
            List<User> userById = userService.getUserById(userId);
            return userById;
        }
...

转年龄格式

  • 意识到一个问题,存入数据库不能写年龄,因为年龄会变化的。所以只能在取的时候转换一下。
  • 而且类的属性改为String会不会方便很多?如果是Date取出来的值...其实应该将Date转换一下也就可以了的。

比较下js与java

 //获取当前年
            var myDate = new Date();
            var year=myDate.getFullYear();
            //获取出生年,得到年龄
            var birthday = userById[0].birthday;
            var birthYear = birthday.split("-")[0];
            var age = year - birthYear;


        if(age != null && !age.contains("不限")){
            String age2 = age.trim();
            int age3 = Integer.parseInt(age2);
            //年龄转年份
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            Date date = new Date();
            int yearNow = Integer.parseInt(sdf.format(date));
            int year = yearNow - age3;
            user.setAge(year);
        }

项目中取值基本都用到if判断是否为空或包含某字段,再trim()去空格,因为前段会有很多换行符或者空格这些。

  • 之前一直在想我数据库存入的是Date格式的,但是我获取的时候无法对Date格式进行更改,因为mapper.xml中是直接对取到数据进行SQL判断的,那怎么办?比如我想计算年龄,取年龄大于18岁的人。
  • 现在想想应该先不用判断,先取出所有年龄的数据,在service层的时候,再对list的Date格式转换,进行判断再筛选。是吧?

mapper.xml
<trim>的用法、模糊查询、where 1=1

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.four.mapper.UserMapper">

<!--    List<User> getUserByCondition(User user);-->
    <select id="getUserByCondition" resultType="User">
        select * from tywmf_user where 1=1
        <if test="nativePlace != null and nativePlace != ''">
            and nativePlace like concat ('%',#{nativePlace},'%')
        </if>
        <if test="height != null and height != ''">
            and height > #{height}
        </if>
        <if test="income != null and income != ''">
            and income > #{income}
        </if>
        <if test="age != null">
            and birthday like concat ('%',#{age},'%')
        </if>

    </select>

<!--    void updateUser(User user);-->
    <update id="updateUser">
        update tywmf_user
        <trim prefix="set" suffixOverrides=",">
            <if test="userName!=null and userName!=''">
                userName = #{userName},
            </if>
            <if test="gender!=null and gender!=''">
                gender = #{gender},
            </if>
            <if test="maritalStatus!=null and maritalStatus!=''">
                maritalStatus = #{maritalStatus},
            </if>
            <if test="education!=null and education!=''">
                education = #{education},
            </if>
            <if test="height!=null and height!=''">
                height = #{height},
            </if>
...
        </trim>
        where userId = #{userId}
    </update>
</mapper>

mybatis-config.xml
加入了pagehelper插件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.four.entity"/>
    </typeAliases>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
</configuration>

application.yml

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/tywmf?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  config-location: classpath:/mybatis/mybatis-config.xml
  mapper-locations: classpath:/mybatis/mapper/*.xml
server:
  tomcat:
    uri-encoding: UTF-8

pom.xml
IDEA添加的时候,已经加入了mybatis-spring、mySql、JDBC

        <!--引入热部署依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- 自己添加jsp依赖 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>
        <!--/自己添加jsp依赖 -->

        <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.10</version>
        </dependency>
    </dependencies>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353