Web项目创建,JSP文件创建、发布和访问,在我的博客
JSP学习(一)
中已经详细介绍,而MySQL数据库的连接在JSP学习(二)
中也有详细介绍,在此我就不再赘述。
一、单词检索条件输入网页
检索的项目主要为首字母检索和词性检索。比如:检索以a开头的英文词汇,或者检索词性为名词n.的英文词汇。
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index</title>
</head>
<body bgcolor="#f0ffff">
<form action="vocabulary.jsp" method="POST"><!-- 完成检索后跳转至“词汇表”页面 -->
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<h1 align="center" id="biaotoucolor">单词检索</h1><!-- 添加标题 -->
<table align="center"><!-- 设置输入框位置为居中 -->
<tr>
<td>首字母:</td><!-- 添加“首字母”输入框 -->
<td><input type="text" name="Initial"/></td>
</tr>
<tr>
<td>词性:</td><!-- 添加“词性”输入框 -->
<td><input type="text" name="Pos"/></td>
</tr>
</table>
<table align="center">
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<td><input type="submit" value="检索"/></td><!-- 设置提交按钮 -->
</table>
</form>
</body>
</html>
二、单词检索、检索结果显示网页
每次检索的条件可以为单一条件也可以为多重条件,程序根据检索页面提交的检索条件对MySQL数据库的表vocabulary
中的内容进行筛选,将符合检索条件的英文词汇输出在JSP网页上。vocabulary.jsp
文件中包含MySQL-JDBC驱动程序,英文词汇输出,检索则主要通过SELECT语句完成。
MySQL数据库中的表vocabulary:
vocabulary.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.mysql.jdbc.Driver" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>vocabulary</title>
</head>
<body bgcolor="#f0ffff">
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<h1 align="center" id="biaotoucolor">检索结果</h1>
<%
//加载驱动程序
String driverName="com.mysql.jdbc.Driver";
//数据库信息
String userName="root";
//密码
String userPasswd="yle30268";
//数据库名
String dbName="tables";
//表名
%>
<table align="center" border="2">
<tr>
<td width="100" english="title">英文</td><!-- 设置词汇表格式 -->
<td width="100" pos="title">词性</td>
<td width="100" chinese="title">中文</td>
</tr>
<%
String url="jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn=DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String initial = request.getParameter("Initial");//获取JSP页面输入的内容
String pos = request.getParameter("Pos");
String sql="SELECT * FROM vocabulary WHERE initial like '%"+initial+"%' and pos like '%"+pos+"%'";//SELECT检索
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
%>
<tr><!-- 英文词汇输出 -->
<td width="100"><%=rs.getString("english") %></td>
<td width="100"><%=rs.getString("pos") %></td>
<td width="100"><%=rs.getString("chinese") %></td>
</tr>
<%
}
%>
</table>
</body>
</html>
检索演示: