servlet的登录练习

1、创建Web项目,部署到tomcat服务器中

 2、在web包创建一个index.jsp包,并添加一个a标签,转跳到登录页面

3、创建一个login.jsp作为登录页面,书写from表单指定提交地址和提交方式

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录页</title>
</head>
<body>
<h2>登录</h2>
<form action="login" method="post">
    账号:<input type="text" name="user" value=""><br/>
    密码:<input type="password" name="pwd" value=""><br/>
    <input type="submit"  value="登录">
</form>
</body>
</html>

 4、在web.xml中配置servlet的映射关系

5、创建一个Java类继承HttpServlet,,并在doPost中获取请求参数

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 Login extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       System.out.println("Login...doGet");
   doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       System.out.println("Login....doPost");

        String requestURI = req.getRequestURI();//项目名称/资源名称
        StringBuffer requestURL = req.getRequestURL();//完整的请求地址
        String contextPath = req.getContextPath();//项目名称
        String servletPath = req.getServletPath();//资源名称

        System.out.println(requestURI);
        System.out.println(requestURL);
        System.out.println(contextPath);
        System.out.println(servletPath);

        //1.获取请求的参数,根据请求参数的name属性获取提交的值

        req.setCharacterEncoding("utf-8");
        String user=req.getParameter("user");
        String pwd = req.getParameter("pwd");
        System.out.println("=========");
        System.out.println(user);
        System.out.println(pwd);

        resp.setCharacterEncoding("utf-8");//设置响应的编码格式
        resp.setContentType("text/html;charset=UTf-8");//设置响应格式为   文本/html;中文编码


        if (user.equals("张三")&&pwd.equals("123")){
            //3.给前端做出响应
            //登录成功
            resp.getWriter().println("<h1>成功<h1>");
        }else{
            //登录失败
            resp.getWriter().println("失败!!");
        }
    }
}

内容格式改变代码 

resp.setCharacterEncoding("utf-8");//设置响应的编码格式
resp.setContentType("text/html;charset=UTf-8");//设置响应格式为   文本/html;中文编码

HttpServlet中的假登录

if (user.equals("张三")&&pwd.equals("123")){
            //3.给前端做出响应
            //登录成功
            resp.getWriter().println("<h1>成功<h1>");
        }else{
            //登录失败
            resp.getWriter().println("失败!!");
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值