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    
        }    


Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session
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    
        }    


Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session
看下效果
Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session
Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session
关闭IE后再打开测试
Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session
SessionServlet2.java
Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session
Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session
• Session 实例 
–登录Session
Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之17.Session
 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,如需转载请自行联系原作者

上一篇:函数式编程小试-记一次代码重构


下一篇:Java随堂笔记05-Java数组