尝试将值从jsp传递到servlet

时间:2014-04-14 17:22:45

标签: mysql jsp servlets

我有一个jsp文件discussion_new.jsp,我试图通过它将参数传递给名为DiscussionServlet的servlet,但是这些值没有通过,请帮助,我附上以下代码。< / p>

以下是discussion_new.jsp

 <%@page contentType="text/html" pageEncoding="UTF-8"%>
 <!DOCTYPE html>

 <html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>

</head>
<body>
<h1 align="center"> Start a New Discussion</h1>
  <div id="right-container">
<form action="DiscussionServlet" method="post">
       <br>
     <h1 align="left">Discussion Title</h1>
  <textarea name="post-title" id="post-title" rows ="1" cols="90" height="50"   
    width="200">
                  </textarea>
            <h1 align="left">Discussion Content</h1>
   <textarea name="post-detail" id="post-detail" rows="18" cols="90" height="50" 
     width="200">
  </textarea>

<input id="button-submit" type="submit" value="Post" onclick="return confirm('Do                
      you really want to make this post?');" name="submit"/>        
     </form>
  </div>

   </body>
    </html>

以下是Servlet代码:

@WebServlet(name = "DiscussionServlet", urlPatterns = {"/DiscussionServlet"})
public class DiscussionServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession s=request.getSession();
   String u_id= (String) s.getAttribute("u_id");
   String post_title=request.getParameter("post-title");
   String post_detail=request.getParameter("post-detail");


    PreparedStatement p1=null;
    try {
         Connection c1=ConnectionClass.getConnected();
         p1=c1.prepareStatement("insert into     
     discuss(id,disc_title,disc_content)values(?,?,?)");
         p1.setString(1, u_id);
         p1.setString(2, post_title);
         p1.setString(3, post_detail);    
    }
    catch(Exception e)
    {

    }
    finally {            
        out.close();
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}


   @Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>
} 

sql语法和属性值没有错误,我已经检查过了,我也从代码中删除了额外的注释。希望有人帮忙

2 个答案:

答案 0 :(得分:0)

您的代码看起来很好,请确认您将servlet打印值中的数据发送到控制台,如下所示 String post_title=request.getParameter("post-title"); String post_detail=request.getParameter("post-detail"); System.out.println(post_title); System.out.println(post_detail); 并检查你控制台是否有价值

答案 1 :(得分:0)

你的代码是完美的,并且值也传递给servlet,只有我认为你犯的错误是你要将接收到的值插入到数据库中但是p1.executeUpdate()丢失了所以如果你想要接收到的值要存储在数据库中包含p1.executeUpdate()它会正常工作...........!