자바 웹 에 서 는 쿠키 를 사용 하여 사용자 의 계 정과 비밀 번 호 를 기억 합 니 다.
먼저 로그 인 한 페이지 입 니 다.사용자 가 비밀 번 호 를 기억 하고 contrller(제 가 사용 하 는 SSM 프레임 워 크)에 전달 하고 배경 에 쿠키 의 값 을 설정 한 다음 에 로그 인 할 때 계 정과 비밀 번 호 를 다시 입력 하지 않 아 도 됩 니 다.
login.jsp 코드:
<%@page import="org.apache.commons.lang.StringUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="public/nocache.jsp" %>
<%@include file="public/header.jsp" %>
<!-- js -->
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<style>
body{
margin:0px;
padding:0px;
}
.wrapper{
width:100%;height:100%;position:fixed;
}
.content{
width:100%;
height:100%;
position:relative;
text-align:center;
}
.login{
width:1050px;
height:450px;
position:absolute;
top:50%;
left:50%;
margin-top:-225px;
margin-left:-525px;
}
</style>
<script type="text/javascript">
window.history.forward();
window.onbeforeunload=function (){
}
</script>
<%@include file="public/headertop.jsp" %>
<!-- -->
<body>
<%-- cookie --%>
<%
String name = "";
String password = "";
try{
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for(int i = 0;i<cookies.length;i++){
if(cookies[i].getName().equals("cookie_user")){
String values = cookies[i].getValue();
// value
if(StringUtils.isNotBlank(values)){
String[] elements = values.split("-");
//
if(StringUtils.isNotBlank(elements[0])){
name = elements[0];
}
if(StringUtils.isNotBlank(elements[1])){
password = elements[1];
}
}
}
}
}
}catch(Exception e){
}
%>
<div class="wrapper" style="">
<div class="content">
<div class="login">
<!-- -->
<div class="easyui-layout" fit="true" border="false">
<div region="west" style="width:550px;text-align:center;" border="false">
<div class="easyui-layout" fit="true" border="false">
<div region="west" border="false" style="width:250px;height:390px;background:url(${pageContext.request.contextPath}/img/banner-jkrzbg.png)">
</div>
<div region="center" style="font-family:' ';" border="false">
<p style="position: relative;margin-top:200px;padding-left:20px;">
<span style="font-size:30px;font-weight:800;"> </span><br/>
<span>Vehicle Maintenance Management System</span>
</p>
</div>
</div>
</div>
<div region="center" border="false" style="width:520px;height:480px;">
<div class="easyui-layout" fit="true" border="false">
<div region="north" style="height:80px;" border="false">
</div>
<div region="west" style="width:90px;position: relative;" border="false">
<img src="${pageContext.request.contextPath}/img/split.png" style="position:absolute;left:0px;top:30px;"/>
</div>
<div region="center" border="false">
<div class="easyui-panel" title=" " iconCls="icon-user"
style="text-align: center;width:300px;height:260px;padding-top:50px;">
<form id="ff" method="post">
<div>
<input id="account" class="easyui-textbox" name="accountnumber"
data-options="iconCls:'icon-man',prompt:' '" value="<%=name %>"
style="width:240px;height:30px;">
<a id="dd" href="#" title=" " class="easyui-tooltip"></a>
</div>
<div style="margin-top: 20px;">
<input id="passwords" class="easyui-textbox" name="passwords" type="password"
data-options="iconCls:'icon-lock',prompt:' '" value="<%=password %>"
style="width:240px;height:30px;">
</div>
<div style="margin-top: 10px;" style="text-align:left;" >
<span style="float:left;padding-left:30px;font-size:12px;"><input id="flag" name="flag" type="checkbox" value="1" checked="checked" /> </span>
</div>
<div style="clear:both;"></div>
<div style="margin-top: 20px;">
<p>
<a href="#" id="submitbtn" style="width:80px;height:30px;" class="easyui-linkbutton" iconCls="icon-accept"> </a>
<a style="margin-left:30px;width:80px;height:30px;" href="#" class="easyui-linkbutton" iconCls="icon-arrow_undo"> </a>
</p>
</div>
</form>
</div>
</div>
<div region="east" style="width:90px;" border="false">
</div>
<div region="south" style="height:0px;" border="false">
</div>
</div>
</div>
</div>
<!-- -->
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
console.log("[
codeby:pengchan
email:[email protected]
csdn:http://blog.csdn.net/w3chhhhhh/]");
//
$("#submitbtn").click(function(){
//
if($("#account").val()==""){
$.messager.alert(' ',' ','info');
return;
}
if($("#passwords").val()==""){
$.messager.alert(' ',' ','info');
return;
}
$("#ff").submit();
});
$('#ff').form({
url:"${pageContext.request.contextPath}/users/login.html",
success:function(data){
data = JSON.parse(data);
try{
if(data.isError){
$.messager.alert(' ',data.errorMsg,'info');
}else{
//$.messager.alert(" "," !",'info');
// ,
// ,
var hisurl = '${hisURL}';
if(hisurl!=null&&hisurl.length>0){
window.location.href="${pageContext.request.contextPath}"+hisurl;
}else{
window.location.href="${pageContext.request.contextPath}/index/main.html";
}
}
}catch(e){
$.messager.alert(" ",' , !','info');
}
},
error:function(error){
$("#ff").form("clear");
}
});
});
</script>
</body>
</html>
배경 처리 자바 부분 코드:
package com.javaweb.controller;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.javaweb.entity.Account;
import com.javaweb.service.impl.ServiceFactory;
import com.javaweb.utils.BaseController;
import com.javaweb.views.LoginBean;
/**
*
* @author cp
*
*/
@Controller
@Scope("prototype")
@RequestMapping("/users")
public class UserInfoController extends BaseController{
private static final Logger logger = LoggerFactory.getLogger(UserInfoController.class);
@Autowired
private ServiceFactory serviceFactory;
/**
*
* @param request
* @param model model
* @param account
* @return
*/
@RequestMapping("/login")
@ResponseBody
public String login(HttpServletRequest request,HttpServletResponse response,Model model,Account account){
logger.info(" :"+JSON.toJSONString(account));
if(account==null){
return responseFail(" !");
}else{
if(StringUtils.isBlank(account.getAccountnumber())){
return responseFail(" ");
}
if(StringUtils.isBlank(account.getPasswords())){
return responseFail(" ");
}
LoginBean loginBean = null;
loginBean = serviceFactory.getUserValidateService().userislawable(account);
if(loginBean==null){
return responseFail(" ");
}else{//
// loginbean session
request.getSession().setAttribute("user", loginBean);
// cookie
String flag = request.getParameter("flag");
//
if(flag!=null&&flag.equals("1")){
Cookie cookie = new Cookie("cookie_user",loginBean.getAccountnumber()+"-"+loginBean.getPasswords());
cookie.setMaxAge(60*60*24*3);//
response.addCookie(cookie);
logger.info(" cookie:"+loginBean.getAccountnumber()+"-"+loginBean.getPasswords());
}else{// ,
Cookie cookie = new Cookie("cookie_user", loginBean.getAccountnumber());
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
logger.info(" cookie:"+loginBean.getAccountnumber());
}
//
logger.info(" :"+loginBean.getAccountnumber()+" ");
return responseSuccess(loginBean, " ");
}
}
}
/**
*
* @param request
* @param model
* @param accountnum
* @return
*/
@RequestMapping("/{accountnum}/logout.html")
public String logout(HttpServletRequest request,Model model,@PathVariable("accountnum") String accountnum){
logger.info(" "+accountnum+", ...");
// session
request.getSession().setAttribute("user", null);
//
return "login";
}
}
실행 효과:계 정 비밀 번 호 를 입력 하여 로그 인 후:
종료 후 다시 로그 인:
위 에서 말 한 것 은 소 편 이 소개 한 자바 웹 에서 쿠키 를 사용 하여 사용자 의 계 정과 비밀 번 호 를 기억 하 는 것 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.소 편 은 제때에 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Javaweb에서 양식 데이터를 가져오는 다양한 방법Javaweb에서 양식 데이터를 가져오는 몇 가지 방법 1. 키 값이 맞는 형식으로 폼 데이터를 얻는다 getParameter(String name): 키를 통해 value를 반환합니다. getParameterVal...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.