項(xiàng)目三習(xí)得(IDEA、SpringBoot)

除了文件上傳,都是用Ajax做的。感覺(jué)很好

功能:
頭像上傳與顯示
滾動(dòng)分頁(yè)
單擊某人詳細(xì)資料(id的傳值)
轉(zhuǎn)年齡格式

頭像上傳與顯示

Controller
  • 形參的名字不要變
  • 最關(guān)鍵是uploadFile.transferTo(),使文件上傳簡(jiǎn)便了許多
  • 上傳文件后存入數(shù)據(jù)庫(kù),我加了一個(gè)/img/,因?yàn)槲沂谴嬖诜?wù)器中的img路徑下的,記得在項(xiàng)目中一定要先創(chuàng)建一個(gè)img,
    其實(shí)不我怎么懂服務(wù)器和我IDEA中項(xiàng)目到底怎樣的關(guān)系。我抱著試一試的態(tài)度,發(fā)現(xiàn)創(chuàng)建了一個(gè)img后,上傳的內(nèi)容也可以從這兒取到,
    所以才在數(shù)據(jù)庫(kù)中存入地址中加了img,到時(shí)候在前端中可以直接
    <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("."));
        //最后存儲(chǔ)的路徑,是本地的服務(wù)器中
        String path = session.getServletContext().getRealPath("img")+ File.separator + finalFileName;
        System.out.println(path);
        //上傳
        File file = new File(path);
        uploadFile.transferTo(file);

        //上傳成功后,將地址存入數(shù)據(jù)庫(kù),讓前端可以直接拿圖片
        String idPic = "/img/" + finalFileName;
        User user = new User();
        user.setIdPic(idPic);
        //獲取id值
        user.setUserId(2);
        userService.updateUser(user);

        return "success";
    }
頁(yè)面
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>
頁(yè)面進(jìn)階版
image.png

image.png
Ajax
  • 將原來(lái)的圖片刪除,再添加進(jìn)去
//個(gè)人基本資料回顯
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");
        }
    })
}

滾動(dòng)分頁(yè)

Controller
        //取第幾頁(yè)
        int pageIndex = Integer.parseInt(rq.getParameter("page"));
        //設(shè)置每頁(yè)顯示10條數(shù)據(jù)
        PageHelper.startPage(pageIndex,10);
        //調(diào)用方法
        List<User> allUser = userService.getUserByCondition(user);
        //獲取總頁(yè)數(shù),傳遞給前端
        //為了之后不重復(fù)顯示相同內(nèi)容
        if(pageIndex == 1){
            PageInfo<User> pageInfo = new PageInfo<User>(allUser);
            int pages = pageInfo.getPages();
            rq.getSession().setAttribute("pages", pages);
        }
Ajax
  • 如果pageIndex==pages,就不再重復(fù)顯示
  • 滾動(dòng)后頁(yè)數(shù)++,再重新show()調(diào)用Controller
  • show()方法是獲取數(shù)據(jù)庫(kù)的值后,append到頁(yè)面,不清楚原有內(nèi)容,所以第二頁(yè)時(shí)候會(huì)把第二頁(yè)的內(nèi)容繼續(xù)append進(jìn)去
  • 注意:Controller我將pages存在了session中,頁(yè)面寫了一個(gè)hidden取這個(gè)值,再用js取得這個(gè)值放入Ajax中
/*-------------------------------------滾動(dòng)分頁(yè)-------------------------------------*/
function rollPage(){

    $(window).scroll(function () {
        //$(window).scrollTop()這個(gè)方法是當(dāng)前滾動(dòng)條滾動(dòng)的距離
        //$(window).height()獲取當(dāng)前窗體的高度
        //$(document).height()獲取當(dāng)前文檔的高度
        var bot = 500; //bot是底部距離的高度
        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
            //當(dāng)?shù)撞炕揪嚯x+滾動(dòng)的高度〉=文檔的高度-窗體的高度時(shí);
            //我們需要去異步加載數(shù)據(jù)了
            if(pageIndex == pages){
                return false;
            }
            pageIndex++;
            show();
        }
    });
}

