java web从网页表单输入数据存储到MySQL数据库

最近做的项目中有一个模块需要填写页面上的表单,然后将表单的内容存入到MySQL数据库,下面将代码贴出来。

  1. 项目结构:
    这里写图片描述
  2. 数据库设计:
    这里写图片描述
    3.各部分代码:
    package com.Interface:
package com.Interface;

import java.sql.Connection;
import java.sql.PreparedStatement;

import com.Util.DbUtil;
import com.model.Literature;

public class LiteratureInterface{
    public boolean addLiterature(Literature literature){
        String ChineseName=literature.getChineseName();
        String EnglishName=literature.getEnglishName();
        String Type=literature.getType();
        String Author=literature.getAuthor();
        String Source=literature.getSource();
        String ChineseAbstract=literature.getChineseAbstract();
        String EnglishAbstract=literature.getEnglishAbstract();
        String ChineseKeyword=literature.getChineseKeyword();
        String EnglishKeyword=literature.getEnglishKeyword();
        String ReforName=literature.getReforName();
        String Incentive=literature.getIncentive();
        String Content=literature.getContent();

        DbUtil db=new DbUtil();
        try {
            String sql="INSERT INTO wenxian(ChineseName,EnglishName,Type,Author,Source,ChineseAbstract,EnglishAbstract,ChineseKeyword,EnglishKeyword,ReforName,Incentive,Content) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
            Connection conn=db.getCon();
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1, ChineseName);
            ps.setString(2, EnglishName);
            ps.setString(3, Type);
            ps.setString(4, Author);
            ps.setString(5, Source);
            ps.setString(6, ChineseAbstract);
            ps.setString(7, EnglishAbstract);
            ps.setString(8, ChineseKeyword);
            ps.setString(9, EnglishKeyword);
            ps.setString(10, ReforName);
            ps.setString(11, Incentive);
            ps.setString(12, Content);
            ps.executeUpdate();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;

    }
}

package com.model:

package com.model;

public class Literature {
    private String ChineseName;
    private String EnglishName;
    private String Type;
    private String Author;
    private String Source;
    private String ChineseAbstract;
    private String EnglishAbstract;
    private String ChineseKeyword;
    private String EnglishKeyword;
    private String ReforName;
    private String Incentive;
    private String Content;
    public String getChineseName() {
        return ChineseName;
    }
    public void setChineseName(String chineseName) {
        ChineseName = chineseName;
    }
    public String getEnglishName() {
        return EnglishName;
    }
    public void setEnglishName(String englishName) {
        EnglishName = englishName;
    }
    public String getAuthor() {
        return Author;
    }
    public void setAuthor(String author) {
        Author = author;
    }
    public String getSource() {
        return Source;
    }
    public void setSource(String source) {
        Source = source;
    }
    public String getChineseAbstract() {
        return ChineseAbstract;
    }
    public void setChineseAbstract(String chineseAbstract) {
        ChineseAbstract = chineseAbstract;
    }
    public String getEnglishAbstract() {
        return EnglishAbstract;
    }
    public void setEnglishAbstract(String englishAbstract) {
        EnglishAbstract = englishAbstract;
    }
    public String getChineseKeyword() {
        return ChineseKeyword;
    }
    public void setChineseKeyword(String chineseKeyword) {
        ChineseKeyword = chineseKeyword;
    }
    public String getEnglishKeyword() {
        return EnglishKeyword;
    }
    public void setEnglishKeyword(String englishKeyword) {
        EnglishKeyword = englishKeyword;
    }
    public String getReforName() {
        return ReforName;
    }
    public void setReforName(String reforName) {
        ReforName = reforName;
    }
    public String getIncentive() {
        return Incentive;
    }
    public void setIncentive(String incentive) {
        Incentive = incentive;
    }
    public String getContent() {
        return Content;
    }
    public void setContent(String content) {
        Content = content;
    }
    public String getType() {
        return Type;
    }
    public void setType(String type) {
        Type = type;
    }

}

package com.Util:

