zoukankan      html  css  js  c++  java
  • 在请求中存取属性

    一、在请求中保存属性

    public void setAttribute(String name, Object o){}
    
    request.setAttribute("message","信息内容"); // 这里是String类型

    二、在请求中获取属性

    public Object getAttribute(String name){}
    Object o
    = request.getAttribute("message"); if(o!=null){ // 判断是否为空,防止空指针 String str = o.toString(); // 类型转换 //其他操作 }

    代码示例:

    用户在userLogin.jsp页面输入账号密码跳转doLogin.jsp页面进行注册,账号="YeHuan"转发到登录失败界面loginFaile.jsp页面,提示用户已存在,其他情况下重定向注册成功界面index,jsp。

    userLogin.jsp

    <body>
    <form id="dataForm" name="dataForm" action="doLogin.jsp" method="get">
    用户名:<input type="text" name="username" value=""/>
    密码:<input type="password" name="password" value=""/>
    <input type="submit" name="save" value="提交"/>
    </form>
    </body>

    doLogin.jsp

    <body>
    <%
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    if(username.equals("YeHuan")){
        // 转发
        request.setAttribute("message", "账号已存在");
        request.getRequestDispatcher("loginFaile.jsp").forward(request, response);
    }else{
        // 重定向
        request.setAttribute("message", "注册成功");
        response.sendRedirect("../index.jsp");
    }
     %>
    </body>

    备注:路径格式说明

    / 根目录(项目名所在那级目录)

    ./ 当前目录

    ../ 上级目录

    loginFaile.jsp

    <body>
    <%
    Object o = request.getAttribute("message");
    if(o!=null){
    out.print(o.toString());
    }
    %>
    </body>

    index.jsp

      <body>
        This is my JSP page! 你好<br>
        <%
        Object o = request.getAttribute("message");
        if(o!=null){
            out.print(o.toString()+" 你好");
        }
        %>
      </body>

    运行结果:注册成功没有提示信息,原因是使用重定向跳转,会重新发出请求;注册失败有提示信息,原因是使用转发跳转,会携带上次的请求。

    相关知识点:转发与重定向

  • 相关阅读:
    对宏的另外一些认识 及 assert.h的实现细节
    不要想太多
    线段树
    SQL基础 利用SELECT检索数据
    hidden表单值无法重置的缺陷
    oracle 数据库登陆
    基于ejb3,对JDBC进行封装,让使用JDBC时能像hibernate使用annotation注解一样简便,而且更加轻巧
    GoJS的一些使用技巧
    GoJS的学习使用
    灵活使用trim方法
  • 原文地址:https://www.cnblogs.com/YeHuan/p/10876447.html
Copyright © 2011-2022 走看看