單擊某人詳細(xì)資料(id的傳值)

image.png
  • 因?yàn)槲沂醉?yè)是展示所有user表中的交友信息,然后需要通過(guò)點(diǎn)擊某人的信息后進(jìn)入查看詳細(xì)信息。展示信息我是通過(guò)Ajax實(shí)現(xiàn)。那么點(diǎn)擊后展現(xiàn)詳細(xì)信息也要通過(guò)Ajax實(shí)現(xiàn),那id值要怎么傳呢?
  • 首先有個(gè)hidden,存放每個(gè)人的id,點(diǎn)擊后Ajax獲取id值,傳給實(shí)現(xiàn)跳轉(zhuǎn)的Controller(因?yàn)槲抑恍枰D(zhuǎn)到詳細(xì)頁(yè)面,詳細(xì)頁(yè)面中也是有Ajax實(shí)現(xiàn)詳細(xì)信息的,此刻他就是需要接收一個(gè)id)
    ...
注意一定得用on,因?yàn)槭莿?dòng)態(tài)append光靠click獲取不到。on是你append的父標(biāo)簽,他是固定的,然后click后面寫你要點(diǎn)擊事件的類
$("#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中有個(gè)hidden取值,然后再js取值至Ajax

(日期)

//個(gè)人展示窗口信息顯示
function show_myself(){
    var userId = $("#userId").val();

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

            //獲取當(dāng)前年
            var myDate = new Date();
            var year=myDate.getFullYear();
            //獲取出生年,得到年齡
            var birthday = userById[0].birthday;
            var birthYear = birthday.split("-")[0];
            var age = year - birthYear;
...
    /*--------------------------------根據(jù)個(gè)人id查看信息--------------------------------*/
    @ResponseBody
    @RequestMapping("/getUserById")
    public Collection<User> getUserById(HttpServletRequest rq,@RequestParam(value="userId", required=false, defaultValue = "none")String userId){

        //單擊某人信息時(shí)查看詳情
        if(!userId.equals("none")){
            List<User> userById = userService.getUserById(userId);
            return userById;
        }
...

轉(zhuǎn)年齡格式

  • 意識(shí)到一個(gè)問(wèn)題,存入數(shù)據(jù)庫(kù)不能寫年齡,因?yàn)槟挲g會(huì)變化的。所以只能在取的時(shí)候轉(zhuǎn)換一下。
  • 而且類的屬性改為String會(huì)不會(huì)方便很多?如果是Date取出來(lái)的值...其實(shí)應(yīng)該將Date轉(zhuǎn)換一下也就可以了的。

比較下js與java

 //獲取當(dāng)前年
            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);
            //年齡轉(zhuǎn)年份
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            Date date = new Date();
            int yearNow = Integer.parseInt(sdf.format(date));
            int year = yearNow - age3;
            user.setAge(year);
        }

項(xiàng)目中取值基本都用到if判斷是否為空或包含某字段,再trim()去空格,因?yàn)榍岸螘?huì)有很多換行符或者空格這些。

  • 之前一直在想我數(shù)據(jù)庫(kù)存入的是Date格式的,但是我獲取的時(shí)候無(wú)法對(duì)Date格式進(jìn)行更改,因?yàn)閙apper.xml中是直接對(duì)取到數(shù)據(jù)進(jìn)行SQL判斷的,那怎么辦?比如我想計(jì)算年齡,取年齡大于18歲的人。
  • 現(xiàn)在想想應(yīng)該先不用判斷,先取出所有年齡的數(shù)據(jù),在service層的時(shí)候,再對(duì)list的Date格式轉(zhuǎn)換,進(jìn)行判斷再篩選。是吧?

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添加的時(shí)候,已經(jīng)加入了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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容