设计一个提交网页
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/zzz/my" method="post">
<input type="text" name="username"/>
<input type="text" name="pwd"/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
编写一个类继承HttpServlet,重写service方法
package com.zhm;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class MyServlet extends HttpServlet{
int count=1;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");//处理post请求乱码
resp.setContentType("text/html; charset=UTF-8");
String username = req.getParameter("username");
String pwd = req.getParameter("pwd");
if(username!=null && pwd!=null) {
if("张三".equals(username) && "123456".equals(pwd)) {
//登录成功
HttpSession session=req.getSession();
session.setAttribute("username", username);
//this.getServletContext();
ServletContext context = req.getServletContext();
if(context.getAttribute("count")==null) {
context.setAttribute("count",1);
}else {
context.setAttribute("count", (Integer)context.getAttribute("count")+1);
}
resp.sendRedirect("/zzz/main.jsp");
}else {
//登陆失败
resp.getWriter().print("登陆失败");
}
}
}
}
编写一个网页,利用session对象捕捉传递的参数,接收显示在网页上
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
欢迎你:<%=session.getAttribute("username") %>
网页共被访问:<%=application.getAttribute("count") %>次
</body>
</html>
完成后如上图所示