- 利用session保存用户信息,验证用户是否有权访问该页面。
- 验证:2个jsp,一个servlet
- login.jsp
<%@ 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>
<form action="servlet1" method="post">
姓名:<input type="text" name="name" id="" value="" ><br />
手机:<input type="text" name="mobile" id="" value="" ><br />
<input type="submit" value="提交">
</form>
</body>
</html>
- servlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String name=request.getParameter("name");
String mobile =request.getParameter("mobile");
if("lisi".equals(name)&&"123".equals(mobile) ) {
request.getSession().setAttribute("name", name);
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
}else {
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- welcome.jsp
<%@ 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>
welcome!
!
<%
if (null==session.getAttribute("name")){
out.write("无权访问");
}
else{
out.write("欢迎"+session.getAttribute("name"));
}
%>
</body>
</html>