項目三習(xí)得(IDEA晾剖、SpringBoot)

除了文件上傳捶牢,都是用Ajax做的崖叫。感覺很好

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

頭像上傳與顯示

Controller
  • 形參的名字不要變
  • 最關(guān)鍵是uploadFile.transferTo()欣范,使文件上傳簡便了許多
  • 上傳文件后存入數(shù)據(jù)庫又沾,我加了一個/img/弊仪,因為我是存在服務(wù)器中的img路徑下的,記得在項目中一定要先創(chuàng)建一個img杖刷,
    其實不我怎么懂服務(wù)器和我IDEA中項目到底怎樣的關(guān)系励饵。我抱著試一試的態(tài)度,發(fā)現(xiàn)創(chuàng)建了一個img后滑燃,上傳的內(nèi)容也可以從這兒取到役听,
    所以才在數(shù)據(jù)庫中存入地址中加了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("."));
        //最后存儲的路徑典予,是本地的服務(wù)器中
        String path = session.getServletContext().getRealPath("img")+ File.separator + finalFileName;
        System.out.println(path);
        //上傳
        File file = new File(path);
        uploadFile.transferTo(file);

        //上傳成功后,將地址存入數(shù)據(jù)庫乐严,讓前端可以直接拿圖片
        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>
頁面進(jìn)階版
image.png

image.png
Ajax
  • 將原來的圖片刪除瘤袖,再添加進(jìn)去
//個人基本資料回顯
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"));
        //設(shè)置每頁顯示10條數(shù)據(jù)
        PageHelper.startPage(pageIndex,10);
        //調(diào)用方法
        List<User> allUser = userService.getUserByCondition(user);
        //獲取總頁數(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ù)顯示
  • 滾動后頁數(shù)++捂敌,再重新show()調(diào)用Controller
  • show()方法是獲取數(shù)據(jù)庫的值后,append到頁面既琴,不清楚原有內(nèi)容占婉,所以第二頁時候會把第二頁的內(nèi)容繼續(xù)append進(jìn)去
  • 注意:Controller我將pages存在了session中,頁面寫了一個hidden取這個值甫恩,再用js取得這個值放入Ajax中
/*-------------------------------------滾動分頁-------------------------------------*/
function rollPage(){

    $(window).scroll(function () {
        //$(window).scrollTop()這個方法是當(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+滾動的高度〉=文檔的高度-窗體的高度時逆济;
            //我們需要去異步加載數(shù)據(jù)了
            if(pageIndex == pages){
                return false;
            }
            pageIndex++;
            show();
        }
    });
}

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

image.png
  • 因為我首頁是展示所有user表中的交友信息,然后需要通過點擊某人的信息后進(jìn)入查看詳細(xì)信息磺箕。展示信息我是通過Ajax實現(xiàn)奖慌。那么點擊后展現(xiàn)詳細(xì)信息也要通過Ajax實現(xiàn),那id值要怎么傳呢松靡?
  • 首先有個hidden升薯,存放每個人的id,點擊后Ajax獲取id值击困,傳給實現(xiàn)跳轉(zhuǎn)的Controller(因為我只需要跳轉(zhuǎn)到詳細(xì)頁面涎劈,詳細(xì)頁面中也是有Ajax實現(xiàn)詳細(xì)信息的,此刻他就是需要接收一個id)
    ...
注意一定得用on阅茶,因為是動態(tài)append光靠click獲取不到蛛枚。on是你append的父標(biāo)簽,他是固定的脸哀,然后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){

            //獲取當(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ù)個人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;
        }
...

轉(zhuǎn)年齡格式

  • 意識到一個問題盲镶,存入數(shù)據(jù)庫不能寫年齡侥袜,因為年齡會變化的。所以只能在取的時候轉(zhuǎn)換一下溉贿。
  • 而且類的屬性改為String會不會方便很多枫吧?如果是Date取出來的值...其實應(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);
        }

項目中取值基本都用到if判斷是否為空或包含某字段九杂,再trim()去空格,因為前段會有很多換行符或者空格這些宣蠕。

  • 之前一直在想我數(shù)據(jù)庫存入的是Date格式的例隆,但是我獲取的時候無法對Date格式進(jìn)行更改,因為mapper.xml中是直接對取到數(shù)據(jù)進(jìn)行SQL判斷的抢蚀,那怎么辦镀层?比如我想計算年齡,取年齡大于18歲的人皿曲。
  • 現(xiàn)在想想應(yīng)該先不用判斷唱逢,先取出所有年齡的數(shù)據(jù),在service層的時候谷饿,再對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添加的時候盯蝴,已經(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)容合作請聯(lián)系作者
  • 序言:七十年代末捧挺,一起剝皮案震驚了整個濱河市虑绵,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌闽烙,老刑警劉巖翅睛,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異黑竞,居然都是意外死亡捕发,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進(jìn)店門很魂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來扎酷,“玉大人,你說我怎么就攤上這事遏匆》òぃ” “怎么了谁榜?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長凡纳。 經(jīng)常有香客問我窃植,道長,這世上最難降的妖魔是什么惫企? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任撕瞧,我火速辦了婚禮,結(jié)果婚禮上狞尔,老公的妹妹穿的比我還像新娘丛版。我一直安慰自己,他們只是感情好偏序,可當(dāng)我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布页畦。 她就那樣靜靜地躺著,像睡著了一般研儒。 火紅的嫁衣襯著肌膚如雪豫缨。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天端朵,我揣著相機(jī)與錄音好芭,去河邊找鬼冲呢。 笑死,一個胖子當(dāng)著我的面吹牛敬拓,可吹牛的內(nèi)容都是我干的邻薯。 我是一名探鬼主播,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼乘凸,長吁一口氣:“原來是場噩夢啊……” “哼厕诡!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起营勤,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤灵嫌,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后葛作,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體寿羞,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年进鸠,在試婚紗的時候發(fā)現(xiàn)自己被綠了稠曼。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖霞幅,靈堂內(nèi)的尸體忽然破棺而出漠吻,到底是詐尸還是另有隱情,我是刑警寧澤司恳,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布途乃,位于F島的核電站,受9級特大地震影響扔傅,放射性物質(zhì)發(fā)生泄漏耍共。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一猎塞、第九天 我趴在偏房一處隱蔽的房頂上張望试读。 院中可真熱鬧,春花似錦荠耽、人聲如沸钩骇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽倘屹。三九已至,卻和暖如春慢叨,著一層夾襖步出監(jiān)牢的瞬間纽匙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工拍谐, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留烛缔,地道東北人。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓赠尾,卻偏偏與公主長得像力穗,于是被迫代替她去往敵國和親毅弧。 傳聞我的和親對象是個殘疾皇子气嫁,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,901評論 2 355