一:在eclipse新建servlet_Login项目
二:在项目下的 Java Resources里 src下新建Login类 包名为:com.cmp.servlet_Login
三:使Login类继承HttpServlet 并且复写service方法
package com.cmp.servlet_Login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
四:开始在service方法里操作
package com.cmp.servlet_Login;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//设置编码格式 否则中文会乱码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输出
PrintWriter out = response.getWriter();
//接受前端提交的信息
String username = request.getParameter("username");
String password = request.getParameter("password");
//进行判断如果用户名为admin密码为admin88便登录成功
if ("admin".equals(username) && "admin88".equals(password)) {
out.println("<h1>登录成功</h1>");
}else {
out.println("<h1>用户名或密码错误</h1>");
}//否则登录失败
}
}
五:在项目下WebContent/WEB-INF里找到web.xml并进行配置
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.cmp.servlet_Login.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
六:在项目下WebContent里新建Login.html
七:编写一个简单的登录表单
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<h1>登录</h1>
<form action="Login">
<p>账号: <input type="text" name="username" /></p>
<p>密码: <input type="password" name="password" /></p>
<p><button type="submit">登录</button></p>
</form>
</body>
</html>
注意:form的action为在web.xml里配置的<url-pattern>/Login</url-pattern>
去掉斜杠 后台以表单的name属性来获取
八:运行html
当输入admin和admin88时登录成功
输入不是admin和admin88时便会登录失败