1.创建web项目,部署到tomcat服务器中
2.在index.jisp首页中添加一个a标签,跳转到登录页面
3.创建一个login.jsp作为登录页面,书写form表单指定提交地址和提交方式
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");
//request用来处理请求 response用来处理响应
//获取请求地址的四个方法
String reqURI = req.getRequestURI(); //项目名称/资源名称
StringBuffer reqURL = req.getRequestURL(); //完整的请求地址
String contextPath = req.getContextPath(); //项目名称
String servletPath = req.getServletPath(); //资源名称
//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);
//2.根据输入的用户名和密码执行数据库的查询 select * from user where user=? and pwd=?
resp.setCharacterEncoding("utf-8"); //设置响应的编码格式
resp.setContentType("text/html;charset=UTF-8"); //设置响应的格式为: 文本/html;中文编码
if(user.equals("张三")&&pwd.equals("666")){
//3.给前端做出响应
//登陆成功
resp.getWriter().println("<h2>成功!</h2>"); //获取响应的输出字符流,向前端打印内容
}else {
//登录失败
resp.getWriter().println("失败!");
}
}
}
正确输入运行后
错误输入运行后