我来分享一下我之做的SpringMVC项目的一个小bug。
制作一个系统一定会需要有登录页面和注测页面的
在注测页面的时候,不能出现用户名重复的问题 ,所以我使用了 jquery来进行前后端连接,判断用户名是否存在。
可以看到我的代码使用 jquery 的ajax 传值的,当用户失去对输入用户名框的焦点就会传值。
<script >
$(function () {
// alert(1);
$("#username").blur(function (){//失去焦点事件
// alert(2);
//获得文本框值
var username = $(this).val();
// alert(username);
$.ajax({
url:"${pageContext.request.contextPath}/isExistedName",
//
data:{"username":username},
type:"POST",
async:false,
dataTypes:'json',
success:function (msg){
// alert(msg);
//判断
if(!msg.state){
alert("用户名已经存在");
}else{
alert(msg.state);
}
},
error:function (){
alert("用户名可以使用")
}
})
})
});
</script>
之前不管怎么试错都无法将数据的值传给后台的Controller层。
后来才发现 ,被我自己写的拦截器给拦截了。哭了哭了
制作登录界面的时候是一定要写拦截器的,不然别人使用时可能就会直接跳转到系统页面,而忽略登录。
这个是我写登录页面的拦截器
package com.tencent.interceptor;
import com.tencent.pojo.Admin;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class PrivilegeInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断用户是否登录成功
HttpSession session = request.getSession();
//获取保存在域中的数据
Admin admin = (Admin) session.getAttribute("admin");
if (admin == null){
//用户没有登录过,不能直接访问,跳转到登录页面
response.sendRedirect(request.getContextPath()+"/login.jsp");
return false;
}
return true;
}
}
拦截器是在 spring-mvc.xml中配置的
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mv="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--mvc注释驱动-->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 静态资源的释放 -->
<mvc:default-servlet-handler/>
<!-- 开启包的扫描 -->
<context:component-scan base-package="com.tencent.controller"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/login"/>
//这个就是控制注测页面的 , 不让拦截器拦截注测页面
<mvc:exclude-mapping path="/isExistedName"/>
<bean class="com.tencent.interceptor.PrivilegeInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- 默认servlet -->
<mvc:default-servlet-handler/>
</beans>
可以看到我在拦截器中设置的了不拦截注测页面 ,设置完之后就不会再被拦截了。
希望出现和我用相同问题的xdm,可以借鉴一下。