年轻人的第一个WEB下载案例

2018-07-11  本文已影响0人  北冥有鱼_很好吃

1.项目环境的搭建

项目的搭建.PNG

2.loginFilter 登陆验证过滤器(验证用户是否登陆)

package com.itheima.expand.Filter;
import com.itheima.expand.entity.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * description:<登陆验证过滤器>
 * create by Richard  on  2018-07-11
 */
@WebFilter(urlPatterns = { "/queryResourceServlet","/listResourceServlet","/downloadServlet"})
public class loginFilter implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        User existUser = (User)request.getSession().getAttribute("login_succeed");
        if (existUser!=null){
            chain.doFilter(request, response);
        }else {
            response.sendRedirect("/index.html");
        }
    }
    public void init(FilterConfig config) throws ServletException {
    }
}

登陆界面效果图:

登陆显示界面.PNG

资源下载界面效果图:

资源下载界面.PNG

3.Code(Servlet)验证码生成器(可以在登陆的时候加上验证码,但这里没用到验证码)

package com.itheima.expand.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 *  create by Richard  on  2018-07-06
 */
@WebServlet("/CodeServlet")
public class Code extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // gui 生成图片

        // 1 高和宽

        int height = 30;

        int width = 60;

        String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";

        Random random = new Random();

        // 2 创建一个图片

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 3 获得画板

        Graphics g = image.getGraphics();

        // 4 填充一个矩形

        // * 设置颜色

        g.setColor(Color.BLACK);

        g.fillRect(0, 0, width, height);

        g.setColor(Color.WHITE);

        g.fillRect(1, 1, width - 2, height - 2);

        // * 设置字体

        g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 25));
       
        StringBuffer sb = new StringBuffer();

        // 5 写随机字

        for (int i = 0; i < 4; i++) {

            // 设置颜色--随机数

            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));

            // 获得随机字

            int index = random.nextInt(data.length());

            String str = data.substring(index, index + 1);

            // 写入

            g.drawString(str, width / 6 * (i + 1), 20);
            sb.append(str);//  获取验证码数据

        }
        //  验证码保存到session中
        request.getSession().setAttribute("code",sb.toString());


        // 6 干扰线

        for (int i = 0; i < 3; i++) {

            // 设置颜色--随机数

            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));

            // 随机绘制先
            g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
            // 随机点
            g.drawOval(random.nextInt(width), random.nextInt(height), 2, 2);
        }
        // end 将图片响应给浏览器
        ImageIO.write(image, "jpg", response.getOutputStream());

    }
}

4. DownloadServlet下载器的核心代码

package com.itheima.expand.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * description:<下载服务器>
 * create by Richard  on  2018-07-06
 */
@WebServlet(name = "DownloadServlet", urlPatterns = "/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取用户提交的文件名
        String filename = request.getParameter("filename");
        System.out.println("用户下载了"+filename);
        //下载资源 : 一个流  两个头 (附件弹窗,文件类型)
        ServletContext servletContext = getServletContext();
        String path = servletContext.getRealPath("/WEB-INF/"+filename);
        File file = new File(path);
        if(file.exists()) {
            FileInputStream in = new FileInputStream(file);
            ServletOutputStream out = response.getOutputStream();
            int len = -1;
            byte[] bytes = new byte[1024 * 4];
            while ((len = in.read(bytes))!=-1) {
                //响应头1.弹窗附件 2.文件的MIME类型
                response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("gbk"), "ISO8859-1"));
              //设置下载时文件名编码 解决乱码问题
                String mimeType = servletContext.getMimeType(filename);
                response.setContentType(mimeType);
                out.write(bytes,0,len);
            }
            in.close();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        doPost(request, response);
    }
}

5.ListResourceServlet资源下载展示页面(最low的手动UI😂)


package com.itheima.expand.servlet;

import com.itheima.expand.entity.MyResource;
import com.itheima.expand.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


/**
 * description:<ListResourceServlet 职责:response将List<Resource>获取 显示资源列表页面>
 * create by Richard  on  2018-07-06
 */
@WebServlet(name = "ListResourceServlet", urlPatterns = "/listResourceServlet")
public class ListResourceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        List<MyResource> resources = (List<MyResource>) request.getAttribute("list");
        PrintWriter out = response.getWriter();
        out.print("<html>");
        User user = (User)request.getSession().getAttribute("login_succeed");
        out.print("<h1>Welcome "+user.getNickname()+" to load musics</h1>");
        for (MyResource resource : resources) {
            String filename = resource.getFilename();
            String str = "<a href='downloadServlet?filename="+filename+"'>"+filename+"</a><br>";
            out.print(str);
        }
        out.print("</html>");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        doPost(request, response);
    }
}

6. LoginServlet 登陆服务

package com.itheima.expand.servlet;
import com.itheima.expand.entity.User;
import com.itheima.expand.utils.DruidUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * description:<登陆服务:用户登陆成功后跳转(转发)到queryResourceServlet 查询服务;登陆失败提醒用户"登陆失败请检查用户名和密码">
 * create by Richard  on  2018-07-06
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取用户信息与数据库用户表users比较是否存在
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //1. 创建JdbcTemplate对象,传入数据源
        JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
        //2. 编写SQL语句
        String sql = "select * from users where username=? and password=?";
        //3. 使用JdbcTemplate对象的queryForObject方法查询结果
        User user = null;
        try {
            user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password);
        } catch (DataAccessException e) {
            System.out.println("someone error_login");
        }
        if (null==user){
            //登陆失败重新跳转到登陆界面
            response.sendRedirect("re_index.html");
        }else{
            //登陆成功 跳转到 queryResourceServlet
            //response.sendRedirect("/queryResourceServlet");
            //绑定转发
           /* request.setAttribute("login_succeed",user.getNickname());
            request.getRequestDispatcher("/queryResourceServlet").forward(request,response);*/
           request.getSession().setAttribute("login_succeed",user);
           response.sendRedirect("/queryResourceServlet");
            System.out.println(user.getNickname()+" login succeed");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        doPost(request, response);
    }
}

7.查询服务,查询资源,将歌曲名称存到集合

package com.itheima.expand.servlet;
import com.itheima.expand.entity.MyResource;
import com.itheima.expand.entity.User;
import com.itheima.expand.utils.DruidUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
 * description:<查询服务,查询数据库resources资源  获取List<Resource>  转发到ListResourceServlet >
 * create by Richard  on  2018-07-06
 */
@WebServlet(name = "QueryResourceServlet", urlPatterns = "/queryResourceServlet")
public class QueryResourceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
            String sql = "select * from resources";
            List<MyResource> myResources = null;
            try {
                myResources = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MyResource.class));
            } catch (DataAccessException e) {
                e.printStackTrace();
            }
            //绑定转发
            request.setAttribute("list", myResources);
            request.getRequestDispatcher("/listResourceServlet").forward(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        doPost(request, response);
    }
}
上一篇下一篇

猜你喜欢

热点阅读