Servlet Class3

1.GET請求的語法css

<a href="download?filename=1366768.jpg">下載圖片</a><!-- get請求寫法:地址?請求屬性名=請求屬性值-->

多個屬性間用&分隔html

2.經過設置響應頭來實現下載功能java

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="download?filename=1366768.jpg">下載圖片</a>
<a href="download?filename=1366.jpg">下載圖片</a>
<a href="download?filename=你好.txt">下載中文名稱文檔</a>
</body>
</html>
public class DownLoadServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getParameter("filename");
        File f = new File(this.getServletContext().getRealPath("download/"+filename));//獲取服務器資源
        if(f.exists()) {//解決文件名中文問題
            String agent = request.getHeader("user-agent");
            if (agent.contains("MSIE")) {
                // IE瀏覽器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            } else if (agent.contains("Firefox")) {
                // 火狐瀏覽器
                BASE64Encoder base64Encoder = new BASE64Encoder();
                filename = "=?utf-8?B?"
                        + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
            } else {
                // 其它瀏覽器
                filename = URLEncoder.encode(filename, "utf-8");                
            }
            response.setContentType(this.getServletContext().getMimeType(f.getPath()));//設置頁面文件類型
            response.setHeader("Content-Disposition", "attachment;filename="+filename);//以附件方式打開文件
            ServletOutputStream sos = response.getOutputStream();
            FileInputStream fis = new FileInputStream(f);
            int len = 0;
            byte[] b = new byte[1024];
            while((len=fis.read(b))!=-1) {
                sos.write(b,0,len);
            }
            fis.close();
        }else {
            response.setContentType("text/html;charset=utf-8");//解決響應中文問題
            response.getWriter().println("<h2 style='color:red;'>文件不存在!</h2>");
        }
        
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

 3.驗證碼生成jquery

public class CheckImgServlet extends HttpServlet {

    // 集合中保存全部成語
    private List<String> words = new ArrayList<String>();

