gpt4 book ai didi

java - Out.Print 方法不起作用?

转载 作者:行者123 更新时间:2023-12-01 18:14:19 24 4
gpt4 key购买 nike

这是我的代码

LoginController.java

包 mvc.demo.control;

    import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.demo.model.Authenticate;


public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;

public LoginController()
{
super();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
}
else
{
//This is the point where i try to print error message on jsp.
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.jsp");
rd.include(req, resp);
}
rd.forward(req, resp);
}
}

登录.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form method="post" action="LoginController" >
UserName: <input type="text" name="username"><BR><BR>
PassWord: <input type="password" name="password"><BR><BR>
<input type="submit" />
</form>
</body>
</html>

请检查loginController类的else block ,我试图在我的jsp文件上打印错误消息,当前“out.print”方法无法反射(reflect)在我的login.jsp文件上。请帮我解决这个问题,提前致谢。

最佳答案

您可以在请求属性中设置错误消息,并可以在JSP中获取它

String errorMsg = "UserName or Password is invalid !";
req.setAttribute("errorMsg", errorMsg);
req.getRequestDispatcher("/login.jsp").forward(req, res);

现在在您的 JSP 上

<h2>${errorMsg}</h2>  // Print wherever you need it  

关于java - Out.Print 方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30588879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com