目录
目的
想让后端作API接口,给我请求,给你数据。后端返回json数据,包括状态码、数据等。SpringMVC不处理jsp视图,改为json视图(关于json视图上一章已提及)。那么页面跳转交由前端ajax处理,jsp页面放到webapp下,不搞WEB-INF。交由控制器的请求让拦截器拦截,前端的jsp请求让过滤器搞定。
一、让内置服务器支持JSP
<!--内置tomcat对Jsp支持的依赖,用于编译Jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- 开启servlet支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
二、拦截器
/**
* 关于登录拦截的配置
*
* @author ZRH
* @version 1.0.0
* @date 2020/9/3
*/
@Configuration
public class LoginConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 建造者模式
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/login").excludePathPatterns("/logout")
.excludePathPatterns("/js/**").excludePathPatterns("/css/**").excludePathPatterns("/img/**");
}
}
三、过滤器
1. 写过滤器
注意@WebFilter是Servlet3.0的,不是SpringBoot的。因为写成SpringBoot的配置类还要写两个类,麻烦。
/**
* 登录过滤器,过滤非法访问需要登录的jsp
*
* @author ZRH
* @version 1.0.0
* @date 2020/9/3
*/
@Slf4j
@WebFilter(urlPatterns = "*.jsp", filterName = "loginFilter")
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse res = (HttpServletResponse) servletResponse;
String path = req.getContextPath();
String indexPath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/pages/login.jsp";
Object loginUser = req.getSession().getAttribute(CommonConstant.LOGIN_EMPLOYEE);
if (!req.getRequestURI().endsWith("login.jsp") && loginUser == null) {
res.sendRedirect(indexPath);
return;
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
2. 在入口类配置
@SpringBootApplication
@MapperScan("com.winrh.mapper")
@ServletComponentScan("com.winrh.filter")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
四、控制器类
封装状态码、数据,返回DTO
@RestController
public class LoginController extends BaseController {
@Autowired
EmployeeService employeeService;
/**
* 登录
* <p>
*
* @param employeeDomain 员工实体类
* @return org.springframework.web.servlet.ModelAndView
* @author ZRH
* @date 2020-08-18
* @version 1.0.0
*/
@PostMapping(value = "/login")
public RestResultDTO<Object> login(@RequestBody EmployeeDomain employeeDomain, HttpSession session) {
return handleMessage(employeeService.checkAccount(employeeDomain, session), session.getAttribute(CommonConstant.LOGIN_EMPLOYEE));
}
/**
* 退出系统
* <p>
*
* @param session
* @return
* @author ZRH
* @date 2020-08-19
* @version 1.0.0
*/
@DeleteMapping(value = "/logout")
public RestResultDTO<Long> logout(HttpSession session) {
session.setAttribute(CommonConstant.LOGIN_EMPLOYEE, null);
return handleMessage(StatusCodeConstant.SUCCESS_STATUS_CODE);
}
}
五、前端
使用Ajax发送接收并跳转
<script type="text/javascript">
function login() {
let account = $("#account").val();
let password = $("#password").val();
let url = "${pageContext.request.contextPath}/login";
let data = {"account": account, "password": password};
console.log(data);
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
data: JSON.stringify(data),
dataType: 'json',
timeout: 3000,
cache: false,
async: true,
success: function (data) {
console.log(data);
alert(data.message);
if(data.data.hasOwnProperty('type')){
let type = data.data.type;
console.log(type);
if(type == 0){
window.location.href="${pageContext.request.contextPath}/pages/admin/index.jsp";
}else if (type == 1){
window.location.href="${pageContext.request.contextPath}/pages/employee/index.jsp";
}
}
}
});
}
</script>