1. 程式人生 > >自動登錄代碼

自動登錄代碼

login xtend package request patch ont pri print 代碼

package cn.lijun.web;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
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.lijun.domain.User1;
import cn.lijun.service.UserService;

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
HttpSession se = request.getSession();

//接受數據
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService ser = new UserService();
User1 user=null;
try {
user= ser.login(username,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(user!=null){
//登錄塵成功 判斷是否勾選
String autoLogin = request.getParameter("autoLogin");
if(autoLogin!=null){
Cookie cookie_username= new Cookie("cookie_username", user.getUsername());
Cookie cookie_password= new Cookie("cookie_password", password);
//設置cookie持續化時間
cookie_username.setMaxAge(60*60*100);
cookie_password.setMaxAge(60*60*100);
// 設置路徑
cookie_username.setPath(request.getContextPath());
cookie_password.setPath(request.getContextPath());
//發送cookie
response.addCookie(cookie_username);
response.addCookie(cookie_password);
}
//將登錄的用戶存儲到session域中
se.setAttribute("user", user);
//重定向 地址欄發生變化
response.sendRedirect(request.getContextPath());
}else{
request.setAttribute("loginInfo", "用戶名或者密碼錯誤");
//轉發 地址欄不變
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

自動登錄代碼