CheckServlet.java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/check")
public class CheckServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("gbk");
response.setCharacterEncoding("gbk");
String name=request.getParameter("name11");
String password=request.getParameter("password11");
if("admin".equals(name)&&"123".equals(password)) {
HttpSession session=request.getSession();
session.setAttribute("info",name);
request.getRequestDispatcher("welcome").forward(request, response);
}else {
request.getRequestDispatcher("index.html").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
WelcomeServlet.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.jasper.tagplugins.jstl.core.Out;
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("gbk");
response.setCharacterEncoding("gbk");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("</head>");
out.print("<body>");
HttpSession session=request.getSession();
String info=(String)session.getAttribute("info");
if(info==null) {
request.getRequestDispatcher("index.html").forward(request, response);
}else {
out.print("<h1>welcome</h1>");
out.print("<h1>欢迎你来到青岛职业技术学院</h1>");
}
out.print("</body>");
out.print("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="gbk">
<title>Insert title here</title>
</head>
<body>
<font size="5">
<form action="check" method="post">
用户名:<input type="text" name="name11"/><br>
密码:<input type="text" name="password11"/><br>
<input type="submit" value="登录"><input type="reset" value="重置"><br>
</form>
</font>
</body>
</html>
这是文件的位置
- 添加到tomcat服务器上
- 运行服务器
- 在浏览器上输入http://127.0.0.1:8080/demo1104/index.html