idea使用过程中request获取不到getParameter方法,session.setAttribute报错

1.request中的方法和session中的方法全部报错?

是因为没有导入jsp-api.jar和servlet-api.jar找到这两个jar包并建立lib文件夹
导入并添加
一般这个情况下request中的方法会回复正常,但是session中的方法还会报错,只要重启idea软件就可以恢复正常了。

// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package com.whir.ezoffice.logon.actionsupport; import com.whir.common.init.DogManager; import com.whir.common.util.CommonUtils; import com.whir.common.util.MD5; import com.whir.component.actionsupport.BaseActionSupport; import com.whir.component.util.LocaleUtils; import com.whir.ezoffice.ldap.LDAP; import com.whir.ezoffice.ldap.MSAD; import com.whir.ezoffice.logon.bd.LogonBD; import com.whir.ezoffice.personalwork.setup.bd.MyInfoBD; import com.whir.ezoffice.security.log.bd.LogBD; import com.whir.integration.realtimemessage.weixin.WeixinUtils; import com.whir.org.basedata.bd.LoginPageSetBD; import com.whir.org.basedata.po.ErrorPasswordPO; import com.whir.org.bd.groupmanager.GroupBD; import com.whir.org.bd.usermanager.UserBD; import com.whir.org.common.util.SysSetupReader; import com.whir.org.sys.bd.SysInterfaceBD; import com.whir.plugins.sys.InterfaceUtils; import java.net.InetAddress; import java.net.URLDecoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import nl.captcha.Captcha; import org.apache.log4j.Logger; public class LogonAction extends BaseActionSupport { private static Logger logger = Logger.getLogger(LogonAction.class.getName()); private static final long serialVersionUID = 1L; private String userAccount; private String userPassword; private String domainAccount; private String reurl; private String restType; private boolean isJson = false; private String captchaAnswer; public String getUserAccount() { return this.userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getUserPassword() { return this.userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getDomainAccount() { return this.domainAccount; } public void setDomainAccount(String domainAccount) { this.domainAccount = domainAccount; } public String getCaptchaAnswer() { return this.captchaAnswer; } public void setCaptchaAnswer(String captchaAnswer) { this.captchaAnswer = captchaAnswer; } private boolean isUseCaptcha(String useCaptcha) { return "1".equals(useCaptcha); } public String login() { return "login"; } public String logon() throws Exception { Date startDate = new Date(); logger.debug("userAccount:" + this.userAccount); logger.debug("domainAccount:" + this.domainAccount); this.isJson = false; if ("json".equals(this.restType)) { this.isJson = true; } String result = "error"; String PORTAL_ERROR = "portalError"; String CONSOLE_ERROR = "console_noright"; boolean isConsoleSubmit = false; if ("Console!init.action".equals(this.reurl)) { if (!"admin".equals(this.userAccount)) { logger.debug("console_noright"); return CONSOLE_ERROR; } isConsoleSubmit = true; } HttpSession session = this.request.getSession(true); logger.debug("captchaAnswer:" + this.captchaAnswer); String useCaptcha = SysSetupReader.getInstance().getSysValueByName("captcha", "0"); if (!isConsoleSubmit && this.isUseCaptcha(useCaptcha)) { if (this.captchaAnswer == null) { this.request.setAttribute("errorType", "captchaWrong"); if (this.isJson) { this.writeResponse2Page("failure", "captchaWrong"); return null; } return result; } Captcha captcha = (Captcha)session.getAttribute("simpleCaptcha"); if (captcha == null) { this.request.setAttribute("errorType", "captchaWrong"); if (this.isJson) { this.writeResponse2Page("failure", "captchaWrong"); return null; } return result; } if (!captcha.getAnswer().equalsIgnoreCase(this.captchaAnswer)) { this.request.setAttribute("errorType", "captchaWrong"); if (this.isJson) { this.writeResponse2Page("failure", "captchaWrong"); return null; } return result; } } session.removeAttribute("userIP"); String userIP = CommonUtils.getIpAddr(this.request); String serverIP = ""; try { serverIP = InetAddress.getLocalHost().getHostAddress(); } catch (Exception ex) { ex.printStackTrace(); } boolean isRtxLoginPage = false; if (this.request.getParameter("RealtimeMsgLogin") != null) { LoginPageSetBD lpsbd = new LoginPageSetBD(); this.userPassword = lpsbd.checkTmpPassword(this.userPassword, this.request.getParameter("RealtimeMsgLogin")); isRtxLoginPage = true; } String _portal_loginUsed = this.request.getParameter("_portal_loginUsed"); if (_portal_loginUsed != null) { result = PORTAL_ERROR; } if ("Console!init.action".equals(this.reurl)) { result = CONSOLE_ERROR; } HashMap userInfo = new HashMap(10, 1.0F); UserBD userBD = new UserBD(); boolean hasDog = false; DogManager dm = DogManager.getInstance(); Integer userNum = userBD.getUserNum(); hasDog = dm.getDogValidate(userNum, "logon"); if (!hasDog) { this.request.setAttribute("errorType", "noDog"); if (this.isJson) { this.writeResponse2Page("failure", "noDog"); return null; } else { return result; } } else { session.setAttribute("userPassword", CommonUtils.encryptPassword(this.userPassword)); LogonBD logonBD = new LogonBD(); int useLDAP = (new LDAP()).getUseLDAP(); int isCheckFlag = (new LDAP()).getIsCheckFlag(); boolean isAdCheckFlag = false; String isAdCheck = userBD.getIsAdCheckByAccount(this.userAccount); if (useLDAP == 1 && isCheckFlag == 1 && isAdCheck.equals("1")) { isAdCheckFlag = true; } if (useLDAP != 0 && !this.userAccount.trim().toLowerCase().equals("admin") && !this.userAccount.trim().toLowerCase().equals("security") && isAdCheckFlag) { if (CommonUtils.isEmpty(this.userPassword)) { logger.debug("密码为空。"); this.request.setAttribute("errorType", "password"); if (this.isJson) { this.writeResponse2Page("failure", "password"); return null; } return result; } LDAP ldap = new MSAD(); String rs = ldap.Authenticate(this.userAccount, this.userPassword); if ("0".equals(rs)) { userInfo = (new LogonBD()).logon(this.userAccount, this.userPassword, userIP, this.domainAccount, "0"); } else { if ("-1".equals(rs)) { this.request.setAttribute("errorType", "user"); if (this.isJson) { this.writeResponse2Page("failure", "user"); return null; } return result; } if ("533".equals(rs)) { logger.debug("LDAP登陆验证,账号被不可用。"); this.request.setAttribute("errorType", "active"); Map umap = userBD.getUserInfoByAccount(this.userAccount); if (umap == null || umap.get("userId") == null) { if (this.isJson) { this.writeResponse2Page("failure", "active"); return null; } else { return result; } } String err_uid = (String)umap.get("userId"); userInfo.put("error", "active"); userInfo.put("userId", err_uid); } else { if ("525".equals(rs)) { logger.debug("LDAP登陆验证,user not found。"); this.request.setAttribute("errorType", "user"); if (this.isJson) { this.writeResponse2Page("failure", "user"); return null; } return result; } if ("773".equals(rs)) { logger.debug("LDAP登陆验证,user must reset password。"); this.request.setAttribute("errorType", "resetpassword"); if (this.isJson) { this.writeResponse2Page("failure", "resetpassword"); return null; } return result; } logger.debug("LDAP登陆验证,密码错误。"); this.request.setAttribute("errorType", "password"); Map umap = userBD.getUserInfoByAccount(this.userAccount); if (umap == null || umap.get("userId") == null) { if (this.isJson) { this.writeResponse2Page("failure", "password"); return null; } return result; } String err_uid = (String)umap.get("userId"); userInfo.put("error", "password"); userInfo.put("userId", err_uid); } } } else { String openId = this.request.getParameter("openId"); if (!CommonUtils.isEmpty(openId)) { String secret = this.request.getParameter("secret"); String newSecret = (new MD5()).toMD5(this.userAccount + openId); if (newSecret.equals(secret)) { userInfo = logonBD.logon(this.userAccount, this.userPassword, userIP, this.domainAccount, "0"); } else { this.reurl = "evo/weixin/login.jsp?openId=" + openId; } } else { if (CommonUtils.isEmpty(this.userPassword)) { logger.debug("非LDAP登陆,密码为空。"); this.request.setAttribute("errorType", "password"); if (this.isJson) { this.writeResponse2Page("failure", "password"); return null; } return result; } if (!"1".equals(this.request.getParameter("pkexit"))) { MD5 md5 = new MD5(); this.userPassword = md5.toMD5(this.userPassword); } String accountscase = SysSetupReader.getInstance().getSysValueByName("accountscase", "0"); userInfo = logonBD.logon(this.userAccount, this.userPassword, userIP, this.domainAccount, "1" + ("0".equals(accountscase) ? "-0" : "")); } } if (userInfo == null) { this.request.setAttribute("errorType", "user"); if (this.isJson) { this.writeResponse2Page("failure", "user"); return null; } else { return result; } } else if (userInfo.get("error") != null) { String errorType = userInfo.get("error").toString(); logger.debug("登录失败:errorType:" + errorType); if ("password".equals(errorType) && this.userAccount != null && !this.userAccount.equals("admin") && !this.userAccount.equals("security")) { int maxErrorNum = logonBD.getPassMaxErrNum("0"); int inputPwdErrorNum = logonBD.getPassErrnum(this.userAccount); ++inputPwdErrorNum; if (inputPwdErrorNum >= maxErrorNum) { String[] ids = new String[1]; ids[0] = userInfo.get("userId").toString(); userBD.sleepUser(ids, "连续输入密码错误"); errorType = "sleep"; ErrorPasswordPO epo = new ErrorPasswordPO(); epo.setErrorNum(0); epo.setUserAccount(this.userAccount); epo.setLoginIp(userIP); logonBD.updatePassErrnum(epo); } else if (inputPwdErrorNum > 0 && inputPwdErrorNum < maxErrorNum) { ErrorPasswordPO epo = new ErrorPasswordPO(); epo.setErrorNum(inputPwdErrorNum); epo.setUserAccount(this.userAccount); epo.setLoginIp(userIP); logonBD.updatePassErrnum(epo); } logger.debug("inputPwdErrorNum:" + inputPwdErrorNum); logger.debug("maxErrorNum:" + maxErrorNum); this.request.setAttribute("inputPwdErrorNum", String.valueOf(inputPwdErrorNum)); this.request.setAttribute("inputPwdErrorNumMax", String.valueOf(maxErrorNum)); } Map umap = userBD.getUserInfoByAccount(this.userAccount); if (umap != null) { String err_uid = (String)umap.get("userId"); if (err_uid != null) { LogBD bd = new LogBD(); bd.log((String)umap.get("userId"), (String)umap.get("userName"), (String)umap.get("orgName"), "oa_index", "登录", startDate, new Date(), "0", "登录失败", userIP, (String)umap.get("domainId")); } } this.request.setAttribute("errorType", errorType); if (this.isJson) { this.writeResponse2Page("failure", errorType); return null; } else { return result; } } else { if (userInfo.get("userName") != null) { session.setAttribute("keySerial", !CommonUtils.isEmpty(userInfo.get("keySerial")) ? "" + userInfo.get("keySerial") : null); session.setAttribute("domainId", userInfo.get("domainId")); if (userInfo.get("userAccount") != null) { session.setAttribute("userName", "系统管理员"); session.setAttribute("orgName", ""); session.setAttribute("orgId", "0"); session.setAttribute("orgIdString", ""); session.setAttribute("browseRange", "0"); String sysAcc = userInfo.get("userAccount").toString(); if (sysAcc.equals("admin")) { session.setAttribute("userId", "0"); session.setAttribute("userAccount", "admin"); } else if (sysAcc.equals("security")) { session.setAttribute("userId", userInfo.get("userId")); session.setAttribute("userAccount", "security"); } session.setAttribute("sysManager", "1"); session.setAttribute("skin", !CommonUtils.isEmpty(userInfo.get("skin")) ? "" + userInfo.get("skin") : "2013/blue"); session.setAttribute("rootCorpId", "0"); session.setAttribute("corpId", "0"); session.setAttribute("departId", "0"); session.setAttribute("orgEnglishName", !CommonUtils.isEmpty(userInfo.get("orgEnglishName")) ? "" + userInfo.get("orgEnglishName") : ""); session.setAttribute("empNumber", !CommonUtils.isEmpty(userInfo.get("empNumber")) ? "" + userInfo.get("empNumber") : ""); session.setAttribute("empBusinessPhone", !CommonUtils.isEmpty(userInfo.get("empBusinessPhone")) ? "" + userInfo.get("empBusinessPhone") : ""); session.setAttribute("orgSelfName", !CommonUtils.isEmpty(userInfo.get("orgSelfName")) ? "" + userInfo.get("orgSelfName") : ""); String empIdCard = userInfo.get("empIdCard") != null ? "" + userInfo.get("empIdCard") : ""; session.setAttribute("empIdCard", empIdCard); MyInfoBD myInfoBD = new MyInfoBD(); String userPageSize = myInfoBD.loadUserPageSize("0"); session.setAttribute("userPageSize", !CommonUtils.isEmpty(userPageSize) ? userPageSize : "15"); session.setAttribute("userIdentityNo", empIdCard); } else { session.setAttribute("userName", userInfo.get("userName")); session.setAttribute("userId", userInfo.get("userId")); session.setAttribute("orgName", userInfo.get("orgName")); session.setAttribute("orgId", userInfo.get("orgId")); session.setAttribute("orgIdString", userInfo.get("orgIdString")); session.setAttribute("skin", !CommonUtils.isEmpty(userInfo.get("skin")) ? "" + userInfo.get("skin") : "2013/blue"); session.setAttribute("rootCorpId", userInfo.get("rootCorpId")); session.setAttribute("corpId", userInfo.get("corpId")); session.setAttribute("departId", userInfo.get("departId")); session.setAttribute("orgEnglishName", !CommonUtils.isEmpty(userInfo.get("orgEnglishName")) ? "" + userInfo.get("orgEnglishName") : ""); session.setAttribute("empNumber", !CommonUtils.isEmpty(userInfo.get("empNumber")) ? "" + userInfo.get("empNumber") : ""); session.setAttribute("empBusinessPhone", !CommonUtils.isEmpty(userInfo.get("empBusinessPhone")) ? "" + userInfo.get("empBusinessPhone") : ""); session.setAttribute("orgSelfName", !CommonUtils.isEmpty(userInfo.get("orgSelfName")) ? "" + userInfo.get("orgSelfName") : ""); String empIdCard = userInfo.get("empIdCard") != null ? "" + userInfo.get("empIdCard") : ""; session.setAttribute("empIdCard", empIdCard); session.setAttribute("userIdentityNo", empIdCard); session.setAttribute("browseRange", !CommonUtils.isEmpty(userInfo.get("browseRange")) ? "" + userInfo.get("browseRange") : "0"); session.setAttribute("userAccount", this.userAccount); session.setAttribute("sysManager", userInfo.get("sysManager")); session.setAttribute("userSimpleName", !CommonUtils.isEmpty(userInfo.get("userSimpleName")) ? "" + userInfo.get("userSimpleName") : ""); session.setAttribute("orgSerial", !CommonUtils.isEmpty(userInfo.get("orgSerial")) ? "" + userInfo.get("orgSerial") : ""); session.setAttribute("orgSimpleName", !CommonUtils.isEmpty(userInfo.get("orgSimpleName")) ? "" + userInfo.get("orgSimpleName") : ""); session.setAttribute("dutyName", !CommonUtils.isEmpty(userInfo.get("dutyName")) ? "" + userInfo.get("dutyName") : ""); session.setAttribute("dutyLevel", !CommonUtils.isEmpty(userInfo.get("dutyLevel")) ? "" + userInfo.get("dutyLevel") : "0"); session.setAttribute("imID", !CommonUtils.isEmpty(userInfo.get("imID")) ? "" + userInfo.get("imID") : "0"); String curuserId = "" + session.getAttribute("userId"); if (!CommonUtils.isEmpty(curuserId)) { String isPasswordRule = userBD.getUserIsPasswordRule(curuserId); String isInitPassword = userBD.getUserIsInitPassword(curuserId); if (isInitPassword.equals("1") && isPasswordRule.equals("1")) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String currentDateStr = sdf.format(new Date()); String latestModPasswordDateStr = userBD.getLatestModiPasswordDate(curuserId); long subTime = 0L; try { long currentDateTime = sdf.parse(currentDateStr).getTime(); long latestModPwdTime = sdf.parse(latestModPasswordDateStr).getTime(); subTime = currentDateTime - latestModPwdTime; long subDays = subTime / 86400000L; if (subDays > 76L) { long subMsgDay = 90L - subDays; if (subMsgDay <= 0L) { this.request.setAttribute("errorType", "forbidUser"); String[] ids = new String[]{curuserId}; userBD.sleepUser(ids, "密码到期"); return result; } this.request.setAttribute("modifyPwdMsg", "modifyPwd"); this.request.setAttribute("subMsgDay", String.valueOf(subMsgDay)); } } catch (ParseException var42) { } } } MyInfoBD myInfoBD = new MyInfoBD(); String userPageSize = myInfoBD.loadUserPageSize("" + userInfo.get("userId")); session.setAttribute("userPageSize", !CommonUtils.isEmpty(userPageSize) ? userPageSize : "15"); } session.setAttribute("hasLoged", (Object)null); String userId = session.getAttribute("userId").toString(); String domainId = session.getAttribute("domainId") != null ? session.getAttribute("domainId").toString() : "0"; session.setAttribute("serverIP", serverIP); if (!isRtxLoginPage) { session.setAttribute("userIP", userIP); } session.setAttribute("empEnglishName", !CommonUtils.isEmpty(userInfo.get("empEnglishName")) ? "" + userInfo.get("empEnglishName") : ""); session.setAttribute("empPosition", !CommonUtils.isEmpty(userInfo.get("empPosition")) ? "" + userInfo.get("empPosition") : ""); session.setAttribute("ownerGroupIdStr", (new GroupBD()).getOwnerGroupIdStrByUserId(userId)); MyInfoBD myInfoBD = new MyInfoBD(); myInfoBD.updateUserLatestLogonTime(userId); try { SysInterfaceBD sibd = new SysInterfaceBD(); String[] interfaceInfos = sibd.getInterfaceInfo("com.whir.plugins.sys.impl.LoginImpl", "execute", "0", domainId); if (interfaceInfos != null) { Class[] paramsType = new Class[]{String.class, String.class, HttpServletRequest.class}; Object[] paramsValue = new Object[]{userId, session.getAttribute("orgId").toString(), this.request}; (new InterfaceUtils()).execute(interfaceInfos, paramsType, paramsValue, "0"); } } catch (Exception e) { System.out.println("--调用登录接口出错--"); e.printStackTrace(); } String _portal_goUrl = this.request.getParameter("_portal_goUrl"); String _portal_flag = this.request.getParameter("_portal_flag"); session.setAttribute("_portal_flag", _portal_flag); if ("1".equals(_portal_loginUsed)) { String localeCode = this.request.getParameter("localeCode"); LocaleUtils.setLocale(localeCode, this.request); this.request.getRequestDispatcher(_portal_goUrl).forward(this.request, this.response); return null; } result = "success"; ErrorPasswordPO epo = new ErrorPasswordPO(); epo.setErrorNum(0); epo.setUserAccount(this.userAccount); epo.setLoginIp(userIP); logonBD.updatePassErrnum(epo); if (this.isJson) { this.writeResponse2Page("success", "success"); return null; } } else { this.request.setAttribute("errorType", "user"); if (this.isJson) { this.writeResponse2Page("failure", "user"); return null; } } logger.debug("reurl:" + this.reurl); if (!CommonUtils.isEmpty(this.reurl)) { this.reurl = URLDecoder.decode(this.reurl, "utf-8"); logger.debug("decode reurl:" + this.reurl); if ("Console!init.action".equals(this.reurl)) { logger.debug("checking userAccount"); if ("admin".equals(this.userAccount)) { logger.debug("Dispatcher reurl:" + this.reurl); this.response.sendRedirect(this.reurl); return null; } else { return "console_noright"; } } else { this.request.getRequestDispatcher(this.reurl).forward(this.request, this.response); return null; } } else { return result; } } } } public String getJsonData() throws Exception { String json = ""; String userAccount = ""; userAccount = WeixinUtils.getUserAccountByWeixinId(this.request.getParameter("openId")); json = "{\"userAccount\":\"" + userAccount + "\"}"; this.printJsonResult(json); return null; } private void writeResponse2Page(String result, String errorType) { if ("success".equals(result)) { this.printJsonResult("{\"result\":\"" + result + "\"}"); } else { this.printJsonResult("{\"result\":\"" + result + "\",\"errorType\":\"" + errorType + "\"}"); } } public String getReurl() { return this.reurl; } public void setReurl(String reurl) { this.reurl = reurl; } public String getRestType() { return this.restType; } public void setRestType(String restType) { this.restType = restType; } } 哪里是解密
08-21
package cn.itcast.session.entity; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } package cn.itcast.session.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.itcast.session.entity.User; @WebServlet(name = "IndexServlet", urlPatterns = "/IndexServlet") public class IndexServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); // 解决乱码问题 // 获取保存有用户信息的Session对象 HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { response.getWriter().print("<a href='/chapter05/login.html'>登录</a>"); } else { response.getWriter().print("您已登录,欢迎你," + user.getUsername() + "!"); response.getWriter().print("<a href='/chapter05/LogoutServlet'>退出</a>"); // 创建Cookie,存放Session的标识 Cookie cookie = new Cookie("JSESSIONID", session.getId()); cookie.setMaxAge(60 * 30); cookie.setPath("/chapter05"); response.addCookie(cookie); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } package cn.itcast.session.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.itcast.session.entity.User; @WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet") public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); PrintWriter pw = response.getWriter(); // 假设正确的用户名是itcast,密码是123 if ("itcast".equals(username) && "123".equals(password)) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpSession session = request.getSession(); session.setAttribute("user", user); response.sendRedirect("/chapter05/IndexServlet"); } else { pw.write("用户名或密码错误,登录失败"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } package cn.itcast.session.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet(name = "LogoutServlet", urlPatterns = "/LogoutServlet") public class LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 将Session对象的User对象移除 request.getSession().removeAttribute("user"); response.sendRedirect("/chapter05/IndexServlet"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Type" content="text/html"> <title>登录</title> </head> <body> <form name="reg" action="http://localhost:8080/webcast/LoginServlet" method="post"> 用户:<input name="username" type="text"/><br/> 密码:<input name="password" type="password"/><br/> <input type="submit" value="提交" /><br/> </form> </body> </html> 改写代码,要在jdk21,tomcat10,idea2023的版本中创建
11-06
package cn.itcast.session.entity; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } package cn.itcast.session.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.itcast.session.entity.User; @WebServlet(name = “IndexServlet”, urlPatterns = “/IndexServlet”) public class IndexServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); // 解决乱码问题 // 获取保存有用户信息的Session对象 HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { response.getWriter().print("<a href='/chapter05/login.html'>登录</a>"); } else { response.getWriter().print("您已登录,欢迎你," + user.getUsername() + "!"); response.getWriter().print("<a href='/chapter05/LogoutServlet'>退出</a>"); // 创建Cookie,存放Session的标识 Cookie cookie = new Cookie("JSESSIONID", session.getId()); cookie.setMaxAge(60 * 30); cookie.setPath("/chapter05"); response.addCookie(cookie); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } package cn.itcast.session.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.itcast.session.entity.User; @WebServlet(name = “LoginServlet”, urlPatterns = “/LoginServlet”) public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); PrintWriter pw = response.getWriter(); // 假设正确的用户名是itcast,密码是123 if ("itcast".equals(username) && "123".equals(password)) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpSession session = request.getSession(); session.setAttribute("user", user); response.sendRedirect("/chapter05/IndexServlet"); } else { pw.write("用户名或密码错误,登录失败"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } package cn.itcast.session.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet(name = “LogoutServlet”, urlPatterns = “/LogoutServlet”) public class LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 将Session对象的User对象移除 request.getSession().removeAttribute("user"); response.sendRedirect("/chapter05/IndexServlet"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Type" content="text/html"> <title>登录</title> </head> <body> <form name="reg" action="http://localhost:8080/webcast/LoginServlet" method="post"> 用户:<input name="username" type="text"/><br/> 密码:<input name="password" type="password"/><br/> <input type="submit" value="提交" /><br/> </form> </body> </html> 改写代码,要在jdk21,tomcat10.1,idea2023的版本中创建
最新发布
11-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值