将结果集值打印为html页面中的文本

时间:2017-10-17 00:58:02

标签: java jsp java-ee-7

我尝试使用这个nameString.jsp来创建一个var,所以我可以在网页中调用它。我想要的只是显示我的表中的值(来自personel_data的SELECT fullname,其中username ='" + user +"'&password ='" +传递+"'")所以它会打印"您好,' myfullname'!"

<%
try{
String user=request.getParameter("user");
String pass=request.getParameter("pass");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection 
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/tz","root","");  
       Statement st=con.createStatement();
       ResultSet rs=st.executeQuery("select * from personel_data where username='"+user+"' and password='"+pass+"'");
       if(rs.next()){
           String name=rs.getString("fullname");
           System.out.print(name);
       }
    }
catch(Exception e){
System.out.println(e);
}
%>

在网页response.jsp

<%@include file="nameString.jsp"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Welcome</title>
</head>
<body>
    Hello <%= name%>!
</body>
</html>

如果我删除&lt;%= name%&gt;,&#34; Hello&#34;将出现在网络上,但如果有&lt;%= name%&gt;它将无法编译。

1 个答案:

答案 0 :(得分:0)

你必须在try语句之外定义名称变量。这个事情的范围是&#34; name&#34;变量是全局的。你可以在另一个文件中使用它

 <%
    String name ="";
    try{
    String user=request.getParameter("user");
    String pass=request.getParameter("pass");
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/tz","root","");  
           Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select * from personel_data where username='"+user+"' and password='"+pass+"'");
           if(rs.next()){
               name=rs.getString("fullname");
               System.out.print(name);
           }
        }
    catch(Exception e){
    System.out.println(e);
    }

%>