您的位置:首页 > 编程语言 > Java开发

Java自学之路-Java基础教程-39:Java的Web工程访问数据库和网页显示数据

2018-03-19 16:54 711 查看
前面已经介绍了如何创建Web工程和第一个jsp网页,并且也介绍了使用Java从数据库里面取出数据转为Java对象。直接把数据库操作的Java代码复制到index.jsp里面的body标签中,放在Java标签<%和%>里是不是就可以在jsp网页上显示数据呢?来试一下。<%
Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb", "root", "root");

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from new_table");

while (rs.next()) {
com.helloworld.Person person = new com.helloworld.Person();
person.setId(rs.getInt(1));
person.setNation(rs.getString(2));
System.out.println(person.getId());
System.out.println(person.getNation());
%>
结果访问http://localhost:8080/calculateWeb/index.jsp页面报错:
An error occurred at line: 27 in the jsp file: /index.jsp
Connection cannot be resolved to a type
错误显示Connection这个类cannot be resolved to a type识别不了。这里要通过import关键字在jsp中引入Connection所在的包。在index.jsp的第一行,要加入两句import语句。<%@ page language="java" import="java.sql.*"%><%@ page language="java" import="com.helloworld.Person"%>而且Mysql连接的jar包mysql-connector-java-5.1.45-bin.jar也需要导入到Web工程里来,可以直接把这个jar包放在lib目录,比如calculateWeb\WebRoot\WEB-INF\lib目录里面,并要重启一下Tomcat服务器。
另外,Person类也要在calculateWeb这个工程里,所以在calculateWeb工程里面,右键点击src,选择新建New,选择包Package,包名定义为com.helloworld。在这个包里面,再新建Person类。
同时,jsp里面也要把Person类引入<%@ page language="java" import="com.helloworld.Person"%>。如果不加这句引入Person,也可以用包名加类名来使用类。
为了让这段代码能在jsp中显示,需要稍作修改。<%
Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb", "root", "root");

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from new_table");

while (rs.next()) {
com.helloworld.Person person = new com.helloworld.Person();
person.setId(rs.getInt(1));
person.setNation(rs.getString(2));
System.out.println(person.getId());
System.out.println(person.getNation());
%>
<%=person.getId() %>
<%=person.getNation() %>
<%}%>这样再访问index.jsp就可以看到数据库的记录值已经显示在网页上了。
要注意的是,通常不建议在jsp里面直接写入Java代码,如果使用Servlet或Web框架,就可以把Java代码从jsp中移出来。本节只是做一个显示,作为前面的总结应用。
题外话:在jsp网页上使用这种<%=value%>来显示Java变量的数据,其实和很多动态网页技术相类似。比如asp也是使用<%=value%>,而php是使用的形式。可见,很多语言的语法相互借鉴,学过一门计算机语言,对其他类似的计算机语言很容易明白过来。



具有OCR和ASR功能,可以识别图片和录音中文字,并有多国语言翻译功能,可以作为便签或笔记,类似微博的图文应用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