第一步:首先進入資料庫,建庫,建表。
第二步:在myeclipse中建立一個web工程,我的就為web01_demo,接著在WebRoot下建立一個add.jsp檔案。
add.jsp的代碼十分簡單:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>My JSP 'add.jsp' starting page</title> </head> <body> <form action="add"> <h4>add employee</h4> name:<input type="text" name="name"><br> salary:<input type="text" name="salary"><br> <input type="submit" value="confirm"> </form> </body></html>
第三步:寫提供服務的Servlet,這裡為AddEmployeeServlet,採取繼承HttpServlet的方式,在web.xml檔案中映射的url為add。
AddEmployeeServlet的代碼如下:
public class AddEmployeeServlet extends HttpServlet {private static final String URL="jdbc:mysql://localhost:3306/exercise";private static final String USER="root";private static final String PASS="mysqladmin";public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException {String name=request.getParameter("name");String salary=request.getParameter("salary");Connection conn=null;PreparedStatement pstmt=null;try {Class.forName("com.mysql.jdbc.Driver");conn=DriverManager.getConnection(URL,USER,PASS);pstmt=conn.prepareStatement("insert into emp(name,salary) values(?,?)");pstmt.setString(1,name);pstmt.setDouble(2,Double.parseDouble(salary));pstmt.executeUpdate();PrintWriter pw=response.getWriter();pw.print("<h3>add success</h3>");} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {pstmt.close();} catch (SQLException e) {e.printStackTrace();}try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}}
第四步:在myeclipse中部署應用web01_demo,接著啟動Tomcat伺服器。
在瀏覽器裡輸入:http://localhost:8080/web01_demo/add.jsp
瀏覽器返回頁面,在表單中輸入姓名和薪水,點擊confirm按鈕,提交,即可將資料寫入exercise資料庫的emp表。