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("失败!!");
}