Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session

简介:
–Session 简介 
–Session API 
–Session 实例 
• 登录Session
#################Michael分割线####################
• Session 简介 
–由于HTTP协议的无状态性,无法持久保持对象的状态,那么怎么才能实现持久保存对象的状态呢?
Java的解决方案有两种: 
• Cookie 
–见上一节 
• Session 
–Session 是用来跟踪用户当前状态的一种机制,是针对浏览器和服务器的一对一关系。 
–Session 的一般用法是,在用户登录时将用户的登录信息保存到session中,以便以后使用。
• Session API 
–Session 接口HttpSession 
• 通常我们只使用HttpSession接口,接口的实现由web容器来完成 
–获得HttpSession 
• 可以从HttpServletRequest中获得HttpSession 
–request.getSession(); 
–将信息保存在HttpSession中 
• session.setAttribute(“UserSession”,obj); 
–从HttpSession中获得信息 
• session.getAttribute(“UserSession”); 
–使HttpSession失效 
• session.invalidate();
SessionServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    

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 SessionServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public SessionServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request,response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    
                HttpSession session = request.getSession();    
                session.setAttribute( "SessionObj""session_Value");    

                response.setContentType( "text/html");    
                PrintWriter out = response.getWriter();    
                out    
                                .println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");    
                out.println("<HTML>");    
                out.println("    <HEAD><TITLE>A Servlet</TITLE></HEAD>");    
                out.println("    <BODY>");    
                out.print("        This is ");    
                out.print(this.getClass());    
                out.println(", using the POST method");    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    

        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occure    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    


image
SessionServlet2.java
package com.michael.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    

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 SessionServlet2  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public SessionServlet2() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request,response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    
                HttpSession session = request.getSession();    
                String obj = (String) session.getAttribute( "SessionObj");    

                response.setContentType( "text/html");    
                PrintWriter out = response.getWriter();    
                out    
                                .println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");    
                out.println("<HTML>");    
                out.println("    <HEAD><TITLE>A Servlet</TITLE></HEAD>");    
                out.println("    <BODY>");    
                out.print(obj);    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    

        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occure    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    


image
看下效果
image
image
关闭IE后再打开测试
image
SessionServlet2.java
image
image
• Session 实例 
–登录Session
image
  ConnectionUtil.java
package com.michael.dao.impl;    

import java.sql.Connection;    
import java.sql.PreparedStatement;    
import java.sql.ResultSet;    
import java.sql.SQLException;    

import com.michael.dao.ConnectionUtil;    
import com.michael.dao.User;    
import com.michael.dao.UserDao;    

public  class UserDaoImpl  implements UserDao {    

         public User login(String username, String password) {    
                Connection conn =  new ConnectionUtil().openConnection();    
                String sql =  "select id,name,password from UserTbl where name=? and password=?";    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(sql);    
                        pstmt.setString(1, username);    
                        pstmt.setString(2, password);    
                        ResultSet rs = pstmt.executeQuery();    
                         if(rs.next()){    
                                 int id = rs.getInt(1);    
                                User u =  new User();    
                                u.setId(id);    
                                u.setUsername(username);    
                                u.setPassword(password);    
                                 return u;    
                        }    
                }  catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                                 try {    
                                        conn.close();    
                                }  catch (SQLException e) {    
                                        e.printStackTrace();    
                                }    
                }    
                 return  null;    
        }    


User.java
package com.michael.dao;    

public  class User {    
         private  int id;    
         private String username;    
         private String password;    
         public  int getId() {    
                 return id;    
        }    
         public  void setId( int id) {    
                 this.id = id;    
        }    
         public String getPassword() {    
                 return password;    
        }    
         public  void setPassword(String password) {    
                 this.password = password;    
        }    
         public String getUsername() {    
                 return username;    
        }    
         public  void setUsername(String username) {    
                 this.username = username;    
        }    

UserDao.java
package com.michael.dao;    

public interface UserDao {    
        public User login(String username,String password);    


UserDaoImpl.java 
package com.michael.dao.impl;    

import java.sql.Connection;    
import java.sql.PreparedStatement;    
import java.sql.ResultSet;    
import java.sql.SQLException;    

import com.michael.dao.ConnectionUtil;    
import com.michael.dao.User;    
import com.michael.dao.UserDao;    

public  class UserDaoImpl  implements UserDao {    

