---------------siwuxie095
登录实例:
从 login.jsp 提交登录信息到 LoginServlet,在 LoginServlet 中打印登录信息
工程结构目录如下:
LoginServlet.java:
package com.siwuxie095.servlet;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
// LoginServlet继承自 HttpServlet public class LoginServletextends HttpServlet { /** *用于序列化和反序列化的 ID */ private static finallong serialVersionUID = -7740192486028671728L;
/** *先覆盖父类 HttpServlet的service()方法, *右键->Source->Override/Implement methods *选择 HttpServlet的 service() *在 service()中编写业务处理逻辑 */ @Override protectedvoid service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String userName=req.getParameter("uname"); String password=req.getParameter("upwd"); System.out.println("用户名:"+userName); System.out.println("密码:"+password); }
} |
login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"> <title>登录页面</title> </head> <body>
<!--添加表单,url在部署描述符中进行配置,使用post方式来提交 --> <formaction="<%= request.getContextPath() %>/loginServlet"method="post"> userName:<inputtype="text"name="uname"/><br/> password:<inputtype="password"name="upwd"/><br/><br/> <inputtype="submit"value="Login"/> <inputtype="reset"value="Reset"/> </form>
</body> </html> |
在部署描述符web.xml 中注册 servlet:
<?xmlversion="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/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1"> <display-name>MyServlet</display-name> <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>
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.siwuxie095.servlet.LoginServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>LoginServlet</servlet-name> <!-- url-pattern即在 form 表单中录入的 action的值 --> <url-pattern>/loginServlet</url-pattern> </servlet-mapping>
</web-app> |
部署描述符web.xml 在 WEB-INF 目录下,如果没有,手动创建即可
选择工程 MyServlet,右键->Java EE Tools->Generate Deployment Descriptor Stub
注意:login.jsp 的 form 表单的 action 属性需要加上 JSP 表达式:
<%= request.getContextPath() %>,用来获取应用的上下文路径
否则,访问localhost:8080/MyServlet/login.jsp,点击Login 后,
会跳转到错误的URL:localhost:8080/loginServlet
显示:HTTP Status 404 和 the requested resource is not available
即缺少了应用的上下文路径
正确的URL:localhost:8080/MyServlet/loginServlet
【made by siwuxie095】