1. 程式人生 > >SSM實現登陸登出

SSM實現登陸登出

第一步:

 

在springmvc.xml配置檔案裡面配置一個攔截器的配置

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*/**"/>
            <mvc:exclude-mapping path="/static/**"/>  
            <bean class="com.lpy.interceptor.LoginInterceptor">
               <property name="unCheckUrls"> 
                  <list> 
					<value>/users/login.action</value>
                  </list> 
              </property> 
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

表示攔截所有路徑,除了靜態資源的路徑

配置了一個攔截器LoginInterceptor,/users/login.action表示不進行攔截

第二步:

書寫一個攔截器的類 並實現 HandlerInterceptor

package com.imooc.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

	private List<String> unCheckUrls;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		String requestUrl = request.getRequestURI();
		requestUrl=requestUrl.replaceAll(request.getContextPath(), "");
		// 判斷是否針對匿名路徑需要攔截,如果包含,則表示匿名路徑,需要攔截,否則通過攔截器
		if (unCheckUrls.contains(requestUrl)){
			// 包含公開url,直接跳過
			return true;
		}
		
		if(null == request.getSession().getAttribute("sessionUser")){
			response.sendRedirect(request.getContextPath()+"/users/login.action"); 
			
			return false;
		}
		
		// 放行
		return true;
	}
	
	
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}

	public List<String> getUnCheckUrls() {
		return unCheckUrls;
	}

	public void setUnCheckUrls(List<String> unCheckUrls) {
		this.unCheckUrls = unCheckUrls;
	}

}

第三步:書寫usersController 

package com.imooc.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.imooc.bean.AdminUser;
import com.imooc.pojo.Users;
import com.imooc.service.UsersService;
import com.imooc.utils.IMoocJSONResult;
import com.imooc.utils.PagedResult;

@Controller
@RequestMapping("users")
public class UsersController {
	
	@Autowired
	private UsersService usersService;
	
	@GetMapping("/showList")
	public String showList() {
		return "users/usersList";
	}
	
	@PostMapping("/list")
	@ResponseBody
	public PagedResult list(Users user , Integer page) {
		
		PagedResult result = usersService.queryUsers(user, page == null ? 1 : page, 10);
		return result;
	}
	

	@GetMapping("/login")
	public String login() {
		return "login";
	}
	
	@PostMapping("login")
	@ResponseBody
	public IMoocJSONResult userLogin(String username, String password,
			HttpServletRequest request, HttpServletResponse response) {
		
		// TODO 模擬登陸
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return IMoocJSONResult.errorMap("使用者名稱和密碼不能為空");
		} else if (username.equals("lee") && password.equals("lee")) {
			
			String token = UUID.randomUUID().toString();
			AdminUser user = new AdminUser(username, password, token);
			request.getSession().setAttribute("sessionUser", user);
			return IMoocJSONResult.ok();
		}
		
		return IMoocJSONResult.errorMsg("登陸失敗,請重試...");
	}
	
	@GetMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute("sessionUser");
		return "login";
	}
	
}

 

書寫UsersController涉及到2個幫助類

第一個:獲取的資料封裝後返回前端的

package com.imooc.utils;

/**
 * @Description: 自定義響應資料結構
 * 				這個類是提供給門戶,ios,安卓,微信商城用的
 * 				門戶接受此類資料後需要使用本類的方法轉換成對於的資料型別格式(類,或者list)
 * 				其他自行處理
 * 				200:表示成功
 * 				500:表示錯誤,錯誤資訊在msg欄位中
 * 				501:bean驗證錯誤,不管多少個錯誤都以map形式返回
 * 				502:攔截器攔截到使用者token出錯
 * 				555:異常丟擲資訊
 */
public class IMoocJSONResult {

    // 響應業務狀態
    private Integer status;

    // 響應訊息
    private String msg;

    // 響應中的資料
    private Object data;
    
    private String ok;	// 不使用

    public static IMoocJSONResult build(Integer status, String msg, Object data) {
        return new IMoocJSONResult(status, msg, data);
    }

    public static IMoocJSONResult ok(Object data) {
        return new IMoocJSONResult(data);
    }

    public static IMoocJSONResult ok() {
        return new IMoocJSONResult(null);
    }
    
    public static IMoocJSONResult errorMsg(String msg) {
        return new IMoocJSONResult(500, msg, null);
    }
    
    public static IMoocJSONResult errorMap(Object data) {
        return new IMoocJSONResult(501, "error", data);
    }
    
    public static IMoocJSONResult errorTokenMsg(String msg) {
        return new IMoocJSONResult(502, msg, null);
    }
    
    public static IMoocJSONResult errorException(String msg) {
        return new IMoocJSONResult(555, msg, null);
    }

    public IMoocJSONResult() {

    }

    public IMoocJSONResult(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public IMoocJSONResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOK() {
        return this.status == 200;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

	public String getOk() {
		return ok;
	}

	public void setOk(String ok) {
		this.ok = ok;
	}

}

 

第二個:分頁的幫助類

package com.lpy.utils;

import java.util.List;

/**
 * @Description: 封裝分頁後的資料格式
 */
public class PagedResult {
	
	private int page;			// 當前頁數
	private int total;			// 總頁數	
	private long records;		// 總記錄數
	private List<?> rows;		// 每行顯示的內容
	
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public long getRecords() {
		return records;
	}
	public void setRecords(long records) {
		this.records = records;
	}
	public List<?> getRows() {
		return rows;
	}
	public void setRows(List<?> rows) {
		this.rows = rows;
	}

}