JavaWeb开发入门(Servlet)2

JavaWeb开发入门(Servlet)2

制作一个简单的验证码

利用Math函数,和BufferedImage,制作一个简答的变化验证码,
package com.kuang.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
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.Map;

//验证码
public class ServletDemo04 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //resp.getWriter().println(newRandom());

        //自动刷新网页
        resp.setHeader("refresh","2");
        //验证码是一个图片 , 我们需要制作一个图片
        BufferedImage image = new BufferedImage(100,30,BufferedImage.TYPE_3BYTE_BGR);

        //图片写入一些东西
        Graphics2D graphics = image.createGraphics();
        graphics.setColor(Color.red);
        String num = String.valueOf(newRandom());
        graphics.drawString(num,10,10);

        //想办法让浏览器知道我们给的是一张图片
        resp.setContentType("image/jpg");

        //让网站去打开图片
        ImageIO.write(image,"jpg",resp.getOutputStream());

    }


    //生成随机数
    public int newRandom(){
        int num = (int)(Math.random()*9+1)*100000;
        return num;
    }

    /*
    @Test
    public void  test(){
        ServletDemo04 servletDemo04 = new ServletDemo04();

        for (int j = 0; j < 100; j++) {
            int i = servletDemo04.newRandom();
            System.out.println(i);
        }
    }
    */



}

Servlet中的Request

JSP获取项目路径,跳转到指定的路径
${pageContext.request.contextPath}/…

request.getContextPath():获得web项目路径
request.getRequestURI():请求获得URI路径
request.getRequestedSessionId():获得sessionId
request.getServletPath():请求servlret的url
request.getLocaclAddr():获得本地地址,防火墙
request.getLocalName();获得本地名字
request.getLocalPort():获得访问的端口号
request.getRemoteUser():获得访问的端口号

Request对象接收前段用户提交的参数

1.写前段注册页面
- 表单的提交方式get/post
- 表单提交的位置action:服务项目的路径/servlet对应的请求url
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/7/14
  Time: 21:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    注册
    



注册

用户名:

密码:

确认密码:

爱好:

说唱 跳舞 篮球 音乐

性别:

写处理前端提交信息的Servlet

- 接收前端传递的控件信息
package com.kuang.servlet;


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

//处理前端提交过来的数据
public class RequestDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //通过HttpServletRequest获取前端用户提交的信息
        //req.getParameterValues(); 获得前端传递的控件信息,通过控件的name;但是可以接受多个参数的控件,比如(多选框....)
        //req.getParameter(); 获得前端传递的控件信息,通过控件的name;

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //连接数据库,比较数据库中的信息是否匹配

        if (username.equals("admin")&&password.equals("1234567")){
            System.out.println("登录成功!"); //跳转到成功页面
        }else {
            System.out.println("登录失败!"); //提示重新注册
        }

        System.out.println(username);
        System.out.println(password);


    }
}

配置web.xml

  • 配置对应的XML文件


    
        ServletDemo1
        com.wang.demo.ServletDemo1
    
    
        ServletDemo2
        com.wang.demo.LoginOutServlet
    
    
    
        ServletDemo1
        /1234
    

    ServletDemo2
    /123.do



4.提交测试

  • 检查英文提交的情况,服务器是否接收成功
  • 提交中文,看看乱码情况
  • 设置编码统一,解决乱码问题

Request实现请求转发

  • 重定向
    • 服务器告诉客户端你应该请求另外一个地址:地址栏汇编
    • response.sendRedirect(“url”);
  • 转发
    • 服务器把这个请求转向另外一个Servlet去处理,地址栏会变,

    • request.getRequestDispacher("/success.jsp").forward(request.response)

      package com.kuang.servlet;
      import javax.servlet.RequestDispatcher;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;
      public class FormServlet1 extends HttpServlet {
      @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      doPost(req,resp);
      }
      @Override
      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //处理乱码
      req.setCharacterEncoding(“UTF-8”);
      //处理前端的请求
      String username = req.getParameter(“username”);
      String password = req.getParameter(“password”);
      System.out.println(“接收到的用户名:”+username+"\n密码:"+password+"\n爱好:");
      String[] hobbies = req.getParameterValues(“hobby”);

         for (String hobby : hobbies) {
             System.out.println(hobby);
         }
         /*
         RequestDispatcher requestDispatcher = req.getRequestDispatcher("/success.jsp");
         requestDispatcher.forward(req,resp);
         */
      
         try {
             Thread.sleep(2000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
      
         req.getRequestDispatcher("/success.jsp").forward(req,resp);
      

      }
      }

转发和重定向的区别

重定向:服务器会告诉客户端,你去请求另外一个地址:客户端行为

  • 地址栏会变
  • 不能携带参数
    转发:服务器自己转到服务器的另一个请求;服务器行为
  • 地址栏不会变
  • 可以携带参数

你可能感兴趣的:(JavaWeb开发入门(Servlet)2)