项目结构
register.htm和WEB-INF(web.xml lib ( mysql-connector-java-5.1.6-bin.jar) classes(com (db servlet ) DatabaseConnection.java registerServlet.java)
register.htm
<html>
<body>
<font size=20>
<center>
<form action="/test/register" method="post">
用户名:<input type="text" name="name"><br>
年 龄:<input type="text" name="age"><br>
地 址:<input type="text" name="address"><br>
<input type="submit" value=" 注 册 ">
</form>
</center>
</body>
</html>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>aa</servlet-name>
<servlet-class>com.servelet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>aa</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
DatabaseConnection.java
package com.db;
import java.sql.*;
public class DatabaseConnection{
public static Connection getCon(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/oa","root","yu");
}catch(Exception e){e.printStackTrace();}
return con;
}
}
RegisterServlet.java
package com.servelet;
import javax.servlet.*;
import javax.servlet.http.*;
import com.db.*;
import java.sql.*;
import java.io.*;
public class RegisterServlet extends HttpServlet{
/*doPost()Called by the server (via the service method) to allow a servlet to handle a POST request.*/
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
response.setCharacterEncoding("gbk");/*指定对服务器响应进行重新编码的编码。*/
String name=request.getParameter("name");
name=new String(name.getBytes("iso-8859-1"),"gbk");
String age=request.getParameter("age");
String address=request.getParameter("address");
address=new String(address.getBytes("iso-8859-1"),"gbk");
Connection con;
Statement stmt;
String sql="";
try{
con =DatabaseConnection.getCon();
stmt = con.createStatement();//获取编译语句
sql="insert into person(name,age,address)values('"+name+
"','"+age+"','"+address+"')";
stmt.executeUpdate(sql);/*在此 PreparedStatement 对象中执行 SQL 语句,该语句必须是一个 SQL INSERT、UPDATE 或 DELETE 语句*/
response.sendRedirect("/test/register.htm");
con.close();
}catch(Exception e){e.printStackTrace();}//将此 throwable 及其追踪输出至标准错误流
}
/*dopost()便已处理方法,用doGet()方法调用dopost()*/
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
doPost(request,response);
}
}
posted on 2009-05-13 11:45
鹏凌 阅读(175)
评论(0) 编辑 收藏 所属分类:
Java --j2ee