JavaWeb

JavaWeb-010-HttpServlet详解

2017-11-12  本文已影响25人  53b3f4658edc
微信公众号:JavaWeb架构师

概述

微信公众号:JavaWeb架构师

优点

测试代码

LoginServlet.java

package com.mac;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    //根据请求的方式重写doXxx(res,req)方法
    //已经强转成对应的HTTP请求和响应了,可以使用更多的方法
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html;charset=UTF-8");
        PrintWriter out = res.getWriter();

        //1.获取ServletContext对应的全局初始化参数(在web.xml中)
        ServletConfig sco = this.getServletConfig();
        System.out.println(sco);
        ServletContext sc = sco.getServletContext();
        String user = sc.getInitParameter("user");
        String password = sc.getInitParameter("password");
        
        //2.获取用户的HTML输入
        String inputUser = req.getParameter("user");
        String inputPassword = req.getParameter("password");
        
        //3.进行用户名和账号的验证
        if( user.equals(inputUser) && password.equals(inputPassword) ) {
            out.println("登录成功!");
        } else {
            out.println("用户名或密码有误!请检查后重试!!!");
        }
    }
}

效果

微信公众号:JavaWeb架构师


其它


关注下方公众号,回复:javaweb_course.code
完整教程PDF版本下载
上一篇下一篇

猜你喜欢

热点阅读