当前位置:编程学习 > JAVA >>

JSP+Servlet在一个Session中共享connection.新手求教!提供完善的解决方法!

两个Servlet,一个负责连接登陆页面的数据库连接,另一个Servlet负责把所需信息存到数据库,用Session共享一个连接。一个request.getSession().setAttribute("connection", connection);
con = (Connection)request.getSession().getAttribute("connection");行不行?最好写完整的代码给我下,另外写个类把连接的提供者放到里面那个不会实现。本人菜鸟一个。麻烦详细点!谢谢 --------------------编程问答-------------------- 没搞懂,设计没看懂到底要干嘛。数据库连接写个jdbc类就行,怎么整到servlet上了。没懂 --------------------编程问答-------------------- 不用session共享的直接利用另一个Servlet调用就行了 --------------------编程问答-------------------- 或者就是写一个连接类,直接调用就行了 --------------------编程问答-------------------- public class ConnectionUtil {  
  
    private static final String DRIVER = "com.mysql.jdbc.Driver";  
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/txazo";  
    private static final String USER = "root";  
    private static final String PASSWORD = "root";  
  
    static {  
        try {  
            Class.forName(DRIVER);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
      
    private ConnectionUtil() {  
    }  
  
    public static synchronized Connection getConnection() {  
        Connection connection = null;  
        try {  
            connection = DriverManager.getConnection(URL, USER, PASSWORD);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return connection;  
    }  
  
}  
然后再sevlet中直接调用这个getConnection方法就行了 --------------------编程问答-------------------- 连接数据库用jdbc或用hibernet,ibatis框架。
页面跳转用struts2框架, --------------------编程问答-------------------- 你这个想法是可以的,通过setAttribute()方法将一个实例化的DB对象放入session中,然后在其他的jsp,servlet中用getAttribute()方法都可以取出来使用。我没有自己实践过,但是我在书上看到过。 --------------------编程问答--------------------
引用 4 楼 scqlmm 的回复:
public class ConnectionUtil {  
  
    private static final String DRIVER = "com.mysql.jdbc.Driver";  
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/txazo";  
    private static final String USER = "root";  
    private static final String PASSWORD = "root";  
  
    static {  
        try {  
            Class.forName(DRIVER);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
      
    private ConnectionUtil() {  
    }  
  
    public static synchronized Connection getConnection() {  
        Connection connection = null;  
        try {  
            connection = DriverManager.getConnection(URL, USER, PASSWORD);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return connection;  
    }  
  
}  
然后再sevlet中直接调用这个getConnection方法就行了

亲,你在sevlet里,直接应用这个类,代码如下:
Connection connection=new ConnectionUtil().getConnection();
request.getSession().setAttribute("connection", connection);
 con = (Connection)request.getSession().getAttribute("connection");
你是不是这个意思呢?
--------------------编程问答--------------------
引用 7 楼 caochuankui 的回复:
Quote: 引用 4 楼 scqlmm 的回复:

public class ConnectionUtil {  
  
    private static final String DRIVER = "com.mysql.jdbc.Driver";  
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/txazo";  
    private static final String USER = "root";  
    private static final String PASSWORD = "root";  
  
    static {  
        try {  
            Class.forName(DRIVER);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
      
    private ConnectionUtil() {  
    }  
  
    public static synchronized Connection getConnection() {  
        Connection connection = null;  
        try {  
            connection = DriverManager.getConnection(URL, USER, PASSWORD);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return connection;  
    }  
  
}  
然后再sevlet中直接调用这个getConnection方法就行了

亲,你在sevlet里,直接应用这个类,代码如下:
Connection connection=new ConnectionUtil().getConnection();
request.getSession().setAttribute("connection", connection);
 con = (Connection)request.getSession().getAttribute("connection");
你是不是这个意思呢?

在servlet中Connection connection=new ConnectionUtil().getConnection(); 下来直接走操作就行了,不用放到session里面去 --------------------编程问答-------------------- 登陆实例(JSP+Servlet+JavaBean) 转
登陆是我们在实际应用中经常用到的,我在这边举个简单的登陆例子,作为抛砖引玉吧!

程序结构如下:

采用JSP+Servlet+JavaBean

1.数据库结构(为简便这边采用access,实际应用中建议采用其他数据库如MySQL,MSSQL等)

==============================

uname   用户名 文本型

pword    密码      文本型

初始数据uname :ceun pword :123

==============================

2.视图(JSP)


<%...@page contentType="text/html"%>
<%...@page pageEncoding="UTF-8"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>登陆</title>
    </head>
    <body>
<center><br><br><br>
<p><form action="<%=request.getContextPath ()%>/CheckServlet" method="post">
<table width="259" border="1" cellpadding="0" cellspacing="0" bordercolor="#0099FF">
<tr align="center">
    <td height="20" colspan="2"><span class="style1">登陆</span></td>
</tr>
<tr>
    <td width="50" height="20">用户名</td>
    <td width="161" align="left"><input name="uname" type="text" id="uname" size="19"></td>
</tr>
<tr>
    <td height="20">密码</td>
    <td align="left"><input name="pword" type="password" id="pword" size="20"></td>
</tr>
<tr align="center">
    <td colspan="2"><input type="submit" name="Submit" value="提交">  
      <input type="reset" name="Submit" value="重置"></td>
</tr>
</table></form></p>
</center>
    </body>
</html>



3.Servlet

package com.ceun;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;
import com.ceun.bean.UserBean;
/** *//**
*
* @author ceun
* @version
*/
public class CheckServlet extends HttpServlet ...{
    
    /** *//** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException ...{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String name=request.getParameter("uname");
        String pword=request.getParameter("pword");
        out.println("<br><br><br><hr><center><font color=red size=12><B>");
        try...{
        UserBean user=new UserBean();
        if(user.check(name,pword))
            out.println("登陆成功");
        else
            out.println("登陆失败");
        }catch(Exception e)...{
           
        }
        out.println("</B></font></center>");
        out.close();
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** *//** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException ...{
        processRequest(request, response);
    }
    
    /** *//** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException ...{
        processRequest(request, response);
    }
    
    /** *//** Returns a short description of the servlet.
     */
    public String getServletInfo() ...{
        return "Short description";
    }
    // </editor-fold>
}

4.JavaBean

package com.ceun.bean;
import java.sql.*;
import com.ceun.util.DbUtil;
/**//**
*
* @author ceun
*/
public class UserBean ...{
    
    /**//** Creates a new instance of UserBean */
    public UserBean() ...{
    }
    public boolean check(String username,String password)
      throws Exception...{
    Connection con= DbUtil.connectToDb();
    Statement stmt=null;
      try...{
            String sql="SELECT * FROM loginInfo "+
         " WHERE uname='"+username+"' and pword='"+password+"'";
              stmt=con.createStatement();
              
              ResultSet rs=stmt.executeQuery(sql);
              if(rs.next()) return true;
        }
      catch(Exception ex)
      ...{
            
      }finally...{
        try...{
          stmt.close();
          con.close();
        }catch(Exception e)...{e.printStackTrace();}
      }
     return false;
}
    
}

5.实用类(用于连接数据库)
package com.ceun.util;
import java.io.*;
import java.sql.*;

/**//**
* <strong>DbUtil</strong> is a utility class to create
* a connection to our sample database.
*/
public class DbUtil ...{
    static String driverName="sun.jdbc.odbc.JdbcOdbcDriver";
    static String dbUrl="jdbc:odbc:";

public DbUtil() ...{

}

public static java.sql.Connection connectToDb(String databaseName)throws Exception
...{
        Connection connection=null;
        String connName = dbUrl+databaseName;
        Class.forName(driverName).newInstance();
        connection = DriverManager.getConnection(connName);
        return connection;
}

public static java.sql.Connection connectToDb()throws Exception...{
    return (connectToDb("logInfo"));
}
}

6.应用配置文件


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <servlet-name>CheckServlet</servlet-name>
        <servlet-class>com.ceun.CheckServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CheckServlet</servlet-name>
        <url-pattern>/CheckServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
    <welcome-file>
            index.jsp
        </welcome-file>
    </welcome-file-list>
</web-app>
这是个小例子看看估计你就明白了 --------------------编程问答-------------------- 你那种方法也可以但是不要关闭连接了 否则在第二个页面中就无法使用了
补充:Java ,  Web 开发
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,