登录功能实现简单介绍:
1:登录时密码输入错误刷新登陆页面并提示登录信息错误;
2:输入正确用户名及密码点击sign in 登录成功。(如果勾选remember me 只要服务器未停止,可以直接免登录进入欢迎页面,否则会提示请先登录并进入登录页面)
3:进入欢迎页面点击用户名可以看到logout按钮,点击logout清除当前用户登录信息并退出到登录页面;
文件上传下载简单介绍:
上传:可以填写相关信息并上传文件并将文件上传到提前准备好的文件夹中(D://upload)中。
下载:可以点击对应文件超链接进行文件的下载;
主要功能代码展示:
Servlet代码:
Loginservlet:
@WebServlet(urlPatterns = "/login.do")
public class loginServlet extends HttpServlet {
StudentDao studentDao = new StudentDao();
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req,resp);
resp.sendRedirect("login.jsp");
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String rember = req.getParameter("rember");
Student student = new StudentDao().findInstance(username,password);
if(student!=null){//登录成功
if(rember!=null){
//cookie
Cookie cookie = new Cookie("username",username);
cookie.setMaxAge(60);
resp.addCookie(cookie);
}
req.getSession().setAttribute("users",student);
// req.getSession().setAttribute("username",username);
resp.sendRedirect("welcome.jsp");
}else{
req.setAttribute("error","输入用户名密码错误");
//输入信息错误,带着错误提示信息(request作用域)转入新的登陆页面
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
}
Logoutservlet;
@WebServlet(urlPatterns = "/logout.do")
public class logoutSrevlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().invalidate();//销毁session
resp.sendRedirect("index.jsp");
}
}
Filelistservlet:
@WebServlet(urlPatterns = "/filelist.do")
public class filelistServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File fold = new File("D:\\upload");
File[] fs = fold.listFiles();
// System.out.println(fs);
// for (File f : fs) {
// System.out.println(f.getName());
// }
//将文件数组传入响应页面(request作用域)
req.setAttribute("files",fs);
req.getRequestDispatcher("down.jsp").forward(req,resp);
}
}
Uploadservelt:(smartupload实现)
@WebServlet(urlPatterns = "/upload.do")
public class uploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
SmartUpload smartUpload = new SmartUpload();
smartUpload.initialize(this.getServletConfig(),req,resp);
smartUpload.setCharset("UTF-8");
try {
smartUpload.upload();
Request request = smartUpload.getRequest();
String bookname = request.getParameter("bookname");
String[] hobbies = request.getParameterValues("hobbies");
System.out.println("bookname:"+bookname);
System.out.println("hobbies"+ Arrays.toString(hobbies));
smartUpload.save("D:\\upload");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Downloadservlet:
@WebServlet(urlPatterns = "/down.do")
public class downloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String filename = req.getParameter("filename");
File file = new File("D:/upload/"+filename);//要下载的文件
FileInputStream inputStream = new FileInputStream(file);
try {
String downname = new String(filename.getBytes("UTF-8"),"ISO-8859-1");//将原来的文件名更改为西欧编码格式
resp.setHeader("content-disposition", "attachment;filename="+downname);//文件下载之后的文件名是西欧编码
OutputStream outputStream = resp.getOutputStream();
byte[] bs = new byte[inputStream.available()];
inputStream.read(bs);
outputStream.write(bs);
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
工具类代码:(过滤器)
Encodingfilter:
public class EncodingFilter implements Filter {
String encode = "UTF-8";
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
request.setCharacterEncoding(encode);
filterChain.doFilter(request, servletResponse);
}
}
Loginfileter:
public class LoginFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
//判断cookie
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0){
for (Cookie c:cookies) {
if(c.getName().equals("username")){
String name = c.getValue();
StudentDao studentDao = new StudentDao();
Student user = studentDao.findByName(name);
request.getSession().setAttribute("users",user);
//直接转到欢迎页面
}
}
}
Student users = (Student)request.getSession().getAttribute("users");
String uri = request.getRequestURI();//获取请求的路径地址
System.out.println(uri+"--------------");
if(users!=null||uri.contains("login")){
filterChain.doFilter(servletRequest,servletResponse);
}else{//users是为null说明没有登录
//response.sendRedirect("index.jsp");
request.setAttribute("error","请先登录再访问");
request.getRequestDispatcher("index.jsp").forward(request,response);
}
}
}
Jsp代码:
Upload.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="upload.do">
<p>图书名字<input type="text" name="bookname"/> </p>
<p>图书图片:<input type="file" name="file"/></p>
<p> <input type="file" name="file"/></p>
<p>兴趣爱好:<input type="checkbox" value="pingpong" name="hobbies"/>乒乓球
<input type="checkbox" value="football" name="hobbies"/>足球
<input type="checkbox" value="basketball" name="hobbies"/>篮球
<input type="checkbox" value="table tennis" name="hobbies"/>桌球
</p>
<input type="submit" value="上传"/>
</form>
</body>
</html>
Down.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>下载</title>
</head>
<body>
<c:forEach items="${files}" var="file">
<p>
<a href="down.do?filename=${file.name}">${file.name}</a>
</p>
</c:forEach>
</body>
</html>
配置文件:
Web.xml:(配置过滤器的映射关系及执行顺序)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.openlab.utils.EncodingFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.openlab.utils.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
</web-app>
效果展示:
1:登录不成功:(提示输入用户名密码错误)
2:不登录进入欢迎页面:(转入登录页面提示请先登录再访问)
3:正确输入并勾选remember me:(登录成功进入欢迎页面并且可以通过输入网址直接访问欢迎页面)
4:点击用户名出现一个下拉菜单,点击logout退出并转到登录页面,并且不能直接通过网址直接访问欢迎页面。(cookie失效)
5:文件上传:(红色框中为刚刚添加的文件)
6:文件下载:(点击超链接进入下载页面,下载文件)