日期:2014-05-17  浏览次数:20759 次

JSP里如何获得Session的值并存入数据库
Java code

<%
    boolean userlogined = false;
    String userLogined = (String) session.getAttribute("userId");
    if (userLogined != null) {
        userlogined = true;
    }
%>
<%
    request.setCharacterEncoding("UTF-8");
    String action = request.getParameter("action");
    if (action != null && action.trim().equals("post")) {
        String title = request.getParameter("title");
        //System.out.println(title);
        String cont = request.getParameter("cont");
        //System.out.println(cont);
        String name = request.getParameter("userlogined");
        Connection conn = DB.getConn();
        boolean autoCommit = conn.getAutoCommit();
        conn.setAutoCommit(false);
        int rootId = -1;
        String sql = "insert into article values(null,?,?,?,?,now(),?,?)";
        PreparedStatement pstmt = DB.prepareStmt(conn,sql,Statement.RETURN_GENERATED_KEYS);

        pstmt.setInt(1, 0);
        pstmt.setInt(2, rootId);
        pstmt.setString(3, title);
        pstmt.setString(4, cont);
        pstmt.setInt(5, 0);
        pstmt.setString(6,name);
        pstmt.executeUpdate();
        
        ResultSet rsKey = pstmt.getGeneratedKeys();    
        rsKey.next();

        rootId = rsKey.getInt(1);
        Statement stmt = DB.createStmt(conn);
        stmt.executeUpdate("update article set rootid=" + rootId + " where id="+ rootId);
        
        conn.commit();
        conn.setAutoCommit(autoCommit);
        DB.close(stmt);
        DB.close(pstmt);
        DB.close(conn);
        response.sendRedirect("articleFlat.jsp");
    }
%>





我在数据库里增加了一个name字段,是想在发表新主题的时候,把此时登陆的用户的名字也存入数据库里,然后实现发表的帖子对应发帖的人,可是用request的方法好像不行,那应该在html里怎么写。??
Java code

<form action="post.jsp" method="post">
                                    <input type="hidden" name="action" value="post" />
                                    
                                    标题:
                                    <input type="text" name="title">
                                    <br>
                                    内容:
                                    <br>
                                    <textarea name="cont" rows="15" cols="80"></textarea>
                                    <br>
                                    <input type="submit" value="提交" />
                                </form>



------解决方案--------------------
登录的时候 也罢username放在session
在 发布主题的时候

String name = (String) session.getAttribute("userName");

在session取出来就行了