下面是登录页面:
index.html
<div class="container " >
<h2 align="center" >Account Login</h2><br>
<form action="servlet1" method="post">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" class="form-control" name="userName" placeholder="Username">
</div> <br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" class="form-control" name="userPass" placeholder="Password">
</div>
<div class="form-group">
<br>
<span id="spanbut"><input type="submit" value="Login" class="btn btn-primary" /> </span>
</div>
</form>
</div>
下面是检查用户名和密码是否匹配的servlet。用户名和密码是硬编码的。如果它们匹配,则导航到欢迎页面。
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/servlet1")
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String[][] arr = new String [4][4];
arr[0][0] = "ABC";
arr[0][1] = "Password123";
arr[1][0] = "XYZ";
arr[1][1] = "servlet";
arr[2][0] = "PQR";
arr[2][1] = "Outlook123";
arr[3][0] = "TUV";
arr[3][1] = "Hello123";
boolean flag=false;
for (int i = 0; i < arr.length; i++)
{
if(n.equals(arr[i][0]))
{
if(p.equals(arr[i][1]))
{
RequestDispatcher rd=request.getRequestDispatcher("/servlet2");
rd.forward(request, response);
flag =true;
}
}
}
if(flag==false)
{
//out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("incorrect.html");
rd.include(request, response);
}
}}
我必须通过html将用户名值获取到欢迎页面。 以下是被称为欢迎页面的servlet。 我需要一个servlet吗?
WelcomeServlet.java
@WebServlet("/servlet2")
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
答案 0 :(得分:0)
您可以使用 request.getAttribute() 和 request.setAttribute() 来获取username
。如下所示:
if(n.equals(arr[i][0]))
{
if(p.equals(arr[i][1]))
{
//get username if password and username matched
String username1=a[i][0];
//set username1 in request
request.setAttribute("username", username1);
RequestDispatcher rd=request.getRequestDispatcher("/servlet2");
rd.forward(request, response);
flag =true;
}
}
然后在您的WelcomeServlet
中执行以下操作:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value got from Login servlet
String n=(String)request.getAttribute("username");
out.print("Welcome "+n);
}