package com.Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

   public class DbUtil {

    private String url="jdbc:mysql://localhost:3306/db-jsp";
    private String user="root";
    private String password="123";
    private String driver="com.mysql.jdbc.Driver";

    public Connection getCon() throws Exception{
                 Class.forName(driver);
                Connection con=DriverManager.getConnection(url, user, password);
                return con;

    }


    public static void getClose(Connection con) throws SQLException{
        if(con!=null){
            con.close();
        }

    }






}

package com.web:

package com.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Interface.LiteratureInterface;
import com.Util.DbUtil;
import com.model.Literature;

public class PublishServlet extends HttpServlet {
    DbUtil db=new DbUtil();

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * Constructor of the object.
     */
    public PublishServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  
        response.setContentType("text/html;charset=UTF-8");

        String ChineseName=request.getParameter("ChineseName");
        String EnglishName=request.getParameter("EnglishName");
        String Type=request.getParameter("Type");
        String Author=request.getParameter("Author");
        String Source=request.getParameter("Source");
        String ChineseAbstract=request.getParameter("ChineseAbstract");
        String EnglishAbstract=request.getParameter("EnglishAbstract");
        String ChineseKeyword=request.getParameter("ChineseKeyword");
        String EnglishKeyword=request.getParameter("EnglishKeyword");
        String ReforName=request.getParameter("ReforName");
        String Incentive=request.getParameter("Incentive");
        String Content=request.getParameter("Content");

        Literature literature=new Literature();
        literature.setChineseName(ChineseName);
        literature.setEnglishName(EnglishName);
        literature.setType(Type);
        literature.setAuthor(Author);
        literature.setSource(Source);
        literature.setChineseAbstract(ChineseAbstract);
        literature.setEnglishAbstract(EnglishAbstract);
        literature.setChineseKeyword(ChineseKeyword);
        literature.setEnglishKeyword(EnglishKeyword);
        literature.setReforName(ReforName);
        literature.setIncentive(Incentive);
        literature.setContent(Content);

        LiteratureInterface literatureInter=new LiteratureInterface();
        literatureInter.addLiterature(literature);

        request.getRequestDispatcher("main.jsp").forward(request, response);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
   <form action="PublishServlet" method="post">
   <table>
       <tr>
          <td>文献中文名称:</td>
          <td><input type="text" name="ChineseName" value="${param.ChineseName}"></td>
       </tr>
       <tr>
          <td>文献英文名称:</td>
          <td><input type="text" name="EnglishName" value="${param.EnglishiName}"></td>
       </tr>
       <tr>
          <td>文献类型:</td>
          <td>
             <select name="Type">
                <option value="">请选择</option>
                <option value="学术论文">学术论文</option>
                <option value="硕士学位论文">硕士学位论文</option>
                <option value="博士学位论文">博士学位论文</option>
                <option value="教材">教材</option>
                <option value="专著">专著</option>
                <option value="网文">网文</option>
                <option value="报告">报告</option>
                <option value="文档">文档</option>
             </select>
          </td>
       </tr>
       <tr>
          <td>作者:</td>
          <td><input type="text" name="Author" value="${param.Author}"></td>
       </tr>
       <tr>
          <td>文献来源:</td>
          <td><input type="text" name="Source" value="${param.Source}"></td>
       </tr>
       <tr>
          <td>中文摘要:</td>
          <td><input type="text" name="ChineseAbstract" value="${param.ChineseAbstract}"></td>
       </tr>
       <tr>
          <td>英文摘要:</td>
          <td><input type="text" name="EnglishAbstract" value="${param.EnglishAbstract}"></td>
       </tr>
       <tr>
          <td>中文关键词:</td>
          <td><input type="text" name="ChineseKeyword" value="${param.ChineseKeyword}"></td>
       </tr>
       <tr>
          <td>英文关键词:</td>
          <td><input type="text" name="EnglishKeyword" value="${param.EnglishKeyword}"></td>
       </tr>
       <tr>
          <td>参考文献:</td>
          <td><input type="text" name="ReforName" value="${param.ReforName}"></td>
       </tr>
       <tr>
          <td>收集动机(因做哪个项目收集此文献):</td>
          <td><input type="text" name="Incentive" value="${param.Incentive}"></td>
       </tr>
       <tr>
          <td>内容:</td>
          <td><textarea name="Content" >${param.Content}</textarea></td>
       </tr>
       <tr>
          <td>
           <input type="submit" value="提交">
          </td>
       </tr>

