Search code examples
htmlstringjspexceptionresultset

How to display a string value taken from a resultset variable onto HTML?


I am trying to print a string which I took from my database and saved it in resultset variable. But when I try to execute it always shows an exception

try{
rs=stmt.executeQuery("select * from users where user_id='"+username+"'");
}
catch(Exception e)
{
System.out.println(e);
}   
%>
<html>
<body style="background-color:powderblue">
<%=username%>'s profile<br>
Username : <%=rs.getString("user_id")%><br>
Gender : <%=rs.getString("g")%><br>
Password : <%=rs.getString("user_password")%><br>
First Name : <%=rs.getString("f_name")%><br>
Last Name : <%=rs.getString("l_name")%><br>
</body>
</html>

The error message I get is

Type Exception Report
Message An exception occurred processing JSP page [/myprofile.jsp] at line [26]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: An exception occurred processing JSP page [/myprofile.jsp] at line [26]
23: <html>
24: <body style="background-color:powderblue">
25: <%=username%>'s profile<br>
26: <%=rs.getString("user_id")%>
27: </body>
28: </html>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Root Cause

javax.servlet.ServletException: java.sql.SQLException: ResultSet.next was not called org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:909) org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:838) org.apache.jsp.myprofile_jsp._jspService(myprofile_jsp.java:155) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)


Solution

  • You need to add if (rs.next()) {} or while (rs.next()) {}.

    <%
    if (rs.next()) {
    %>
        Username : <%=rs.getString("user_id")%><br>
        Gender : <%=rs.getString("g")%><br>
        Password : <%=rs.getString("user_password")%><br>
        First Name : <%=rs.getString("f_name")%><br>
        Last Name : <%=rs.getString("l_name")%><br>
    <%
    }
    %>