Java+myeclipse+tomcat (iv) servlet submission forms and database operations

Source: Internet
Author: User
Tags getmessage java web

the previous three articles describe how to configure MyEclipse and Tomcat to develop JSP Web sites, how to configure a servlet to implement form submissions simply, and how to configure MySQL to implement JSP database queries.
This article focuses on the submission of servlet forms, the implementation of database query operations in Java, and the bottlenecks and understandings you encounter. Java Web Basic article, I hope to help you ~
Java+myeclipse+tomcat (i) Introduction to the configuration process and JSP Web site development
Java+myeclipse+tomcat (ii) Configuring the servlet and simply implementing the form submission
Java+myeclipse+tomcat (c) Configure MySQL and query data to be displayed in the JSP Web page
Two items free (hope to help you):

one. servlet form submission

Create a new Web project with the project name TestServlet01. The project structure looks like this:

then modify the index.jsp code as follows:
<%@ 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" >the effect is as follows:
Core Code:
<form action= "/testservlet01/servlet/postservlet" method= "POST" >
Departure: <input type= "text" id= "Start" name= "Start" style= ' font-size:18px '/>
<input type= "Submit" Name= "select" value= "Submit Information"/>
</form>
Then right-click on the SRC to add the package named Servlet, and then add the servlet file, file name Postservlet.java. Select the icon. The previous article described the manual configuration of the servlet, including the servlet class, mapping, and so on, and now it automatically generates the Webroot/web-inf/web.xml file as follows:
<?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 EE component</description> <display-name>this is the display Name of my EE component</display-name> <servlet-name>PostServlet</servlet-name> <servlet-cla Ss>servlet. postservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>postservlet</ Servlet-name> <url-pattern>/servlet/PostServlet</url-pattern> </servlet-mapping> < Welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app >
while modifying the Src/servlet/postservlet.java file, use the Post method to display the form data:
Package Servlet;import Java.io.ioexception;import Java.io.printwriter;import javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Postservlet extends HttpServlet {public postservlet () {super ();} public void Destroy () {Super.destroy (),//Just puts "destroy" string in log//Put your code here}public void doget (httpse Rvletrequest request, HttpServletResponse response) throws Servletexception, IOException {response.setcontenttype (" Text/html "); PrintWriter out = Response.getwriter (); Out.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > ") out.println (" <HTML> "); Out.println (" < Head><title>a servlet</title>The effect is as follows:


two. servlet database query

Or use the above project to modify, implement the Servlet database query operation. Database configuration can refer to the previous blog configuration MySQL process, I create a new database test01, insert table train, table data such as:

then modify the index.jsp code as follows:
<%@ 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" >        modified Postservlet.java code as follows: 
Package Servlet;import Java.io.ioexception;import Java.io.printwriter;import java.sql.connection;import Java.sql.drivermanager;import Java.sql.resultset;import Java.sql.sqlexception;import Java.sql.Statement;import Javax.servlet.servletconfig;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class PostServlet Extends HttpServlet {//Custom variable private Connection Connection = null;//define database Connection object Private String drivername = "Com.mysql.jdbc. Driver "; Database Drive Private String userName = "root"; Database user name private String userpasswd = "123456"; Password private String dbName = "test01"; Database name private String tableName = "Train";                Indicates//connection string database address URL MySQL database port 3306private String url = "jdbc:mysql://localhost:3306/" + DbName + "? user=" + UserName + "&password=" + userpasswd;//initialization method public void init (ServletConfig config) throws servletexception{ Super.init (config);} Public PostServlet () {super ();} Handle GET Request method public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexception{response.setcharacterencoding ("UTF-8");//Set Output code request.setcharacterencoding ("UTF-8");  Response.setcontenttype ("text/html"); Set Output type PrintWriter out = Response.getwriter (); Gets the Out object try {//Database operation Class.forName (drivername). newinstance (); connection = drivermanager.getconnection (URL); Statement Statement = Connection.createstatement (); String StartName = Request.getparameter ("Start"); Get the origin//Note: StartName need to add single quotation mark otherwise error--Errors: Unknown column ' Beijing ' in ' WHERE clause ' String sql = "SELECT * from" + tableName + "WHERE startname= '" + startname+ "';"; if (startname== "") {sql = "select * from" + tableName;} ResultSet rs = statement.executequery (SQL); Out.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > ") out.println (" <HTML> "); Out.println (" < Head><title>a servlet</title>At the same time, Webroot/web-inf/web.xml file servlet mapping has not changed, need to add Mysql-connector-java-5.1.15-bin.jar in Webroot/web-inf/lib, otherwise will be error " Com.mysql.jdbc.Driver error ".
The effect is as follows:




Writing here I have a question about two ways to get the results of a database when the form submits information:
1. The first is written in the previous blog, in the JSP through the <% ....%> call Java code to implement the connection database, the MySQL table to obtain data and display;
2. The second is written in this blog, in the JSP through the Post method to submit form form, in Java through the servlet GET request/response, and then through Java out.println ("
In terms of these two methods, I want to implement the function is: JSP assignment layout, display interface, Java is responsible for connecting the database, database additions and deletions, processing results are returned to the JSP display, rather than nested each other. In other words: In the JSP, click the "Submit" button, the TextBox to pass the origin, Java describes the request, the database query, the resulting results are returned to the JSP display.
How does that make it? The following articles may be covered.
DAO and Java beans are the most effective two methods for layering and modularity of JDBC. DAO (database operand, db Access object) is a common pattern under JDBC, and before DAO appears, the code that operates the database and the business code appear in the servlet or JSP, without the separation of business code. When DAO appears, all database-related operations are taken to the DAO layer implementation, and the servlet or JSP only operates the Java bean or DAP layer, while the DAO layer value operates the database.

PS: I am very glad that I have found this difficulty through the actual project, and then found the solution. Although learning the Java web for a week, still learned a lot of things. Personal feeling DAO is similar to middleware stuff!Finally, I hope the article will help you, this article is about the servlet connection MySQL database and form interaction between the knowledge. If the article has insufficient or wrong place, also please Haihan! Next article talk about the session and a typical simple interface layout and other related knowledge!
        (By:eastmount 2015-5-15 midnight 1. )http://blog.csdn.net/eastmount/)



Java+myeclipse+tomcat (iv) servlet submission forms and database operations

Related Article

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.