1,新建类 WebSecurityConfig
package com.yuiyu.project2.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截登录
InterceptorRegistration addInterceptor = registry.addInterceptor(new LoginAdminInterceptor());
//不拦截的配置
addInterceptor.excludePathPatterns("/login.html");
addInterceptor.excludePathPatterns("/user/existusername");
addInterceptor.excludePathPatterns("/user/login");
//拦截的配置
addInterceptor.addPathPatterns("/*.html");
addInterceptor.addPathPatterns("/user/*");
addInterceptor.addPathPatterns("/**");
}
}
2,新建类
package com.yuiyu.project2.configuration;
import com.sd.gather.pojo.Account;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 拦截必须是管理员才能操作账号管理
*/
public class LoginAdminInterceptor implements HandlerInterceptor {
//判断session的值
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
Account account = (Account) request.getSession().getAttribute("account");
if (account == null) {
try {
//跳出iframe
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<script>");
out.println("window.open ('" + request.getContextPath() + "/login.html','_top')");
out.println("</script>");
out.println("</html>");
} catch (IOException e) {
e.printStackTrace();
}
return false;
} else {
//判断是不是管理员
if (account.getType() == 2) {
if (request.getRequestURL().equals("/user/*") || request.getRequestURL().equals("userIndex.html")) {
try {
response.sendRedirect("/login.html");
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
}
return true;
}
}