   </table>

   </form>
  </body>
</html>

main.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'main.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    This is my JSP page. <br>
  </body>
</html>

administrator.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'guanliyuan.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
     <form action="PublishServlet" method="post">
   <table>
       <tr>
          <td>文献中文名称:</td>
          <td><input type="text" name="ChineseName" value="${param.ChineseName}"></td>
       </tr>
       <tr>
          <td>文献英文名称:</td>
          <td><input type="text" name="EnglishName" value="${param.EnglishiName}"></td>
       </tr>
       <tr>
          <td>作者:</td>
          <td><input type="text" name="Author" value="${param.Author}"></td>
       </tr>
       <tr>
          <td>文献来源:</td>
          <td><input type="text" name="Source" value="${param.Source}"></td>
       </tr>
       <tr>
          <td>中文摘要:</td>
          <td><input type="text" name="ChineseAbstract" value="${param.ChineseAbstract}"></td>
       </tr>
       <tr>
          <td>英文摘要:</td>
          <td><input type="text" name="EnglishAbstract" value="${param.EnglishAbstract}"></td>
       </tr>
       <tr>
          <td>中文关键词:</td>
          <td><input type="text" name="ChineseKeyword" value="${param.ChineseKeyword}"></td>
       </tr>
       <tr>
          <td>英文关键词:</td>
          <td><input type="text" name="EnglishKeyword" value="${param.EnglishKeyword}"></td>
       </tr>
       <tr>
          <td>参考文献:</td>
          <td><input type="text" name="ReforName" value="${param.ReforName}"></td>
       </tr>
       <tr>
          <td>收集动机(因做哪个项目收集此文献):</td>
          <td><input type="text" name="Incentive" value="${param.Incentive}"></td>
       </tr>
       <tr>
          <td>内容:</td>
          <td><textarea name="Content" >${param.Content}</textarea></td>
       </tr>
       <tr>
          <td>
           <input type="submit" value="提交">
          </td>
       </tr>

   </table>

   </form>
  </body>
</html>

配置文件web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>PublishServlet</servlet-name>
    <servlet-class>com.web.PublishServlet</servlet-class>
  </servlet>



  <servlet-mapping>
    <servlet-name>PublishServlet</servlet-name>
    <url-pattern>/PublishServlet</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

4.运行项目,首界面:
这里写图片描述
点击提交后,再刷新数据库:
这里写图片描述

  • 33
    点赞
  • 218
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
要在网页输入数据并将其存储数据库中,您需要使用Java Web开发技术,例如Java Servlet和JSP。以下是一些大致的步骤: 1. 创建一个包含表单的JSP页面,该表单将允许用户输入数据。 2. 在JSP页面中使用Java Servlet API创建一个Servlet,该Servlet将接收表单数据。 3. 在Servlet中,使用Java JDBC API连接到数据库并将表单数据插入到数据库中。 下面是一个基本的示例代码,仅供参考: JSP页面代码: ``` <form method="post" action="InsertDataServlet"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <br> <label for="email">Email:</label> <input type="text" id="email" name="email"> <br> <input type="submit" value="Submit"> </form> ``` Java Servlet代码: ``` import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class InsertDataServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取表单数据 String name = request.getParameter("name"); String email = request.getParameter("email"); // 连接到数据库并插入数据 Connection conn = null; PreparedStatement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password"); stmt = conn.prepareStatement("INSERT INTO mytable(name, email) VALUES (?, ?)"); stmt.setString(1, name); stmt.setString(2, email); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) {} try { conn.close(); } catch (Exception e) {} } // 跳转到成功页面 response.sendRedirect("success.jsp"); } } ``` 请注意,此示例代码仅用于说明目的,并且可能需要进行更改以适应您的具体需求。您还应该确保正确配置数据库连接和表单验证以提高安全性。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值