Servlet Request获取数据及转发小案例

2019-10-26  本文已影响0人  JayMeWangGL

在杭州不太方便,只好写一写前些天学的方法巩固一下,案例包括获取获取网页中输入的数据,数据共享与转发。

转发

请求转发:一种在服务器内部的资源跳转方式

  1. 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)
  2. 使用RequestDispatcher对象来进行转发:forward(ServletRequest request, ServletResponse response)

资源共享及获取

  1. void setAttribute(String name,Object obj):存储数据
  2. Object getAttribute(String name):通过键获取值
  3. void removeAttribute(String name):通过键移除键值对

HTML5一个用表格写的简陋注册页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="/DemoServlet" method="post">
    用户名<input type="text" name="username" placeholder="请输入用户名" ><br>
    密码<input type="password" name="password" placeholder="请输入密码"><br>
    爱好<input type="checkbox" name="hobby" value="study">学习<br>
    <input type="submit" value="提交" >
</form>
</body>
</html>
效果图

第一个Servlet


@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String username = request.getParameter("username");
//        System.out.println(username);
        request.setCharacterEncoding("utf-8");//设置编码格式以防止中文乱码
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            System.out.println(name+"->"+value);
            request.setAttribute(name,value);//数据存储以便在转发后可访问到数据
        }
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/DemoServlet2");//转发数据
        requestDispatcher.forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

转发Servlet

@WebServlet("/DemoServlet2")
public class DemoServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String username = request.getParameter("username");
//        System.out.println(username);
        request.setCharacterEncoding("utf-8");
        System.out.println("----转发----");
        Object username = request.getAttribute("username");
        Object password = request.getAttribute("password");
        Object hobby = request.getAttribute("hobby");
        System.out.println(username+" "+password+" "+hobby);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

数据测试及效果

注意:如果获取CheckBox 最好选用Map<String,String[]> getParameterMap()方法
其他方法会无法获取全部的值

上一篇下一篇

猜你喜欢

热点阅读