除了文件上传,都是用Ajax做的。感觉很好
功能:
头像上传与显示
滚动分页
单击某人详细资料(id的传值)
转年龄格式
头像上传与显示
Controller
- 形参的名字不要变
- 最关键是uploadFile.transferTo(),使文件上传简便了许多
- 上传文件后存入数据库,我加了一个/img/,因为我是存在服务器中的img路径下的,记得在项目中一定要先创建一个img,
其实不我怎么懂服务器和我IDEA中项目到底怎样的关系。我抱着试一试的态度,发现创建了一个img后,上传的内容也可以从这儿取到,
所以才在数据库中存入地址中加了img,到时候在前端中可以直接
<img src="/img/..." />
//文件上传
@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";
}
页面
<form action="/up" enctype="multipart/form-data" method="post" style="display: none;" id="show_up">
<input type="file" name="uploadFile"/>
<input type="submit"/>
</form>
页面进阶版
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(""+ userById[0].idPic +"");\" 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的传值)
- 因为我首页是展示所有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>