这是一个servlet代码,其功能只是一个查询本地数据库中的信息。
问题:在我测试其功能中,当我输入数据库中存在的数据,可以正确查询;当我故意查找不存在的数据,弹出"用户不存在后",我再次查找存在的数据,然后没有反应了,一直转圈圈
会不会是servlet重定向导致了阻塞还是因为什么
package com.exam.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.exam.bean.User;
import com.exam.dao.UserDao;
import com.exam.dao.impl.UserDaoImpl;
import com.exam.service.UserService;
@WebServlet(urlPatterns = "/searchUser")
public class searchUserServlet extends HttpServlet {
private ApplicationContext applicationContext;
@Override
public void init() throws ServletException {
try {
applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
} catch (Exception e) {
e.printStackTrace();
throw new ServletException("无法加载ApplicationContext", e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//不写这句就会乱码
request.setCharacterEncoding("utf-8");
UserService userService = (UserService) applicationContext.getBean("userService");
// 获取表单数据
String userName = request.getParameter("userId");
// 在这里可以将用户信息存储到数据库或进行其他操作
//增加到数据库
UserDao user = new UserDaoImpl();
System.out.println(userName);
System.out.println(request.getCharacterEncoding());
try {
if(user.selectUserByName(userName)!=null) {
System.out.println("查询成功");
request.setAttribute("user", user.selectUserByName(userName));
request.getRequestDispatcher("searchshow.jsp").forward(request, response);
}else {
System.out.println("用户不存在");
// 设置响应的字符集和内容类型
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// 弹出JavaScript的alert提示框
String alertMessage = "用户不存在!";
PrintWriter out = response.getWriter();
out.println("<script type=\"text/javascript\">");
out.println("alert('" + alertMessage + "');");
out.println("window.location='searchUserForm.jsp';"); // 重定向到成功页面
out.println("</script>");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 进行重定向或其他操作
//response.sendRedirect("index.jsp");
}
}
<body>
<h1>查询用户</h1>
<form action="searchUser" method="post" accept-charset="UTF-8">
<label for="userName">名字:</label>
<input type="text" id="userId" name="userId" required>
<input type="submit" value="查询">
</form>
<p style="text-align: center; margin-top: 20px;">
<a href="index.jsp">返回主界面</a>
</p>
</body>