用IDEA设计登录页面完成假登录
1.检查web项目是否部署到tomcat服务器
2.在index.jsp首页中添加一个a标签,跳转到登录页面。

注意:ctrl+超链接标签可以跳转到登录页面
3.创建一个login.jsp作为登录页面,书写form表单指定提交地址和提交方式。
注意创建login.jsp


4.在web.xml中配置servlet的映射关系

5.创建一个Java类继承HttpServlet,在doPost中获取请求参数


Requset和Response

从编写Servlet的过程中可以看出,doGet()或者doPost()方法中有两个参数,分别是HttpServletRequest和HttpServletReponse对象中。
- 1.Servlet容器接受到来自客户端的HTTP请求后 ,容器会针对该请求分别创建一个HttpServletRequest对象和HttpServletReponse对象。
- 2.容器将HttpServletRequest和HttpServletResponse对象以参数的形式传入service()(或者doGet()/ doPost())方法内,并调用该方法。
- 3.在service() 或者(doGet()/ doPost())方法中Servlet通过HttpServletRequest对象获取客户端信息以及请求相关信息。
- 4.对HTTP请求进行处理
- 5.请求处理完成后,将响应信息封装到HttpServletReponse对象中。
- 6.Servlet容器将响应信息返回给客户端。
- 7.当servlet容器将响应信息返回给客户端后,HttpServletReponse对象和HttpServletRequest对象被销毁。
通过以上流程可以看出,HttpServletRequest和HttpServletReponse是Servlet处理HTTP请求流程中最重要的两个对象。HttpServletRequest对象用于封装HTTP请求信息,HttpServletReponse对象用于封装HTTP响应信息。
获取请求的参数:根据请求参数的name属性获取提交的值
注意要:为了防止乱码需要加上UTF-8


给前端做出响应

综合案例:
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");
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);
//2.根据输入的用户和密码执行数据库的查询 select * from user where user=? and pwd=?
resp.setCharacterEncoding("utf-8");//设置响应的编码格式
resp.setContentType("text/html;charset=UTF-8");//设置响应的格式为: 文本/html;中文的编码
//3.给前端做出响应
if (user.equals("张三") && pwd.equals("666")){
resp.getWriter().println("成功");//获取响应的输出字符流,向前端打印内容
}else{
resp.getWriter().println("失败");
}
}
}