一步一步学习Servlet中Request和Response

在我们的项目开发过程中难免会遇到一些获取前台信息和页面跳转的问题,这里的获取前台信息用提交表单进行演示,Servlet获取内容用getParameter()获取单条信息,getParameterValues()获取多个信息页面跳转用请求转发getRequestDispatcher()和重定向sendRedirect()演示。

首先写一个默认的页面,也就是我们启动了服务器就会进入的页面,也就是index了

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>登录</title>
  </head>
  <body>
  <form action="/login" method="post">
    账号:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    爱好:<br>
    <input type="checkbox" name="hobbies" value="java">java<br>
    <input type="checkbox" name="hobbies" value="C">C<br>
    <input type="checkbox" name="hobbies" value="Linux">Linux<br>
    <input type="submit">
  </form>
  </body>
</html>

然后再写一个成功页面和一个失败页面,成功页面用请求转发跳转,失败页面用重定向跳转

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>成功</h3>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>失败</h3>
</body>
</html>

最后就是我们的Servlet了

package com.zhiying.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取单个信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 获取多个信息
        String[] hobbies = req.getParameterValues("hobbies");
        System.out.println(username);
        System.out.println(password);
        if (hobbies != null) {
            for (String hobby : hobbies) {
                System.out.println(hobby);
            }
            // 请求转发
            req.getRequestDispatcher("/success.jsp").forward(req,resp);
        } else {
            // 重定向
            resp.sendRedirect("/error.jsp");
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

这个是成功的演示,注意网址的变化

这个是失败的演示

发布了376 篇原创文章 · 获赞 242 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/104039388