**loginServlet.java**
package com.anil.apps;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String uid=request.getParameter("userid");
String password=request.getParameter("pwd");
if(uid.equals("Anil")&&password.equals("missinlx")){
//out.println("welcome "+uid);
response.sendRedirect("welcomeUser?userid="+uid);
}
else{
out.println("invalid username or password");
}
}
}
**WelcomeUserServlet.java**
package com.anil.apps;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("<html><body><h1>Welcome " +uid+ "</h1></body></html>");
}
}
我的代码出了什么问题?我想使用response.sendRedirect()方法将页面重定向到welcomeUser.java页面。 因为我是servlet的新手,请帮助我。请告诉我Servlet中页面重定向的完整格式。
答案 0 :(得分:0)
GET
参数不会自动转入变量。您需要将其添加到doGet
:
WelcomeUserServlet
方法的顶部
String uid = request.getParameter("userId");
使该课程看起来像这样:
public class WelcomeUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uid = request.getParameter("userId");
PrintWriter out=response.getWriter();
out.println("<html><body><h1>Welcome " +uid+ "</h1></body></html>");
}
}
答案 1 :(得分:-1)
您对sendRedirect方法使用了错误的参数
你应该使用像
这样的完整路径response.sendRedirect("some/path/here/to/"+welcomeUser?userid="+uid)
或更好
response.sendRedirect(response.encodeURL(response.getContextPath()+"welcomeUser?userid="+uid))
或者使用知道项目结构且不需要完整路径的请求调度程序
request.getRequestDispatcher("welcomeUser?userid="+uid).forward(request,response)