javaWeb 每天積極向上

I GO SOLO發表於2021-01-03

Servlet三大核心元件: Servlet , Filter , Listener

1.Servlet
作用:
用來處理客戶端傳送過來的請求,並對改請求作出響應
1. 獲取接收客戶端傳送過來的請求資料
2. 處理請求
3. 將處理的結果通過響應傳送到客戶端

(1).編寫第一個Servlet程式
方式一 .XML對映:

/**
 * 1.繼承HttpServlet
 * 2.重寫doGet和doPost函式
 * 3.在web.xml裡編寫servlet對映
 */
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        System.out.println("Hello Servlet Get請求");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        System.out.println("Hello Servlet Post請求");
    }
}
<?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">
    <servlet>
        <servlet-name>helloServlet</servlet-name><!--對映類的名稱-->
        <servlet-class>com.zx.servlet.HelloServlet</servlet-class><!--對映的類-->
    </servlet>

    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name><!--引用對映類-->
        <url-pattern>/hello</url-pattern> <!--訪問對映名稱 /hello-->
    </servlet-mapping>
</web-app>

方式二.註解對映:

/**
 * 註解名稱
 * 註解對映
 */
@WebServlet(name="HelloServlet",urlPatterns="/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        System.out.println("Hello Servlet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        System.out.println("Hello Servlet");
    }
}

(2).請求(HttpServletRequest/Response)
1.獲取請求行和請求頭

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
    	/** 獲取請求行 */
        request.getMethod();//返回請求方法 get/post/head/delete/put
        request.getRequestURL();//返回URL
        request.getRemoteAddr();//返回客戶端IP地址
        request.getRemotePort();//返回客戶端埠號
        request.getLocalAddr();//獲取伺服器當前接收請求的IP地址
        request.getContextPath();//獲取URL中屬於web應用程式的路徑
        request.getProtocol();//獲取請求行中的協議名和版本
        
        /** 獲取請求頭 */
        Enumeration<String> headName =request.getHeaderNames();
        while(headName.hasMoreElements()){
            System.out.println(request.getHeader(headName.nextElement()));
        }
    }

2.請求 (HttpServletRequest)
獲取請求引數

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        //返回字元型別
        String context_string=request.getParameter("name");
        //返回列舉型別
        Enumeration<String> context_enumeration=request.getParameterNames();
        //返回map型別
        Map<String,String[]> context_map=request.getParameterMap();
    }

3.響應 (HttpServletResponse)
傳送響應行和響應頭

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws IOException{
        //設定狀態碼
        response.setStatus(200);
        //改方法標識傳送錯誤資訊的狀態碼,例如404找不到資源
        response.sendError(404);
        response.sendError(404,"找不到請求的資源");
        //設定Servlet輸出內容的型別 img/jpeg 或者是 text/html;charset=UTF-8 
        response.setContentType("text/html;charset=UTF-8");
    }

4.位元組流和字元流

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException{
      String message="登陸成功";
      
      //位元組流 適用於輸出媒體檔案
      ServletOutputStream out=response.getOutputStream();
      out.write(message.getBytes());
        
      //字元流 適用於輸出網頁文件
      response.setContentType("text/html;charset=UTF-8"); //解決亂碼問題
      PrintWriter writer=response.getWriter();
      writer.write(message);
   }

小案例-驗證碼切換

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException{
        int width=100;
        int height=30;
        String checkCode="ABCDEFGH12345";
        Random random=new Random();
        //建立一張圖片
        BufferedImage img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //獲取img的畫板
        Graphics graphics= img.getGraphics();
        graphics.setColor(Color.gray);
        graphics.fillRect(0,0,width,height);
        //設定驗證碼
        graphics.setColor(Color.black);
        for(int i=0;i<5;i++){
            int randomParam=random.nextInt(checkCode.length());
            String randomStr=checkCode.substring(randomParam,randomParam+1);
            graphics.drawString(randomStr,i*22,18);
        }
        ImageIO.write(img,"jpg",response.getOutputStream());
    }

相關文章