十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!
10年积累的成都做网站、网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计制作后付款的网站建设流程,更有龙岩免费网站建设让你可以放心的选择与我们合作。本文实例为大家分享了java实现自动登录的具体代码,供大家参考,具体内容如下
package com.learning.web.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 com.learning.domain.User; import com.learning.service.UserService; @WebServlet("/servlet/loginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String autologin = request.getParameter("autologin"); UserService userService=new UserService(); User user = userService.findUser(username, password); //user不为null,则登录成功 if (user!=null) { //创建cookie来保存用户信息 Cookie cookie=new Cookie("user", user.getUsername()+"&"+user.getPassword()); cookie.setPath("/"); //autologin不为null,则记住了登录状态 if (autologin!=null) { cookie.setMaxAge(1*60*60*24);//一天的有效时间 } else { cookie.setMaxAge(0); } response.addCookie(cookie); request.getSession().setAttribute("user", user); request.getRequestDispatcher("/home.jsp").forward(request, response); }else { response.sendRedirect(request.getContextPath()+"/homeLogin.jsp"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }