//index.jsp
<body>
<font color="red">
<%
if(request.getAttribute("err")!=null){
out.println(request.getAttribute("err"));
}
%>
</font>
输入用户 名和密码:
<form id="login" method="post" action="login" οnsubmit="return check(this);">
user:<input type="text" name="username"/><br/>
password:<input type="password" name="userpwd"/><br/>
<input type="submit" value="login"/><br/>
</form>
</body>
LoginServlet.class
public class LoginServlet extends HttpServlet{
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
RequestDispatcher rd;
String username=req.getParameter("username");
String pass=req.getParameter("userpwd");
String errMsg="";
if(username==null||username.equals("")){
errMsg+="lose username";
}else if(pass==null|| pass.equals("")){
errMsg+="lose password";
}
else{
rd=req.getRequestDispatcher("/welcome.jsp");
rd.forward(req, res);
return;
}
if(errMsg!=null && !errMsg.equals("")){
rd=req.getRequestDispatcher("/login.jsp");
req.setAttribute("err", errMsg);
rd.forward(req, res);
return;
}
}
}
web.xml的配置
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>hello.yaohuiye.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
布置在tomcat上,启动后运行 localhost:8080/LoginTest/index.jsp
![](https://img-my.csdn.net/uploads/201211/26/1353932189_5171.jpg)
输入用户名,密码后,点击login
发生如下错误的时候
"java.lang.IllegalStateException: Cannot forward after response has been committed “
原因在于
当你有多个跳转的页面的语句时候,好好检查一下,当 转发 或者 重定向的时候,需要在后加一个retrun 即可。
else{
rd=req.getRequestDispatcher("/welcome.jsp");
rd.forward(req, res);
return;
}
if(errMsg!=null && !errMsg.equals("")){
rd=req.getRequestDispatcher("/login.jsp");
req.setAttribute("err", errMsg);
rd.forward(req, res);
return;
}
服务器中不允许多次跳转,否则 会发生这个错误。
因为服务器端使用sendRedirect跳转到客户端的时候,不能在使用req.getRequestDispatcher("跳转的页面").forward(req, reqs);
跳转;所以在跳转之后,return就不会往下执行。