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

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

本文出自 “王乾De技术博客” 博客,谢绝转载!

你可能感兴趣的:(java,jsp,Web,servlet,jdbc)