Java Web Session设置

一、前言

  在做 java web项目时,我们很多时候都要用到 Session,那么我就简单的写一下 Session 的写法。

二、代码实现 Servlet Session 的设置

package com.wz.option;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.wz.dto.AdminDto;
import com.wz.test.AdminCRUD; import net.sf.json.JSONArray; public class loginWZ extends BaseServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取session
HttpSession hs = request.getSession(); request.setCharacterEncoding("utf-8");
String adminNumber = request.getParameter("adminNumber");
String adminPassword = request.getParameter("adminPassword"); AdminCRUD admin = new AdminCRUD();
List<AdminDto> a = admin.getAdmin();
int id = 0;
for (AdminDto dto : a) {
if (dto.getAccoutNumber().equals(adminNumber) && dto.getPassword().equals(adminPassword)) {
          //设置 Session 的值
id = dto.getId();
hs.setAttribute("AdminID", dto.getId());
hs.setAttribute("adminNumber", dto.getAccoutNumber());
hs.setAttribute("adminPassword", dto.getPassword());
hs.setAttribute("realName", dto.getRealName());
break;
}
} if (id != 0) {
request.getRequestDispatcher("Admin/index.jsp").forward(request, response);
} else {
request.getRequestDispatcher("login.jsp").forward(request, response);
} }
}

三、获取 Session

HttpSession hs=request.getSession();
String name=(String)hs.getAttribute("realName");

四、总结

  这就是 Session 的使用,希望以后自己忘记了,就来看看!

上一篇:dynamic关键字


下一篇:Java时间转换类实现