1.获取请求部分的信息方法:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应的内容为html,指定编码为utf-8
response.setContentType("text/html;charset=utf-8");
//获取打印流
PrintWriter out = response.getWriter();
//输出到浏览器端
out.print("你好,Servlet <br/>");
//接口的好处:降低tomcat和我们servlet之间的耦合度,以后还可以使用别的web服务器
out.print("请求对象:" + request + "<hr/>");
out.print("<h1>请求行</h1>");
out.print("获取请求方式:" + request.getMethod() + "<br/>"); //GET或POST
out.print("获取当前模块的访问地址:" + request.getContextPath() + "<br/>"); // day27_02_request_war_exploded
out.print("获取完整的URL:" + request.getRequestURL() + "<br/>"); // http://localhost:8888/day27_02_request_war_exploded/Demo1Servlet
out.print("获取URI:" + request.getRequestURI() + "<br/>"); // /day27_02_request_war_exploded/Demo1Servlet
//访问地址:http://localhost:8888/day27_02_request_war_exploded/Demo1Servlet?name=NewBoy&password=123
out.print("查询字符串(?后面的参数):" + request.getQueryString() + "<br/>"); //name=NewBoy&password=123
//out.write()和out.print()区别,是一样的,没有什么区别。print方法重载更多,使用更方便。 print底层调用的就是write方法
out.print("<h1>请求头</h1>");
//由键和值组成,通过键获取值。
out.print("获取user-agent请求头:" + request.getHeader("user-agent") + "<br/>");
out.print("<h1>请求体</h1>");
out.print("GET没有请求体<br/>");
out.print("POST方法获取数据:<br/>");
//1.得到字符输入流
BufferedReader br = request.getReader();
//2.从输入流中读取数据
String line = br.readLine();
out.print(line);
}
2.通过request.getParameterMap()直接获取所有参数的map对象
public class Demo2ParamServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//GET请求汉字没有乱码问题,POST请求会有乱码问题,解决方法:在获取参数前设置请求的编码
request.setCharacterEncoding("utf-8");
//方式一:获取所有的参数,封装成Map
//1.获取表单所有的参数,封装成Map,键是String,值是String[]数组
Map<String, String[]> parameterMap = request.getParameterMap();
//2.输出所有的参数名和值
parameterMap.forEach((key,value) -> System.out.println("参数名:" + key + ",参数值:" + Arrays.toString(value)));
//方式二:通过名字获取一个值,参数名是表单项的名字
String city = request.getParameter("city");
System.out.println("获取一个参数:" + city);
//方式三:通过名字获取一组值,获取字符串的数组
String[] hobbies = request.getParameterValues("hobby");
System.out.println("获取一组值:" + Arrays.toString(hobbies));
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
3.修改idea自带的模板代码:
在设置里找到File and Code Templates
在Other里可以找到Servlet Class的模板
4.设置跳转:
public class Demo3ServletA extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("访问资源A");
//转发:在服务器端进行页面跳转
//将数据放在请求作用域中
request.setAttribute("key", "钥匙");
//前面部分获取转发器,指定要跳转到的地址,再调用forward方法转发,传递请求和响应对象
//request.getRequestDispatcher("b").forward(request, response);
//重定向: 1) 设置状态码为302 2)指定要跳转的地址,设置响应头location
//response.setStatus(302);
//response.setHeader("location","b");
//因为以上2个方法常用,所以也专门设置了重定向的方法
response.sendRedirect("b");
//跳转到其它任意的服务器
//response.sendRedirect("http://www.itheima.com");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
@WebServlet("/b") //要跳转到的地址
public class Demo4ServletB extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("访问资源B");
//1.设置响应内容和编码
response.setContentType("text/html;charset=utf8");
//2.获取字符流
PrintWriter out = response.getWriter();
//3.输出
out.println("<h1>资源B</h1>");
//4.从请求域中获取数据
out.println(request.getAttribute("key"));
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
5.设置响应头
@WebServlet("/Demo5HeaderServlet")
public class Demo5HeaderServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置一个响应头:设置响应的类型
//response.setHeader("content-type","text/html;charset=utf-8");
//因为这个响应头用得很多,所以专门设置了一个方法。如果没有这句,浏览器端汉字会乱码
//MIME类型:通过类型指定打开资源的方式,格式:大类型/小类型;其它参数
response.setContentType("text/html;charset=utf-8");
//获取打印字符流
PrintWriter out = response.getWriter();
//输出到浏览器
out.print("你好,积极响应!");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
6.输入输出流:
resources里的文件在编译的时候会被打包到类文件夹下
@WebServlet("/Demo6PictureServlet")
public class Demo6PictureServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//0.设置响应类型MIME为图片类型
response.setContentType("image/jpeg");
//1.读取图片文件,得到字节输入流 (通过类对象读取根目录下文件)
//getClass()类对象的getResourceAsStream方法:默认是在当前类所在的包去读取文件
//getClassLoader()类加载器的getResourceAsStream方法:默认是在类路径的根目录下读取文件
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("404a.jpg");
//2.获取响应对象的字节输出流
ServletOutputStream outputStream = response.getOutputStream();
//3.将输入流复制到输出流中
IOUtils.copy(inputStream, outputStream);
//4.关闭输入输出流
inputStream.close();
outputStream.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
7.设置断点debug:
在idea的列号和对应代码之间,点击空白即可看到设置红色的断点
然后在运行的时候选择虫子模样的debug图标
之后可以在idea里通过调试器一步步看程序里变量的变化
8.在pom.xml里导入mybaits和mysql的坐标
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
9.利用mybatis+servlet编写登录和注册请求
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//汉字乱码
request.setCharacterEncoding("utf-8");
//1.接收用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.调用Mapper查询,返回User对象
//2.1 调用工具类得到会话对象
SqlSession sqlSession = MyBatisUtils.getSession();
//2.2 由会话对象得到UserMapper的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//2.3 调用接口中方法查询
User user = userMapper.select(username, password);
//2.4 关闭会话
sqlSession.close();
//打印到浏览器上
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//3.判断User对象是否为null
if (user == null) {
//为null:登录失败
out.print("登录失败,<a href='login.html'>请重试</a>");
}
else {
//不为null:登录成功
out.print("欢迎您! " + username);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//如果注册有汉字,考虑汉字乱码的问题
request.setCharacterEncoding("utf-8");
//1.获取用户名和密码 ctrl+d 复制一行
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.判断用户名是否存在
SqlSession sqlSession = MyBatisUtils.getSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//通过用户名查找用户
User user = userMapper.selectByUsername(username);
//模板代码:rout
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//3.如果存在,提示:注册失败 快捷键:inn 和 ifn
if (user != null) {
out.print("用户名:" + username + ",已经存在,<a href='register.html'>请重试</a>");
}
//4.否则就添加用户,提示:注册成功
else {
//创建一个用户对象
user = new User();
//封装属性
user.setUsername(username);
user.setPassword(password);
userMapper.add(user);
//注:添加要提交事务
sqlSession.commit();
//输出注册成功
out.println("注册成功,<a href='login.html'>请登录</a>");
}
//关闭会话
sqlSession.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}