    @Override
    public void init() throws ServletException {
        // 初始化階段,讀取new_words.txt
        // web工程中讀取 文件,必須使用絕對磁盤路徑
        String path = getServletContext().getRealPath("/WEB-INF/new_words.txt");
        try {
            BufferedReader reader = new BufferedReader(new FileReader(path));
            String line;
            while ((line = reader.readLine()) != null) {
                words.add(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 禁止緩存
        // response.setHeader("Cache-Control", "no-cache");
        // response.setHeader("Pragma", "no-cache");
        // response.setDateHeader("Expires", -1);

        int width = 120;
        int height = 30;

        // 步驟一 繪製一張內存中圖片
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        // 步驟二 圖片繪製背景顏色 ---經過繪圖對象
        Graphics graphics = bufferedImage.getGraphics();// 獲得畫圖對象 --- 畫筆
        // 繪製任何圖形以前 都必須指定一個顏色
        graphics.setColor(getRandColor(200, 250));
        graphics.fillRect(0, 0, width, height);

        // 步驟三 繪製邊框
        graphics.setColor(Color.WHITE);
        graphics.drawRect(0, 0, width - 1, height - 1);

        // 步驟四 四個隨機數字
        Graphics2D graphics2d = (Graphics2D) graphics;
        // 設置輸出字體
        graphics2d.setFont(new Font("宋體", Font.BOLD, 18));

        Random random = new Random();// 生成隨機數
        int index = random.nextInt(words.size());
        String word = words.get(index);// 得到成語
        
        // 定義x座標
        int x = 10;
        for (int i = 0; i < word.length(); i++) {
            // 隨機顏色
            graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
                    .nextInt(110), 20 + random.nextInt(110)));
            // 旋轉 -30 --- 30度
            int jiaodu = random.nextInt(60) - 30;
            // 換算弧度
            double theta = jiaodu * Math.PI / 180;

            // 得到字母數字
            char c = word.charAt(i);

            // 將c 輸出到圖片
            graphics2d.rotate(theta, x, 20);
            graphics2d.drawString(String.valueOf(c), x, 20);
            graphics2d.rotate(-theta, x, 20);
            x += 30;
        }

        // 將驗證碼內容保存session
        request.getSession().setAttribute("checkcode_session", word);

        // 步驟五 繪製干擾線
        graphics.setColor(getRandColor(160, 200));
        int x1;
        int x2;
        int y1;
        int y2;
        for (int i = 0; i < 30; i++) {
            x1 = random.nextInt(width);
            x2 = random.nextInt(12);
            y1 = random.nextInt(height);
            y2 = random.nextInt(12);
            graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
        }

        // 將上面圖片輸出到瀏覽器 ImageIO
        graphics.dispose();// 釋放資源
        
        //將圖片寫到response.getOutputStream()中
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * 取其某一範圍的color
     * 
     * @param fc
     *            int 範圍參數1
     * @param bc
     *            int 範圍參數2
     * @return Color
     */
    private Color getRandColor(int fc, int bc) {
        // 取其隨機顏色
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

}

 使用案例:web

注意,驗證碼中設置的Session值須要在另外一個servlet中獲取,利用輸入的成語與生成的成語做比較,比較這一步也要放在servlet中,若是利用顯示驗證碼的頁面中定義js直接獲取session值是獲取不到的、或者是獲取到前一個已通過期的session值,驗證碼圖片以前是隱藏的,知足必定條件後顯示,因此隨着頁刷新session值一直在改變。ajax

即便在知足必定條件後再給img的src填寫地址,也會致使session值被設置,可是在當前頁面不刷新的狀況下,直接獲取必然是null,在頁面再次刷新後,圖片也再次刷新,此時雖然能獲取到session值,但也是前一次生成的值,致使你獲取到的session值永遠是過時的,這裏要利用ajax向驗證servlet發送請求,根據返回的Text來進行操做。
bootstrap

究其緣由,是由於頁面運行在客戶端,而session保存在服務端,只有客戶端發起一次請求後,才能獲取到session值,而servlet運行在服務端,能夠隨時獲取到session值。瀏覽器

 

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>歡迎</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
    * {
        margin: 0px;
        padding: 0px;
    }
    .form {
        position: absolute;
        top: 350px;
        left: 462px;
        height: 300px;
        width: 700px;
    }
    body {
        background-color: #c1c1c1;
    }
    .header {
        position: absolute;
        top: -50px;
        left: 230px;
    }
</style>
<script>
$(document).ready(function(){
            var uname = document.getElementById("uname");
            var pwd = document.getElementById("pwd");
            var uspan = document.getElementById("uspan");
            var pspan = document.getElementById("pspan");
            var message = "${message }";
            if(message !=""){
                var wrong = parseInt("${wrong}");
                if(wrong>=2){//輸錯兩次顯示驗證碼
                     $("#code").show();
                     document.getElementById("lbtn").disabled=true;
                }
                uname.style.borderColor = "red";
                pwd.style.borderColor = "red";
                uspan.innerHTML = "×"+message;
                   pspan.innerHTML = "×"+message;        
            }
        });
    
    </script>
</head>
<c:if test="${!empty cookie.logSta &&cookie.logSta.value eq '1'}">
    <c:redirect url="success.jsp?uname=${cookie.uname.value }"/>
</c:if>
<body style="overflow:hidden;">
<div class="header">
    <img src="img/1.png" alt="" height="50%" width="80%">
</div>
<div class="form">
    <form class="form-horizontal" role="form" action="login"  method="post">
      <div class="form-group">
        <label for="firstname" class="col-sm-2 control-label">用戶名</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="uname" placeholder="請輸入用戶名" name="user" style="width:200px;display:inline;">
          <span style="color:red;" id="uspan"></span>
        </div>
      </div>
      <div class="form-group">
        <label for="lastname" class="col-sm-2 control-label">密碼</label>
        <div class="col-sm-10">
          <input type="password" class="form-control" id="pwd" placeholder="請輸密碼" name="pwd" style="width:200px;display:inline;">
          <span style="color:red;" id="pspan"></span>
        </div>
      </div>
      <div class="form-group" id="code" style="display:none;">
        <label for="lastname" class="col-sm-2 control-label">驗證碼</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="checkImg" placeholder="請輸驗證碼"  style="width:200px;display:inline;" onBlur="check()">
          <img src="checkImg" onClick="changeImg(this)" id="img">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <div class="checkbox">
            <label>
              <input type="checkbox" name="autologin">請記住我
            </label>
          </div>
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default" id="lbtn">登陸</button>
          <a class="btn btn-primary" href="signUp.html">註冊</a>
        </div>
      </div>
    </form>
</div>
<script>
var count = 0;
function changeImg(obj){
    obj.src="checkImg?time="+count;
    count++;
    if(count==650){
        count = 0;
    }
}
var xmlhttp;
var checkImg = document.getElementById('checkImg');
function check(){
        var val = checkImg.value;
        var url = "check?val="+val;//向驗證地址提交輸入的值
        xmlhttp =new XMLHttpRequest();
        xmlhttp.onreadystatechange=checkResult; 
        xmlhttp.open("GET",url,true); 
        xmlhttp.send();  
}
function checkResult(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var result = xmlhttp.responseText;//獲取返回的文本
            if(result=="yes"){
                checkImg.style.borderColor="green";
                document.getElementById("lbtn").disabled=false;
            }else{
                checkImg.style.borderColor="red";
                document.getElementById("lbtn").disabled=true;
            }
        }
}
</script>
</body>
</html>
package com.login.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.login.model.dao.UserDAO;

public class LoginServlet extends HttpServlet{
    private UserDAO userDAO = new UserDAO(); 
    private int wrong;
    @Override
    public void init() {
        wrong = 0;
    }
    @Override
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
        //doPost(request,response);
        
    }
    @Override
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
        
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");
        String autologin = request.getParameter("autologin");
        if(!userDAO.login(user, pwd)) {
            wrong++;//設置錯誤次數
            request.setAttribute("wrong", wrong);
            request.setAttribute("message", "帳戶名或密碼錯誤!");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }else {
            wrong = 0;
            if(autologin!=null) {
                Cookie uname = new Cookie("uname",user);
                Cookie logSta = new Cookie("logSta","1");//保存用戶登陸狀態碼
                logSta.setMaxAge(60*60*24*7);//有效期一週
                uname.setMaxAge(60*60*24*7);
                response.addCookie(logSta);
                response.addCookie(uname);
            }
            request.setAttribute("user", user);
            request.getRequestDispatcher("success.jsp").forward(request, response);
        }
    }
}
package com.login.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String word = (String) request.getSession().getAttribute("checkcode_session");
        response.setContentType("text/html;charset=utf-8");
        if(request.getParameter("val").equals(word)){//輸入值和生成值做比較    
            response.getWriter().print("yes");
        }else {
            response.getWriter().print("no");
        }
    
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
相關文章
相關標籤/搜索