1.创建web项目,部署到tomcat服务器中
2.在index.isp首页中添加一个a标签,跳转到登录页面
3.创建一个ogin.jisp作为登录页面, 书写form表单指定提交地址和提交方式
4.在web.xml中配置servlet的映射关系
5.创建一个ava类继承HttpServlet,在doPost中获取请求参数
一.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>喜羊羊与灰太狼</title>
</head>
<body>
<h2>欢迎来到动画世界</h2>
<a href="login.jsp">去登陆</a>
</body>
</html>
二.
<%@ 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>
三.
<?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>
<!--起别名-->
<servlet-name>login</servlet-name>
<!--servlet类所在位置:类的全类名就是 包名.类名-->
<servlet-class>com.chen.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
四.五
package com.chen.servlet;
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");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求的参数:根据请求的name属性获取提交值
System.out.println("Login...doPost");
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);
//2.根据输入的用户名和密码执行数据库的查询 select*from user where user=? and pwd=?(程序的业务处理)
resp.setCharacterEncoding("utf-8");//设置响应的编码格式
resp.setContentType("text/html;charset=utf-8");
if (user.equals("张三")&&pwd.equals("666")){
//3.给前端做出响应
//登陆成功
resp.getWriter().println("<h2>成功</h2>");//获取响应的输出字符流,像前端打印内容
}else{
//登录失败
resp.getWriter().println("失败");
}
}
}