Servlet 基本使用
一、创建一个项目的步骤
①login.jsp代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<form action="myTest" method="post">
<input name="username">
<input name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
②index.jsp代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<%
if (session.getAttribute("username")==null) {
response.sendRedirect("login.jsp");
}
%>
<%=session.getAttribute("username")%>---->>欢迎您登录
</body>
</html>
③创建一个LoginServlet的java文件
LoginServlet代码如下:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "123456".equals(password)) {
request.getSession().setAttribute("username",username);
response.sendRedirect("index.jsp");
}
else{
response.sendRedirect("login.jsp");
}
}
}
二、相关的资源参数配置
①Tomcat资源配置
②Servlet 的配置包含在 web.xml文件中,主要通过以下两步进行设置。
三、运行的测试阶段
①加载Tomcat服务
②密码不正确的情况下
③账号密码都正确的情况下