从 servlet 获取数据到 JSP 并通过 ajax 再次将该数据发送到另一个 servlet
Posted
技术标签:
【中文标题】从 servlet 获取数据到 JSP 并通过 ajax 再次将该数据发送到另一个 servlet【英文标题】:Getting data from a servlet to JSP and sending that data again to another servlet through ajax 【发布时间】:2021-08-15 10:09:13 【问题描述】:我是 JSP 和 servlet 的新手。我正在设计一个tomcat 10.0版的图书馆管理系统,当用户使用他的用户ID和密码以html形式登录时,一旦使用RequestDispatcher匹配的凭据将它发送到登录servlet,它将用户ID发送到userlogin(home)JSP进一步使用。
在这一切正常之前,在该 JSP 中,有两个操作,一个是用户可以检查 mysql 数据库中的书籍可用性和他/她的书的归还日期,如果他/她借了任何书,否则不会有借书消息显示。
任务是,我想通过ajax得到以上两个动作的结果。一旦用户在输入字段中输入要搜索的书名并按下按钮,ajax应该调用servlet并从数据库中获取与其对应的值并以htmltable格式创建数据并将其返回给ajax调用和ajax获取它,应该使用 innerhtml 或 DOM html 函数在特定的 div 中显示它。同样的方法是user获取用户借书的归还日期。
问题:
但是,一旦在字段中输入书名并按下按钮,就会调用该操作,但它会显示 405 错误,即 servlet 不允许 GET 方法,尽管在 ajax 调用和我的 servlet 中我使用了 POST 方法。我注意到当用户登录时,即使页面显示 JSP 页面,URL 栏也会显示登录 servlet URL,并且一旦调用 ajax,数据就会从登录 servlet 发送(http://localhost:8080/library/UserLogin ) 并且也在同一个登录 servlet(http://localhost:8080/library/UserLogin?search=java) 中收到,这似乎在 get 方法中工作(但我在双方都使用了 POST),所以我猜数据是仍在同一个 servlet URL 中移动。
UserLogin.java
public class UserLogin extends HttpServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html");
PrintWriter out=response.getWriter();
//getting userid and password for checking with database//
String userid=request.getParameter("uid");
String pass=request.getParameter("pwd");
try
Connection connect=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password");
PreparedStatement ps =connect.prepareStatement("select * from library.user where userid = ? and pass = ?");
ps.setString(1, userid);
ps.setString(2, pass);
ResultSet rs=ps.executeQuery();
if(rs.next())
request.setAttribute("userid",userid);
RequestDispatcher rd=request.getRequestDispatcher("userlogin.jsp");
rd.forward(request,response);
else
RequestDispatcher rd=request.getRequestDispatcher("http://localhost:4200/user");
rd.forward(request,response);
catch(SQLException e)
System.out.println(e);
'
userlogin.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
<link rel="stylesheet" href="css/app.css">
<link rel="icon" href="images/logo.jpg" type ="image/x-icon">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="heading">
<div class="title">
<h1>Online Library</h1>
</div>
<div class="logo">
<i class="fas fa-book-reader fa-7x"></i>
</div>
</div>
<div class="search-container">
<form>
<input type="text" name="search" id="search" placeholder="Search by book genre (Eg:Search Java for Java books)" />
<button id="getbook"><i class="fas fa-search"></i></button>
<!--the button for ajax to get book availability table-->
</form>
</div>
<hr>
</div>
<button id="mybook">My Books and Due date</button>
<!--the button for ajax to get user's book returndate table-->
<%String suserid=(String)request.getAttribute("userid");
out.println("name:"+suserid);%> <!--storing userid for using it for user's book returndate-->
<div id="books"> <!--div tag where the table will show-->
</div>
<script>
$(document).ready(function()
$("#getbook").click(function()
var search=$("#search").val()
$.ajax(
type:'POST',
url:'Issuedbooks',
data:search,
success:function(response)
console.log(response);
$("#books").html(response);
,error:function(request,status,error)
alert("Error:"+error+status);
);
);
$("#mybook").click(function()
var userid= suserid; /*I also doubt on this declaration if it is wrong give suggestion please*/
$.ajax(
type:'POST',
url:'mybooks',
data:userid,
success:function(response)
console.log(response);
$("#books").html(response);
,error:function(request,status,error)
alert("Error:"+error+status);
);
);
);
</script>
</body>
</html>
Issuedbooks.java
public class Issuedbooks extends HttpServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html><body>"); //creating a html table//
String genre=request.getParameter("search"); //the value in input field of jsp page//
try
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select * from library.issue where genre='"+genre+"'");
out.println("<table border=1>");
out.println("<tr><th>Bookid</th><th>Returndate</th><th>Bookname</th><th>Authorname</th></tr>"); //creating table header//
while(rs.next())
String bookid=rs.getString(3);
String returndate=rs.getString(5);
out.println("<tr><td>"+bookid+"</td><td>"+returndate+"</td>");
Connection con1=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password"); //as I have to get data from two database I have created two connections//
Statement stmt1 = con1.createStatement();
ResultSet rs1=stmt1.executeQuery("select * from library.books where genre='"+genre+"'");
while(rs1.next())
String bookname=rs1.getString(2);
String authorname=rs1.getString(3);
out.println("<td>"+bookname+"</td><td>"+authorname+"</td></tr>"); //continuing to add this in same table//
out.println("</table");
out.println("</body></html>"); //end of htmltable//
catch(SQLException e)
e.printStackTrace();
mybooks.java
public class mybooks extends HttpServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
String userid=request.getParameter("suserid"); //getting userid from jsp which is obtained from userlogin servlet//
try
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select * from library.issue where userid='"+userid+"'");
out.println("<table border=1>");
out.println("<tr><th>Bookid</th><th>IssueId</th><th>Userid</th><th>Bookid</th><th>Issuedate</th><th>Returndate</th><th>Genre</th></tr>");
if(rs.next())
String issueid=rs.getString(1);
String userid=rs.getString(2);
String bookid=rs.getString(3);
String issuedate=rs.getString(4);
String returndate=rs.getString(5);
String genre=rs.getString(7);
out.println("<tr><td>"+issueid+"</td><td>"+userid+"</td><td>"+bookid+"</td><td>"+issuedate+"</td><td>"+returndate+"</td><td>"+genre+"</td></tr>");
else
out.println("No books issued");
catch(SQLException e)
e.printStackTrace();
所以这些是我的代码,在运行这些代码时会出现这样的错误。 HTTP GET is not supported by this url 在我的 tomcat 服务器中。我使用 POST 方法完成了所有操作,因为使用 GET 方法时出现错误,并且 jsp 页面中的 url 仍然显示 userlogin servlet URL,并且在调用 ajax 时数据未通过此 URL 传递。我检查了 web.xml 一切都很好。
对不起,描述太长了,我只是想清楚地描述我的问题以获得答案。在此先感谢:)
【问题讨论】:
您好,您的表单正在提交,而不是 ajax。简单的解决方法是将type="button"
添加到您的按钮。
@Swati 谢谢妈妈,它工作 ajax 正在获取表,但表没有显示除表头以外的任何值。在 servlet 中创建 html 表的方法是好还是我应该使用任何其他方法来获取表值。需要建议...!
嗨,你检查request.getParameter("search");
是否有任何价值?另外,尝试将此data:search
更改为data:"search" : search ,
@Swati 它工作得很好妈妈,我得到了桌子,但第二个动作不起作用。我从 loginservlet 收到用户 ID 并转换为字符串并将其值设置为输入字段,以便我可以将其用于 ajax 函数。用户 ID 正在传递给 servlet,但响应只是表头,没有表数据。
嗨,打印看看userid
是否有任何价值。此外,无需将它们转换为字符串,因为它们已经是字符串值并且在您的服务器上userid
列是 Pk 吗?如果是,只需将该传递值转换为整数类型。
【参考方案1】:
很抱歉再次分享代码,但我没有弄清楚我遗漏了该部分的位置。这里我只分享了不工作的部分
userlogin.jsp
<%String userid=(String)request.getAttribute("userid");%> //converted to received object to string here//
<input type="hidden" id="userid" value='<%out.println(userid);%>'> //set value of input as userid and hide it so I can use it for ajax//
<input type="button" id="mybook" value="My books and due date" />
<div id="books">
</div>
<script>
$("#mybook").click(function()
console.log("test print");
var userid= $("#userid").val();
$.ajax(
type:'POST',
url:'mybooks',
data:user_id:userid.toString(), //I have a doubt whether it is changed to string or not so again tried to transfer it as string//
success:function(response)
console.log(response);
$("#books").html(response);
,error:function(request,status,error)
alert("Error:"+error+status);
);
);
</script>
mybooks.java
public class mybooks extends HttpServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
String userid=request.getParameter("user_id");
try
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select * from library.issue where userid='"+userid+"'");
out.println("<table border=1>");
out.println("<tr><th>Bookid</th><th>IssueId</th><th>Userid</th><th>Bookid</th><th>Issuedate</th><th>Returndate</th><th>Genre</th></tr>"); //i am getting upto this content in response//
while(rs.next())
String issueid=rs.getString(1);
String uid=rs.getString(2);
String bookid=rs.getString(3);
String issuedate=rs.getString(4);
String returndate=rs.getString(5);
String genre=rs.getString(7);
out.println( "<tr><td>"+issueid+"</td><td>"+uid+"</td><td>"+bookid+"</td><td>"+issuedate+"</td><td>"+returndate+"</td><td>"+genre+"</td></tr>"); //I didn't get this part in response, I doubt whether the data is receiving in servlet evethough it is passed here//
out.println("</table>");
out.println("</body></html>");
catch(SQLException e)
e.printStackTrace();
【讨论】:
以上是关于从 servlet 获取数据到 JSP 并通过 ajax 再次将该数据发送到另一个 servlet的主要内容,如果未能解决你的问题,请参考以下文章
servlet怎么从javabean得到表格数据 然后再传给jsp
怎么从servlet传递一个值,然后在一个jsp页面得到这个值