Добавьте ответ в раздел комментариев во время работы с jsp

#javascript #html #ajax #jsp

Вопрос:

Я пытаюсь создать раздел комментариев, и мне не разрешено использовать php, а только jsp и сервлеты. Даже работая с jsp, мои знания ограничены. По сути, этот вопрос сводится к:

Как добавить элемент динамической формы с использованием файла jsp, чтобы разработчик мог ответить на комментарий после отображения комментария. Мой текущий код позволяет мне создавать комментарии с использованием ajax, но я не могу понять, как добавлять ответы.

Вот мой код, который приводит к созданию и отображению комментариев.

html-файл

 <!DOCTYPE html>
<html>
<head>
    <title>Comment Section </title>
<script>
var request;
function postComment(){
var comment=document.commentform.comment.value;
var email=document.commentform.email.value;

var url="index.jsp?comment=" comment "amp;email=" email;

if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}

try{
request.onreadystatechange=function(){
if(request.readyState===4){
var val=request.responseText;
document.getElementById('mylocation').innerHTML=val;
}
};
request.open("GET",url,true);
request.send();
}catch(e){alert("Unable to connect to server");}
}
</script>
</head>
<body>
<h1>Comment Form</h1>
<form name="commentform">
Enter Comment:<br/>
<textarea name="comment" style="width:300px;height:100px" required>
</textarea><br/>
Enter Email:<br/>
<input type="text" name="email" required/><br/><br/>

<input type="button" value="Post Comment" onclick="postComment()">
</form>

<span id="mylocation"></span>
</body>
</html>
 

Вот мой файл jsp, который добавляет комментарий в базу данных и отображает его, и функциональность работает:

 <!DOCTYPE html>
<html>
<head>
    <title>Comment Section  </title>
<style>
div.box{margin:2px;border:1px solid pink;padding:10px;background-color:#e3e3e3}
</style>
</head>
<body>

<%@ page import="java.sql.*" %>
<% 
    Connection con;
    String driverName ="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String sourceURL = 
"jdbc:sqlserver://localhost:1433;databaseName=Comments;user=sa;password=helloworld;";
    String user = "sa";
    String password = "helloworld";    
    String comment=request.getParameter("comment");
    String email=request.getParameter("email");
    
if(comment==null||email==null||comment.trim().equals("")||email.trim().equals("")){
        out.print("<p>Please write comment</p>");
    }else{

    try{
        Class.forName(driverName);
        con = DriverManager.getConnection(sourceURL, user,password); 

        PreparedStatement ps=con.prepareStatement("insert into 
usercomment(comment1,email) values(?,?)");
        ps.setString(1,comment);
        ps.setString(2,email);
        int i=ps.executeUpdate();

        PreparedStatement ps2=con.prepareStatement("select * from usercomment order 
by id desc");
        ResultSet rs=ps2.executeQuery();

        out.print("<hr/><h2>Comments:</h2>");
        while(rs.next()){
            out.print("<div class='box'>");
            out.print("<p>" rs.getString(2) "</p>");
            out.print("<p><strong>By: " rs.getString(3) "</strong></p>");
            out.print("</div>");
        }

        con.close();
    }catch(Exception e){out.print(e);}
        System.out.println("error");
    }
%>
</body>
</html>
 

The next jsp file is an updated version of the previous jsp where i succeed in adding a reply section to the comments themselves but then the functionality stops.

 <!DOCTYPE html>
<html>
<head>
    <title>Comment Section  </title>
<style>
div.box{margin:2px;border:1px solid pink;padding:10px;background-color:#e3e3e3}
</style>
</head>
<body>

<%@ page import="java.sql.*" %>
<% 
    Connection con;
    String driverName ="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String sourceURL = 
"jdbc:sqlserver://localhost:1433;databaseName=Comments;user=sa;password=helloworld;";
    String user = "sa";
    String password = "helloworld";    
    String comment=request.getParameter("comment");
    String email=request.getParameter("email");
    
if(comment==null||email==null||comment.trim().equals("")||email.trim().equals("")){
        out.print("<p>Please write comment</p>");
    }else{

    try{
        Class.forName(driverName);
        con = DriverManager.getConnection(sourceURL, user,password); 

        PreparedStatement ps=con.prepareStatement("insert into 
usercomment(comment1,email) values(?,?)");
        ps.setString(1,comment);
        ps.setString(2,email);
        int i=ps.executeUpdate();

        PreparedStatement ps2=con.prepareStatement("select * from usercomment order 
by id desc");
        ResultSet rs=ps2.executeQuery();

        out.print("<hr/><h2>Comments:</h2>");
        while(rs.next()){
            out.print("<div class='box'>");
            out.print("<p>" rs.getString(2) "</p>");
            out.print("<p><strong>By: " rs.getString(3) "</strong></p>");
            out.write("<form name="commentform">n");
            out.write("Enter Comment:<br/>n");
            out.write("<textarea name="comment" style="width:300px;height:100px" 
required>n");
            out.write("</textarea><br/>n");
            out.write("Enter Email:<br/>n");
            out.write("<input type="text" name="email" required/><br/><br/>n");
            out.write("n");
            out.write("<input type="button" value="Post Comment" 
onclick="postComment()">n");
            out.write("</form>n");
            out.write("n");
            out.write("<span id="mylocation"></span>n");
            out.print("</div>");
        }

        con.close();
    }catch(Exception e){out.print(e);}
        System.out.println("error");
    }
%>
</body>
</html>
 

Вот ошибка, которую я получаю в браузере при запуске моего html со вторым jsp.

 index.html:8 Uncaught TypeError: Cannot read property 'value' of undefined
at postComment (index.html:8)
at HTMLInputElement.onclick (index.html:1)
postComment @ index.html:8
onclick @ index.html:1
 

Помощь была бы очень признательна.