一 JSP连接MySQL数据库
<%@page language="java" pageEncoding="gb2312"%>
<%@page import="java.util.*"%>
<%@page import="com.mysql.jdbc.Driver"%>
<%@page import="java.sql.*"%>
<%@page import="com.mysql.jdbc.ResultSetMetaData"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
/** 链接数据库参数 **/
String driverName = "com.mysql.jdbc.Driver"; //驱动名称
String DBUser = "root"; //mysql用户名
String DBPasswd = "111111"; //mysql密码
String DBName = "short_message"; //数据库名
//数据库完整链接地址
String connUrl = "jdbc:mysql://localhost/" + DBName + "?user="
+ DBUser + "&password=" + DBPasswd;
//加载数据库驱动
Class.forName(driverName).newInstance();
//链接数据库并保存到 conn 变量中
Connection conn = DriverManager.getConnection(connUrl);
//申明~?
Statement stmt = conn.createStatement();
//设置字符集
stmt.executeQuery("SET NAMES UTF8");
//要执行的 sql 查询
//String sql = "SELECT idsend,numbersend,timesend,contentsend FROM sendmessage ORDER BY add_time DESC LIMIT 15";
String sql = "SELECT idsend,numbersend,timesend,contentsend FROM sendmessage ORDER BY idsend";
//取得结果
ResultSet rs = stmt.executeQuery(sql);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base href="<%=basePath%>">
<title>Jsp链接mysql数据库测试</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<table align="center" cellpadding="1" cellspacing="1">
<tr style="font-weight: bold;">
<td width="5%">短信Id</td>
<td width="5%">发送号码</td>
<td width="5%">发送时间</td>
<td width="40%">发送内容</td>
</tr>
<%
/** 打印结果 **/
while (rs.next()) {
%>
<tr>
<td width="5%"><%=rs.getString("idsend") %></td>
<td width="5%"><%=rs.getString("numbersend") %></td>
<td width="5%"><%=rs.getString("timesend") %></td>
<td width="40%"><%=rs.getString("contentsend") %></td>
<!--out.println("<td>"+rst.getFloat("price")+"</td>");-->
</tr>
<%
}
%>
</table>
</body>
</html>
<%
/** 关闭连接 **/
conn.close();
stmt.close();
rs.close();
%>
二 添加数据
要说明的是:数据库中id一定要注意设置为自动增加;否则,操作数据库很有可能出现问题,这个是要非常注意的问题。
方法1:
<%@ page import="java.sql.*" %>
<HTML>
<HEAD>
<TITLE>add message into table </TITLE>
</HEAD>
<BODY>
<%
String name=request.getParameter("name");
String mail=request.getParameter("mail");
String title=request.getParameter("title");
String content=request.getParameter("content");
if(name==null)
name="";
if(title==null)
title="";
if(content==null)
content="";
if(mail==null)
mail="";
//System.out.println(title + "::::" + content);
if(name.length()==0)
out.println("留言人姓名不能为空!");
else if(title.length()==0)
out.println("留言主题不能为空!");
else if(content.length()==0)
out.println("留言内容不能为空!");
else
{
java.util.Date date=new java.util.Date();
String datetime=new Timestamp(date.getTime()).toString();
try
{
/** 链接数据库参数 **/
String driverName = "com.mysql.jdbc.Driver"; //驱动名称
String DBUser = "root"; //mysql用户名
String DBPasswd = "111111"; //mysql密码
String DBName = "jspmessage"; //数据库名
//数据库完整链接地址
String connUrl = "jdbc:mysql://localhost/" + DBName + "?user="
+ DBUser + "&password=" + DBPasswd;
//加载数据库驱动
Class.forName(driverName).newInstance();
//链接数据库并保存到 conn 变量中
Connection con = DriverManager.getConnection(connUrl);
//申明~?
Statement stmt = con.createStatement();
//设置字符集
stmt.executeQuery("SET NAMES UTF8");
PreparedStatement stm = con.prepareStatement("insert into message(title,name,time,content,mail) values(?,?,?,?,?)");
//String sql = "insert into message(title,name,mail,time,content) values('title','name','mail','datetime','content')";
//PreparedStatement stm = con.prepareStatement(sql);
stm.setString(1,title);
stm.setString(2,name);
stm.setString(3,datetime);
stm.setString(4,content);
if(mail.length()==0)
stm.setString(5,null);
else
stm.setString(5,mail);
try
{
stm.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
}
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
%>
<jsp:forward page="view_message.jsp" />
<%
}
%>
</body>
</html>
方法二:
<%@ page import="java.sql.*" %>
<HTML>
<HEAD>
<TITLE>add message into table </TITLE>
</HEAD>
<BODY>
<%
String name=request.getParameter("name");
String mail=request.getParameter("mail");
String title=request.getParameter("title");
String content=request.getParameter("content");
if(name==null)
name="";
if(title==null)
title="";
if(content==null)
content="";
if(mail==null)
mail="";
//System.out.println(title + "::::" + content);
if(name.length()==0)
out.println("留言人姓名不能为空!");
else if(title.length()==0)
out.println("留言主题不能为空!");
else if(content.length()==0)
out.println("留言内容不能为空!");
else
{
java.util.Date date=new java.util.Date();
String datetime=new Timestamp(date.getTime()).toString();
try
{
/** 链接数据库参数 **/
String driverName = "com.mysql.jdbc.Driver"; //驱动名称
String DBUser = "root"; //mysql用户名
String DBPasswd = "111111"; //mysql密码
String DBName = "jspmessage"; //数据库名
//数据库完整链接地址
String connUrl = "jdbc:mysql://localhost/" + DBName + "?user="
+ DBUser + "&password=" + DBPasswd;
//加载数据库驱动
Class.forName(driverName).newInstance();
//链接数据库并保存到 conn 变量中
Connection con = DriverManager.getConnection(connUrl);
String sql = "insert into message(id,title,name,mail,time,content) values(null,'"+title+"','"+name+"','"+mail+"','"+datetime+"','"+content+"')";
PreparedStatement stmt = con.prepareStatement(sql);
try
{
stmt.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
}
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
%>
<jsp:forward page="view_message.jsp" />
<%
}
%>
</body>
</html>
三 数据的现实
说明:从数据库里面读取数据,并且显示出来。
<!--view_message.jsp-->
<%@ page import="java.sql.*" %>
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<TITLE> show the message in the table </TITLE>
</HEAD>
<BODY>
<p align="center">所有访客留言</p>
<hr>
<%
try
{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//String url="jdbc:odbc:user_db";
/** 链接数据库参数 **/
String driverName = "com.mysql.jdbc.Driver"; //驱动名称
String DBUser = "root"; //mysql用户名
String DBPasswd = "111111"; //mysql密码
String DBName = "jspmessage"; //数据库名
//数据库完整链接地址
String connUrl = "jdbc:mysql://localhost/" + DBName + "?user="
+ DBUser + "&password=" + DBPasswd;
//加载数据库驱动
Class.forName(driverName).newInstance();
//链接数据库并保存到 conn 变量中
Connection con = DriverManager.getConnection(connUrl);
//申明~?
//Statement stmt = conn.createStatement();
//Connection con=DriverManager.getConnection(url,"insher","insher");
Statement stm=con.createStatement();
//设置字符集
stm.executeQuery("SET NAMES gb2312");
ResultSet result=stm.executeQuery("select count(*) from message");
int message_count=0;
if(result.next())
{
message_count=result.getInt(1);
result.close();
}
if(message_count>0)
{
result=stm.executeQuery("select * from message order by time desc");
while(result.next())
{
String title=result.getString("title");
String name=result.getString("name");
String mail=result.getString("mail");
Timestamp time=result.getTimestamp("time");
Date date_time=new Date(time.getTime());
Time time_time=new Time(time.getTime());
String content=result.getString("content");
%>
<TABLE width="100%" align="center" border=1 cellspacing="0" cellpadding="0" bordercolordark="#000000" bordercolorlight="#88a6dd">
<tr><td bgcolor="#88a6dd"><font size=2>主题:</font></td>
<td colspan=3><%=title%></td></tr>
<tr><td bgcolor="#88a6dd"><font size=2>留言人:</font></td>
<td><%=name%></td><td bgcolor="#88a6dd"><font size=2>E-mail:</font></td>
<td>
<%
out.println("<a href=mailto:"+mail+">"+mail+"</a>");
%>
</td></tr>
<tr><td bgcolor="#88a6dd"><font size=2>留言时间:</font></td><td colspan=3>
<%
out.println("<font size=2>"+date_time+" "+time_time+"</font>");
%>
</td></tr>
<tr><td align="center">
<%
out.println("("+message_count+")");
%>
</td>
<td colspan=3><%=content%>
</td></tr>
</table>
<%
out.println("<hr>");
message_count--;
}
result.close();
con.close();
}
else
{
out.println("目前还没有任何留言!");
con.close();
}
} catch(Exception e)
{out.println(e);}
%>
<p align="center"><a href="index.jsp">我要留言</a></p>
</body>
</html>
四 基础的jsp页面消息处理
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
out.println("hello " + path);
out.println("world" + basePath);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login2.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<BODY bgcolor="cyan">
<Font size=1 >
<%!
Hashtable hashtable=new Hashtable();
public synchronized void putString(String s)
{
hashtable.put(s,s);
}
%>
<%
String person_name = request.getParameter("name"),
name_found=null;
if(person_name==null){
person_name="";
}
//byte b[]=person_name.getBytes("ISO-8859-1");
byte b[] = person_name.getBytes("utf-8");
person_name = new String(b);
name_found = (String)hashtable.get(person_name);
if(name_found == null)
{
String person_email = request.getParameter("address");
if(person_email == null)
{
person_email = "";
}
StringTokenizer fenxi = new StringTokenizer(person_email," @");
int n = fenxi.countTokens();
if(n >= 3){
out.print("<BR>"+"你输入的Email有不合法字符");
}
else{
putString(person_name);
out.print("<BR>"+"您已经注册成功");
out.print("<BR>"+"您注册的名字是"+person_name);
out.print("<BR>"+"您注册的邮箱是"+person_email);
}
}
else
{
out.print("<BR>"+"该名字已经存在,请您换个名字");
}
%>
</FONT>
"This is my JSP page. hello world !<br>
<%
for(int i = 0;i < 10 ;i ++)
{
out.println(i);
out.println("hello world!<br>");
}
int j =0;
while(true)
{
j++;
out.println(j);
if(j == 10)
break;
}
%>
<% Date date=new Date();
%>
<BR>
<%=date%>
<p>sin(0.9)除以3等于<%=Math.signum(0.9)/3 %></p>
<p>3的平方是:<%=Math.pow(3,2)%></p>
<P> 5的平方根等于<%=Math.sqrt(5)%> </P>
<p><%=getServletInfo()%></p>
<p><% String s=getServletInfo();
out.print("<BR>"+s);%></p>
<BR>获取客户的
IP地址:
<% String IP=request.getRemoteAddr();
out.println(IP);
%>
<BR>获取客户机的名称:
<% String clientName=request.getRemoteHost();
out.println(clientName);
%>
<BR>获取服务器的名称:
<% String serverName=request.getServerName();
out.println(serverName);
%>
<BR>获取服务器的端口号:
<% int serverPort=request.getServerPort();
out.println(serverPort);
%>
<BR>获取客户端提交的所有参数的名字:
</BODY>
</HTML>
待续。。。