除了文件上傳捶牢,都是用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(""+ userById[0].idPic +"");\" 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>