关于请求地址的问题
想通过Ajax来异步校验用户名是否有效,可是好像Ajax的请求路径有问题,又不知道怎么改,求教
function CheckUserIsExist() {
var user = $("#username").val();
console.log(user);
//发送Ajax请求判断用户名是否有效
// 1.创建异步交互对象
var xmlHttp = createXmlHttp();
// 2.设置监听
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var str = xmlHttp.responseText;
//console.log(str);
if( str !== false){
alert("用户名不存在,请重新输入");
}
}
}
// 3.打开连接
xmlHttp.open("POST","self/check.do",true);
// 4.发送
xmlHttp.send("account="+user);
}
这是方法:
public void check(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String account = request.getParameter("account");
System.out.println(account);
int flag = selfService.check(account);
response.setContentType("text/html;charset=UTF-8");
if (flag == 1) {
//用户名存在
response.getWriter().println("true");
} else {
//用户名不存在
response.getWriter().println("false");
}
}
正在回答
你好!关于config的问题,在init(config)的开始添加如下语句super.init(config);
关于ajax的问题,也像下面一样做一个判断,path为self/check.do时就调用filterChain.doFileter()进行放行
祝学习愉快!
给过滤器初始化参数
<filter>
<filter-name>Login</filter-name>
<filter-class>com.imooc.sm.global.LoginFilter</filter-class>
<init-param>
<param-name>Go</param-name>
<param-value>/check.do</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
然后去过滤这个Ajax请求
public class LoginFilter implements Filter {
/**
* 需要排除的请求
*/
private String config;
public void init(FilterConfig filterConfig) throws ServletException {
//获取filter初始化参数
config = filterConfig.getInitParameter("GO");
System.out.println("1" + config);
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
String path = request.getServletPath();
System.out.println("2" + path);
boolean isExcludedPage = false;
if(path.equals(config)){
isExcludedPage = true;
}
if(isExcludedPage){
//是需要过滤的请求
filterChain.doFilter(servletRequest,servletResponse);
}else {
if (path.toLowerCase().indexOf("login") != -1) {
filterChain.doFilter(request, response);
} else {
HttpSession session = request.getSession();
Object obj = session.getAttribute("USER");
if (obj != null) {
filterChain.doFilter(request, response);
} else {
response.sendRedirect(request.getContextPath() + "/toLogin.do");
}
}
}
}
public void destroy() {
}
}
可是获取初始化参数一直为null,老师能帮我看看吗
- 参与学习 人
- 提交作业 205 份
- 解答问题 4317 个
Java中非常实用的SSM整合开发内容,从Spring开始,到MyBaits的进阶内容,再到SpringMVC的应用,最后是SSM整合开发案例,逐步深入,助你成长为一名Java工程师!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星