我已经使用html
创建了一个登录页面,我在其中输入用户名和密码并显示用户名。我创建了一个servlet
用于显示用户名,在这里我使用request.getParameter(<fieldName>)
来显示用户名。我正在使用Eclipse IDE
和Tomcat
来部署应用程序。由于该方法返回null,因此无法执行此操作。代码如下:
PageLogin.java
/**
* Servlet implementation class PageLogin
*/
@WebServlet("/login")
public class PageLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PageLogin() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
processRequest(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
processRequest(request,response);
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String user = request.getParameter("username");
String pass = request.getParameter("password");
PrintWriter out = response.getWriter();
System.out.println("username : "+user);
System.out.println("password : "+pass);
String htmlResponse = "<html>";
htmlResponse += "<h2>Username : " + user + "</h2>";
htmlResponse +="</html>";
out.println(htmlResponse);
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="PageLogin" method="post" >
Username :<input type="text" name="username"><br>
Password :<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>LoginQ3</display-name>
<servlet>
<servlet-name>loginpage</servlet-name>
<servlet-class>PageLogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginpage</servlet-name>
<url-pattern>/display</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
当我使用网址
我得到的输出为:
用户名:null