带头像的注册小项目(下)
要求:
用户注册成功后,跳转页面.点击下载后下载资源.同时下载次数+1
并记录日志信息,格式: xxxx下载了xxxx
1.创建数据库相关语句
create table files(
id int(10) primary key auto_increment,
name varchar(20),
count int(10)
);
加入测试数据,把图片信息存储到files文件夹中
insert into files values(default,'a.png',0);
insert into files values(default,'b.png',0);
2.创建实体类pojo
加入set和get方法
public class Files {
private int id;
private String name;
private int count;
}
3.创建mapper层
进行查询全部,所以是List
public interface FilesMapper {
@Select("select * from files")
List<Files> selAll();
@Update("update files set count=count+1 where id=#{0}")
int updCountById(int id);
}
4.创建service层
接口
public interface FilesService {
/**
* 显示全部
*/
List<Files> show();
/**
* 根据id修改资料下载次数
*/
int updCount(int id,Users users,String name);
}
实现类
@Service把该类交给spring管理,在下方进行依赖注入
@Service
public class FileServiceImpl implements FilesService {
@Resource
private FilesMapper filesMapper;
@Override
public List<Files> show() {
return filesMapper.selAll();
}
@Override
public int updCount(int id,Users users,String name) {
Logger logger = Logger.getLogger(FileServiceImpl.class);
logger.info(users.getUsername()+name);
return filesMapper.updCountById(id);
}
}
5.创建控制器controller类
数据传入用request作用域进行传入,用Model,本质就是request作用域
@Controller
public class FilesController {
@Resource
private FilesService filesServiceImpl;
@RequestMapping("show")
public String show(Model model){
model.addAttribute("list", filesServiceImpl.show());
return "/main.jsp";
}
@RequestMapping("download")
public void download(int id,String name,HttpServletResponse res,HttpServletRequest req) throws IOException{
filesServiceImpl.updCount(id,(Users)req.getSession().getAttribute("user"),name);
res.setHeader("Content-Disposition", "attachment;filename="+name);
ServletOutputStream os = res.getOutputStream();
File file = new File(req.getServletContext().getRealPath("files"),name);
os.write(FileUtils.readFileToByteArray(file));
os.flush();
os.close();
}
}
6.新建main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$("a").click(function(){
//parent() 父标签
//prev() 前一个兄弟标签
//jquery中规范,对象名以$开头
var $td =$(this).parent().prev();
//html()返回值字符串
$td.html(parseInt($td.html())+1);
});
})
</script>
</head>
<body>
<table border="1">
<tr>
<td>资料名称</td>
<td>下载次数</td>
<td>操作</td>
</tr>
<c:forEach items="${list }" var="file">
<tr>
<td>${file.name }</td>
<td>${file.count }</td>
<td><a href="download?id=${file.id }&name=${file.name}">下载</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>