session 用户名 java_Session保存用户名到Session域对象中

Session保存用户名

1.构造登录界面

用户名:

密   码:

Session保存用户名

用户名:

密   码:

2.获取Session并将用户名保存到Session域对象中

package com.oaec.session;

import java.io.IOException;

import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class servletDemo3 extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

req.setCharacterEncoding("UTF-8");

resp.setContentType("text/html;charset=UTF-8");

// req.getAttribute(arg0)

String name = req.getParameter("name");

String pwd = req.getParameter("pwd");

if ("高圆圆".equals(name) && "123".equals(pwd)) {

// 将用户名保存在session中

// 1.获得session

HttpSession session = req.getSession();

// 2.将用户名保存在session中

session.setAttribute("uname", name);

resp.sendRedirect("doS4");

} else {

resp.sendRedirect("index.html");

}

}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGet(req, resp);

}

}

3.从Session中取出数据  并对页面进行保护  没有登录通过URL访问 直接重定向到登录界面  即主页

package com.oaec.session;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class servletDemo4 extends HttpServlet{

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

req.setCharacterEncoding("UTF-8");

resp.setContentType("text/html;charset=UTF-8");

//从session中取出数据

HttpSession session = req.getSession(false);

Object object = null;

if (session != null && (object = session.getAttribute("uname"))!=null) {

PrintWriter writer = resp.getWriter();

writer.write("登录成功
");

writer.write("欢迎你"+object);

}else {

//没有登录过 直接重定向到主页

resp.sendRedirect("index.html");

}

}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGet(req, resp);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>