前几天我写了一个小demo,遇到了很多小问题,在此感谢我身边的小伙伴给我的帮助,最终做出来了!虽然我很笨,但是我努力了,青春,不后悔!加油吧,骚年!本人小白一枚,大神勿喷,有什么交流可以联系我的QQ:673467208(柠檬少年心亦暖)!
1.登录的controller和文件上传的controller(仅供参考):
登录:
@Controller
@RequestMapping("users/")
public class UsersController {
@Autowired
private UsersService usersService;
@RequestMapping("login")
public String login(Users user,HttpSession session,Model model){
Users u=usersService.login(user);
if(u!=null){
session.setAttribute("u",u);
return "redirect:/files/findAll.do";
}else{
model.addAttribute("msg", "登录失败,请重新登录");
return "forward:/index.jsp";
}
}
@RequestMapping("logout")
public String logout(HttpSession session){
session.removeAttribute("u");
return "redirect:/index.jsp";
}
}
文件上传:
@Controller
@RequestMapping("files/")
public class FilesController{
@Autowired
private FilesService filesService;
@RequestMapping("findAll")
public String findAll(Model model){
List<Files> filesList=filesService.findAll();
model.addAttribute("filesList", filesList);
return "success";
}
@RequestMapping("add")
public String add(MultipartFile[] fileName,HttpServletRequest request) throws IllegalStateException, IOException {
//获取服务器的绝对路径
String path=request.getSession().getServletContext().getRealPath("/")+"/upload/";
for(int i=0;i<fileName.length;i++){
MultipartFile fileUpload=fileName[i];
//1.上传文件
String filePath=path+fileUpload.getOriginalFilename();//上传文件的绝对路径
File file=new File(filePath);
if(!file.exists()){
file.mkdirs();//创建一个空文件
}fileUpload.transferTo(file);
//2.把文件信息保存到数据库
Files fileInfo=new Files();
fileInfo.setFilesname(fileUpload.getOriginalFilename());
fileInfo.setFilessize(fileUpload.getSize());
fileInfo.setFilestimes(new Date());
filesService.add(fileInfo);
}
return "redirect:/files/findAll.do";
}
@RequestMapping("del")
public String del(int id,HttpServletRequest request){
String path=request.getSession().getServletContext().getRealPath("/")+"/upload/";
Files file = filesService.getid(id);
File files=new File(path+file.getFilesname());
files.delete();
filesService.del(id);
return "redirect:/files/findAll.do";
}
}
2.配置时间格式convertor:
public class MyDateConvertor implements Converter<String, Date>{
public Date convert(String str) {
String[] patterns=new String[]{"yyyy-MM","yyyy/MM",
"yyyy-MM-dd","yyyy-MM-dd hh:mm:ss",
"yyyy/MM/dd","yyyy/MM/dd hh:mm:ss"};
Date date = null;
try {
date=DateUtils.parseDate(str, patterns);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
3.拦截器的配置interceptor:
public class MyInterceptor implements HandlerInterceptor{
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2) throws Exception {
Users users = (Users)request.getSession().getAttribute("u");
if(users!=null)
{
return true;
}else{
request.getRequestDispatcher("/index.jsp").forward(request, response);
return false;
}
}
}
这里需要注意的是
Users users = (Users)request.getSession().getAttribute(“u”)中的参数(u)要与登录的controller中的session.setAttribute(“u”,u)(U)相同,否则无法传参;
4.配置mapper:
登录的mapper&xml和文件上传的mapper&xml:
public interface UsersMapper {
public Users login(Users users);
}
<select id="login" parameterType="Users" resultType="Users">
select * from users where name=#{name} and pwd=#{pwd}
</select>
public interface FilesMapper {
public List<Files> findAll();
public void add(Files filesInfo);
public void del(int id);
public Files getid(int id);
}
<select id="findAll" resultType="files">
select * from files
</select>
<insert id="add" parameterType="files">
insert into files values(seq_files.nextval,#{filesname},#{filessize},#{filestimes})
</insert>
<delete id="del" parameterType="int">
delete from files where id=#{id}
</delete>
<select id="getid" resultType="files">
select * from files where id=#{id}
</select>
5.pojo也就是封装数据:
(本人使用逆向工程)
private BigDecimal id;
private String name;
private String pwd;
private BigDecimal id;
private String filesname;
private long filessize;
private Date filestimes;
6.实现类service与目标类serviceimpl;
public interface UsersService {
public Users login(Users users);
}
@Service
public class UsersServiceImpl implements UsersService{
@Autowired
private UsersMapper usersMapper;
public Users login(Users users) {
return usersMapper.login(users);
}
}
public interface FilesService {
public List<Files> findAll();
public void add(Files fileInfo);
public void del(int id);
public Files getid(int id);
}
@Service
public class FilesServiceImpl implements FilesService {
@Autowired
private FilesMapper filesMapper;
public List<Files> findAll() {
return filesMapper.findAll();
}
@Override
public void add(Files fileInfo) {
// TODO Auto-generated method stub
filesMapper.add(fileInfo);
}
@Override
public void del(int id) {
// TODO Auto-generated method stub
filesMapper.del(id);
}
@Override
public Files getid(int id) {
return filesMapper.getid(id);
}
}
7.登录页面:
<center>
<h1>网络U盘</h1>
<form action="users/login.do" method="post">
<div>${msg }</div>
<div class="form-group">
<label for="exampleInputEmail1">用户名</label>
<input type="text" class="form-control" name="name" id="exampleInputEmail1" placeholder="用户名">
</div>
<div class="form-group">
<label for="exampleInputPassword1">密码</label>
<input type="password" class="form-control" name="pwd" id="exampleInputPassword1" placeholder="密码">
</div>
<button type="submit" class="btn btn-default">登录</button>
</form>
</center>
8.显示正文:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'success.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<jsp:include page="/common/include.jsp"></jsp:include>
</head>
<script type="text/javascript">
$(function(){
$("#sel").change(function(){
$("#files").empty();
var str=$(this).val();
for(var i=0;i<str;i++){
$("#files").append('<input type="file" name="fileName" id="fileHead">');
}
});
});
</script>
<style type="text/css">
body{
width:60%;
margin-left:5%;
}
</style>
<body>
<h1>网络U盘</h1>
<div>欢迎${sessionScope.u.name }登录<a href="users/logout.do">退出</a></div>
<table class="table table-bordered table-hover">
<tr>
<th>ID</th>
<th>文件名</th>
<th>文件大小</th>
<th>上传日期</th>
<th>操作</th>
</tr>
<c:forEach items="${filesList}" var="f">
<tr>
<td>${f.id }</td>
<td>${f.filesname }</td>
<td>${f.filessize }KB</td>
<td>
<fmt:formatDate value="${f.filestimes }" pattern="yyyy-MM-dd"/>
</td>
<td>
<a href="files/del.do?id=${f.id }">删除</a>
</td>
</tr>
</c:forEach>
</table>
<h3>上传文件模块</h3>
<form action="files/add.do" method="post" enctype="multipart/form-data">
<span>上传文件的数量</span>
<select id="sel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="files">
<input type="file" name="fileName" id="fileHead"/>
</div>
<input type="submit" value="上传"/>
</form>
</body>
</html>
这是登录和上传的代码,这些都需要运行于ssm环境,jar包都在一下地址:
环境与jar包