用doPost來接收post傳過來的資料並存入mysql資料庫

李世榮發表於2014-12-02
/*
 * 用doPost來接收post傳過來的資料並存入mysql資料庫
 */
package servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class addTeam extends HttpServlet {
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
request.setCharacterEncoding("GBK");//設定接收的字符集
//接收資料
String name = request.getParameter("name");
String slogan = request.getParameter("slogan");
String leader = request.getParameter("leader");
//儲存到資料庫
Connection cn = null;
PreparedStatement pst = null;

try {
Class.forName("com.mysql.jdbc.Driver");//載入MySQL驅動程式

//建立與資料庫的連線
String url = "jdbc:mysql://localhost:3306/training";
String user = "root";
String password = "jakeyouxiang";
cn = DriverManager.getConnection(url,user,password);

pst = cn.prepareStatement("insert into team(name,slogan,leader) values (?,?,?)"); //建立PreparedStatement物件

//設定資料
pst.setString(1,name);
pst.setString(2,slogan);
pst.setString(3,leader);

pst.executeUpdate(); //向資料庫增加資料

// 通過response向客戶端應答,顯示增加成功
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>增加小組成功</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1 align=center>增加小組成功</h1>");
out.println("<p><a href='../addTeam.html'>繼續增加</a>");
out.println("<a href='viewteams'>顯示小組</a>");
out.println("<a href='../index.html'>返回首頁</a>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
e.printStackTrace();
// 通過response向客戶端應答,顯示增加失敗
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>增加小組失敗</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1 align=center>增加小組失敗</h1>");
out.println("<p><a href='../addTeam.html'>繼續增加</a>");
out.println("<a href='viewteams'>顯示小組</a>");
out.println("<a href='../index.html'>返回首頁</a>");
out.println("</body>");
out.println("</html>");

}
finally {
try {
pst.close();
cn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}

相關文章