在请求中存取属性

一、在请求中保存属性

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>

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

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

原文地址:https://www.cnblogs.com/YeHuan/p/10876447.html