<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${message}<br>
<form action="selectBook" method="get">
书号:<input type="text" name="isbn"><br>
书名:<input type="text" name="title"><br>
价格:<input type="text" name="price"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
package com.yl;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class BookServlet
*/
@WebServlet("/addBook")
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection db=null;
public void init(){
String driver="com.mysql.jdbc.Driver";
String dbur1="jdbc:mysql://127.0.0.1:3306/web?useSSL=true";
String username="root";
String passwd="root";
try{
Class.forName(driver);
db=DriverManager.getConnection(dbur1,username,passwd);
}catch(ClassNotFoundException e){
System.out.println(e);
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String isbn=request.getParameter("isbn");
String title=request.getParameter("title");
float price=Float.parseFloat(request.getParameter("price"));
String message="";
try{
String sql="insert into book value(?,?,?)";
PreparedStatement p=db.prepareStatement(sql);
p.setString(1, isbn);
p.setString(2, title);
p.setFloat(3, price);
int num=p.executeUpdate();
if(num==1){
message="插入记录成功";
}else{
message="插入记录失败";
}
request.setAttribute("message", message);
request.getRequestDispatcher("test4.jsp").forward(request, response);
}catch(SQLException e){
System.out.println(e);
request.setAttribute("message", message);
request.getRequestDispatcher("test4.jsp").forward(request, response);
}
}
}