JSP内置对象session 常用方法及案例

首先我先说一下session的常用方法

1>setAttribute 

2>getAttribute

3>sendRedirect //重定向


这是login.jsp代码及效果图

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>






登陆页面





	
用户名:
密  码:

当你输入1  1 经过control.jsp跳到success.jsp

control.jsp代码如下

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<%
	request.setCharacterEncoding("utf-8");
	String name = request.getParameter("txtname");
	String pwd = request.getParameter("txtpwd");
	if ("1".equals(name) && "1".equals(pwd)) {
		session.setAttribute("name", name);
		response.sendRedirect(path + "/success.jsp");
		Cookie cookie=new Cookie("name",name);
		response.addCookie(cookie);
	} else {
		response.sendRedirect(path + "/login.jsp");
	}
%>
success.jsp代码效果图如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>



  

    
    成功页面
    


  
  
  
  
  <%@ include file="tool.jsp"  %>
  欢迎您:<%=session.getAttribute("name") %>
  注销
  
当你点击注销时,会执行longout.jsp 代码如下


  
    
    
    My JSP 'loginout.jsp' starting page
    


  
  
  
   <%
   		session.removeAttribute("name");
   		response.sendRedirect(path+"/login.jsp");
   		
   
   
    %>
  


如果你直接从success.jsp进去 那么会直接挑传到login.jsp(登陆)页面也就是他会执行success.jsp

<%@ include href="tool.jsp"%>

tool.jsp的代码如下

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
Object name=session.getAttribute("name");
if(name==null){
response.sendRedirect(path+"/	login.jsp");
}
 %>












你可能感兴趣的:(JSP内置对象session 常用方法及案例)