JSP Session. Getattribute () method: get the attribute value according to the attribute name
•
Java
getAttribute(String name)
Example
<% session.getAttribute("user"); %>
Typical application
<form name="form1" method="post" action=""> 用户名:<input name="name" type="text" id="name" style="width:120px"><br> 密&nbsp;&nbsp;码:<input name="pwd" type="password" id="pwd" style="width:120px"><br> <br> <input type=" submit" name="Submit" value="提交"> </form>
<%@page language="java" contentType="text/html;charset=GB18030" pageEncoding="GB18030"%> <%@page import = "java.util.*"%> <% String[][] userList = {{"mr","mrsoft"},{"wgh","111"},{"sk","111"}}; //定义一个保存用户列表的二维数组 boolean flag = false; //登录状态 request.setCharacterEncoding("GB18030"); //设置编码 String username = request.getParameter("username"); //获取用户名 String pwd = request.getParameter("pwd"); //获取密码 for(int i=0;i<userList.length;i++){ //遍历二维数组 if(userList[i][0].equals(username)){ //判断用户名 if(userList[i][1].equals(pwd)){ //判断密码 flag = true; //表示登录成功 break; //跳出for循环 } } } if(flag){ //如果值为true,表示登录成功 session.setAttribute("username",username); //保存用户名到session范围的变量 response.sendRedirect("main.jsp"); //跳转到主页 }else{ response.sendRedirect("index.jsp"); //跳转到用户登录页面 } %>
<%@page language="java" contentType="text/html;charset=GB18030"pageEncoding="GB18030"%> <% String username = (String)session.getAttribute("username"); //获取保存在session范围内的用户名 %> <html> <head> <Meta http-equiv="Content-Type" content="text/html;charset=GB18030"> <title>系统主页</title> </head> <body> 您好![<%=username%>]欢迎您访问!<br> <a href="https://www.jb51.ccexit.jsp">[退出]</a> </body> </html> 编写 exit.jsp 文件,在该文件中销毁 session,并重定向页面到 index.jsp 页面。exit.jsp 文件的具体代码如下: <%@page language="java" contentType="text/html;charset=GB18030" pageEncoding="GB18030"%> <% session.invalidate(); //销毁session response.sendRedirect("index.jsp"); //重定向页面到index.jsp %>
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码