A simple small program to get data into a database from a Web page

Source: Internet
Author: User
Tags stub

1. Database new table: Student_information, three fields in table, name (nvarchar (), null), sex (nvarchar (), null), age (numeric (18,0), NULL)

2. Create a new main.jsp first.

<%@ 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><Metahttp-equiv= "Content-type"content= "text/html; charset=iso-8859-1"><title>Insert Title here</title></Head><Body><formAction= "Employeservlet"Method= "POST">  <H1Align= "Center"ID= "Biaotou"> Increase Student Information</H1>  <TableAlign= "Center">    <TR>        <TD>Name:<TD>        <TD><inputtype= "text"name= "Emplyname"value=""/></TD>    <TR>     <TR>        <TD>Gender:</TD>        <TD><inputtype= "Radio"name= "Sex"value= "Male">male<inputtype= "Radio"name= "Sex"value= "female">female</TD>    </TR>    <TR>        <TD>Age:<TD>        <TD><inputtype= "text"name= "Age"value=""/></TD>    <TR>     <TR>        <TD><TD>        <TD><Buttontype= "Submit"value= "Submit">Submit</Button></TD>    <TR>   </Table></form></Body></HTML>

3. Create a new employ class that holds student attributes

Package Testjsp;public class Employ {private string name;private  string sex;private  int age;      public void  SetName (String name) {     this.name=name;    }    Public String GetName () {    return this.name;    }    public void  setsex (String sex) {     this.sex=sex;    }    Public String Getsex () {    return this.sex;    }    public void Setage (int.) {    this.age=age;    }    public int getage () {    return this.age;    }    }

4. Create a new testjsp class, get the data, connect to the database, insert the data

 Packagetestjsp;Importjava.io.IOException;Importjava.sql.Connection;ImportJava.sql.Driver;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;Importjava.sql.SQLException;Importjavax.servlet.ServletException;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importtest. Employeservlet; Public classtestjsp { Public BooleanAddemploy (employ ee) {System.out.println (Ee.getname ());       System.out.println (Ee.getsex ());       System.out.println (Ee.getage ()); String a=Ee.getname (); String b=Ee.getsex (); intC=Ee.getage (); System.out.println (A+b+c); String URL= "Jdbc:sqlserver://localhost:1433;databasename=test_cal"; String USER= "SA"; String PASSWORD= "XXXXXX"; Connection Conn=NULL; PreparedStatement pstmt=NULL; Try{           //Load DriverClass.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); //get a database connectionconn=(Connection) drivermanager.getconnection (Url,user,password);           SYSTEM.OUT.PRINTLN (conn); String SQL= "INSERT into student_information (name,sex,age) VALUES (?,?,?)"; Pstmt=conn.preparestatement (SQL); Pstmt.setstring (1, Ee.getname ()); Pstmt.setstring (2, Ee.getsex ()); Pstmt.setint (3, Ee.getage ());       Pstmt.execute (); }Catch(ClassNotFoundException e) {e.printstacktrace (); }Catch(SQLException e) {e.printstacktrace (); }                          return true; }    Public Static voidMain (string[] args) {//testjsp n=new testjsp (); //N.addemploy ();}}

5. Create a new servlet class

 Packagetest;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importtestjsp. employ;Importtestjsp. testjsp;/*** Servlet Implementation class Employeservlet*/@WebServlet ("/employeservlet") Public classEmployeservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; /**     * @seeHttpservlet#httpservlet ()*/     PublicEmployeservlet () {Super(); //TODO auto-generated Constructor stub    }    /**     * @seeHttpservlet#doget (httpservletrequest request, httpservletresponse response)*/    protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stub//response.getwriter (). Append ("Served at:"). Append (Request.getcontextpath ());    }    /**     * @seeHttpservlet#dopost (httpservletrequest request, httpservletresponse response)*/     Public voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stubdoget (request, response); Request.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8"); //string Name=new string (Request.getparameter ("Emplyname"). GetBytes ("Iso-8859-1"), "Utf-8 ");//Found the answer, do not know how to useString name=request.getparameter ("Emplyname"); String Sex=request.getparameter ("Sex"); String Age=request.getparameter ("Age"); Employ EM=Newemploy ();         Em.setname (name);         Em.setsex (Sex);                  Em.setage (Integer.parseint (age));         SYSTEM.OUT.PRINTLN (name);         SYSTEM.OUT.PRINTLN (Sex);                  System.out.println (Integer.parseint (age)); testjsp te=Newtestjsp ();            Te.addemploy (EM); }  }

6. Create a new Web. xml

<?xml version= "1.0" encoding= "UTF-8"?>
<web-app>

<welcome-file-list>
<welcome-file>MainPage.jsp</welcome-file>
</welcome-file-list>
<servlet>
<!--servlet name, must be consistent with Servlet-name in servlet-mapping--
<servlet-name>EmployeServlet</servlet-name>
<!--the location of the servlet class--
<servlet-class>test. Employeservlet</servlet-class>
</servlet>
<servlet-mapping>
<!--the servlet name, which must be the same as the servlet-name above--
<servlet-name>EmployeServlet</servlet-name>

<url-pattern>/EmployeServlet/</url-pattern>
</servlet-mapping>
</web-app>

A simple small program to get data into a database from a Web page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.