code070.java
package pack02;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//SaveServlet��
@WebServlet(name = "code070",urlPatterns = "/page04/code070")
public class code070 extends HttpServlet
{
private Connection conn = null;
@Override
public void init(ServletConfig config) throws ServletException
{
//��ʼ��ʱ�������ݿ⽨������
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "mysql123";
try
{
Class.forName(driver);
this.conn = DriverManager.getConnection(url,user,password);
if (this.conn != null)
{
System.out.println("���ݿ����ӳɹ���");
}
} catch (Exception e)
{
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String userName = request.getParameter("userName");
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
String description = request.getParameter("description");
if (conn != null)
{
try
{
String sql = "insert into user(user_name,password,sex,description)"
+ "values(?,?,?,?)";
PreparedStatement param = conn.prepareStatement(sql);
param.setString(1, userName);
param.setString(2, pwd);
param.setString(3, sex);
param.setString(4, description);
param.executeUpdate();
PrintWriter writer1 = response.getWriter();
writer1.print("<h1>");
writer1.print(userName + "ע��ɹ�");
writer1.print("</h1>");
writer1.flush();
writer1.close();
conn.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
else
{
response.sendError(500,"���ݿ����Ӵ���");
}
}
}
/*
*servlet3.0������
*����ע����servlet3.0���ش����֮һ��
*ͨ��ʹ��ע�;�������web.xml�ļ��ж�servlet���߹�����
*���������ˡ�
*����ע����@WebServlet��@WebFilter��@WebListener��@WebInitParam
*
* @WebServlet���������£�
* name string �ȼ���<servlet-name>
* value string[] �ȼ��� urlPatterns ����������ͬʱʹ��
* urlPatterns string[] �ȼ���<url-pattern>
* loadOnStartup int �ȼ���<load-on-startup>
* initParams WebInitParam[] �ȼ���<init-param>
* asyncSupported boolean �ȼ���<async-supported>
* description sring �ȼ���<description>
* displayName string �ȼ���<display-name>
*/