         public User login(String username, String password) {    
                Connection conn =  new ConnectionUtil().openConnection();    
                String sql =  "select id,name,password from UserTbl where name=? and password=?";    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(sql);    
                        pstmt.setString(1, username);    
                        pstmt.setString(2, password);    
                        ResultSet rs = pstmt.executeQuery();    
                         if(rs.next()){    
                                 int id = rs.getInt(1);    
                                User u =  new User();    
                                u.setId(id);    
                                u.setUsername(username);    
                                u.setPassword(password);    
                                 return u;    
                        }    
                }  catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                                 try {    
                                        conn.close();    
                                }  catch (SQLException e) {    
                                        e.printStackTrace();    
                                }    
                }    
                 return  null;    
        }    


LoginServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    

import javax.servlet.ServletException;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    
import javax.servlet.http.HttpSession;    

import com.michael.dao.User;    
import com.michael.dao.UserDao;    
import com.michael.dao.impl.UserDaoImpl;    

public  class LoginServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public LoginServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                response.setContentType( "text/html");    
                PrintWriter out = response.getWriter();    
                out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");    
                out.println("<HTML>");    
                out.println("    <HEAD><TITLE>A Servlet</TITLE></HEAD>");    
                out.println("    <BODY>");    
                out.print("        This is ");    
                out.print(this.getClass());    
                out.println(", using the GET method");    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    

        /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {    
                //获取用户名和密码    
                String username = request.getParameter("username");    
                String password = request.getParameter("password");    
                UserDao dao = new UserDaoImpl();    
                User u = dao.login(username,password);    
                if(u!=null){    
                        HttpSession session = request.getSession();    
                        session.setAttribute("UserSession", u);    
                        request.getRequestDispatcher("/welcome.jsp").forward(request, response);    
                }else{    
                        request.getRequestDispatcher("/failure.html").forward(request, response);    
                }    
        }    

        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occure    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    


DBConfig.properties
driver=com.mysql.jdbc.Driver    
url=jdbc:mysql: //localhost:3306/servlet_db    
user=root    
password=mysqladmin
#################Michael分割线####################






本文转自redking51CTO博客,原文链接:http://blog.51cto.com/redking/175908,如需转载请自行联系原作者

相关文章
|
20天前
|
监控 JavaScript 前端开发
《理解 WebSocket:Java Web 开发的实时通信技术》
【4月更文挑战第4天】WebSocket是Java Web实时通信的关键技术,提供双向持久连接,实现低延迟、高效率的实时交互。适用于聊天应用、在线游戏、数据监控和即时通知。开发涉及服务器端实现、客户端连接及数据协议定义,注意安全、错误处理、性能和兼容性。随着实时应用需求增加,WebSocket在Java Web开发中的地位将更加重要。
|
6天前
|
JSON Java fastjson
Spring Boot 底层级探索系列 04 - Web 开发(2)
Spring Boot 底层级探索系列 04 - Web 开发(2)
15 0
|
6天前
|
安全 编译器 PHP
PHP 8.1版本发布:引领Web开发新潮流
PHP编程语言一直是Web开发的主力军,而最新发布的PHP 8.1版本则为开发者们带来了更多创新和便利。本文将介绍PHP 8.1版本的主要特性,包括更快的性能、新的语言功能和增强的安全性,以及如何利用这些功能来提升Web应用程序的质量和效率。
|
9天前
|
PHP
web简易开发——通过php与HTML+css+mysql实现用户的登录,注册
web简易开发——通过php与HTML+css+mysql实现用户的登录,注册
|
9天前
|
前端开发 数据挖掘 API
使用Python中的Flask框架进行Web应用开发
【4月更文挑战第15天】在Python的Web开发领域,Flask是一个备受欢迎的轻量级Web框架。它简洁、灵活且易于扩展,使得开发者能够快速地构建出高质量的Web应用。本文将深入探讨Flask框架的核心特性、使用方法以及在实际开发中的应用。
|
18天前
|
安全 前端开发 Java
Java Web开发知识点学习总结
Java Web开发涉及Java基础、Servlet、JSP、数据库操作(SQL+JDBC)、MVC设计模式、Spring框架、Hibernate ORM、Web服务(SOAP&RESTful)、安全认证(HTTP Basic/Digest/OAuth)及性能优化(缓存、异步、负载均衡)。
17 3
|
21天前
|
XML JSON JavaScript
使用JSON和XML:数据交换格式在Java Web开发中的应用
【4月更文挑战第3天】本文比较了JSON和XML在Java Web开发中的应用。JSON是一种轻量级、易读的数据交换格式,适合快速解析和节省空间,常用于API和Web服务。XML则提供更强的灵活性和数据描述能力,适合复杂数据结构。Java有Jackson和Gson等库处理JSON,JAXB和DOM/SAX处理XML。选择格式需根据应用场景和需求。
|
23天前
|
Java
排课系统【JSP+Servlet+JavaBean】(Java课设)
排课系统【JSP+Servlet+JavaBean】(Java课设)
7 0
|
23天前
|
Java
仓库管理系统【JSP+Servlet+JavaBean】(Java课设)
仓库管理系统【JSP+Servlet+JavaBean】(Java课设)
13 0
|
Java 应用服务中间件 容器
Java设置session超时(失效)的三种方式 (转载)
Java设置session超时(失效)的三种方式 (转载)
209 0