(1)Servlet 编译环境:JDK8+Tomcat,编译方法将项目打成 war 包,放到 Tomcat 的 webapp 目录下,然后启动 Tomcat,打开浏览器访问 localhost:8080/login3.jsp
(2)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>用户登录</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style>
#login {
width: 400px;
}
h3 {
text-align: center;
}
#btn {
text-align: center;
}
</style>
</head>
<body>
<div class="container" id="login">
<h3>用户登录</h3>
<form action="${pageContext.request.contextPath}/login3_do" method="post">
<div class="form-group">
<label for="admin">用户名:</label>
<input type="text" name="name" class="form-control" id="admin" placeholder="请输入用户名"/>
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/>
</div>
<hr/>
<div class="form-group" id="btn">
<input class="btn btn-primary" type="submit" value="登录">
<input class="btn btn-default" type="reset" value="重置" />
</div>
</form>
</div>
</body>
</html>
(3)
public class Login3_do extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取用户信息
String name = request.getParameter("name");
String password = request.getParameter("password");
// 3.返回给用户
request.setAttribute("name", name);
request.setAttribute("password", password);
// 4.跳转首面
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
this.doPost(request, response);
}
}
(4)
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置 Servlet-->
<servlet>
<!--给 Servlet 起一个名字,一般和类名一致-->
<servlet-name>Login3_do</servlet-name>
<!--配置这个 Servlet 的全类名-->
<servlet-class>com.zt.web.servlet.Login3_do/servlet-class>
</servlet>
<!--配置 Servlet 的映射路径-->
<servlet-mapping>
<servlet-name>Login3_do</servlet-name>
<!--外界能访问到 Servlet 的资源路径-->
<url-pattern>/login3_do</url-pattern>
</servlet-mapping>
</web-app>