要实现将jsp中数据添加到数据库并刷新页面可以使用servlet来做中间件,进行数据库的插入操作。
具体示例代码如下:
jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="/demoServlet" method="post">
<input type="text" name="num"/><br/>
<input type="text" name="name"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
servlet类:
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn = null;
PreparedStatement pstmt = null;
String num = request.getParameter("num");
String name = request.getParameter("name");
try{
String sql="insert into student values(?,?)";
// conn=jdbcTool.getConnection();//获取连接(工具类)
pstmt=conn.prepareStatement(sql);
pstmt.setString(1,num);
pstmt.setString(2,name);
pstmt.executeUpdate();//执行插入
}
catch(Exception e ){
System.out.println(e.toString());
}finally{
jdbcTool.free(null, pstmt, conn);//关闭连接(工具类)
}
request.getRequestDispatcher("/demo.jsp").forward(request, response);//重新跳转到本页面(刷新页面)
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
点击提交按钮后,表单提交,调用doPost方法,执行操作,最后通过转发跳转会原来的界面。