Data transfer between JSP, Servlet, and SQL (foreground and background data interaction)

Source: Internet
Author: User

Background:

The MVC (Model-view-control) development model, which is popular in the industry, is understood as

The model is a bean,

The view is html/jsp,

Control is a servlet,

DAO for Association Database

The web's operating mechanism:

The data is first displayed on the JSP, the user sees the page triggers some events, and may pass the data, the data and requests are received by the controller, and then start processing (often require some database operations (query, modify database data)), when these processing ends, We need to feed the data back to the JSP to show the user, complete a complete interactive process.

Text:

According to the order in the background, we describe in turn----how to transfer data from the JSP to the servlet and receive it, how to get the database data in the servlet, and how to pass the data within the servlet to the JSP and display it on the Web page.

(i) from JSP to Servlet

1. Send Information

Form submission

HTML code

<form action= "URL" name= "form name" method= "How to submit (post, get{two ways to submit}*)" >

<input type= "text" name= "textbox name"/><!--a text input box--

</form>

Define a function to process the form text box check for non-empty and submit form events

HTML code

<script>
$ (document). Ready (function () {
$ ("#被单击按钮的ID"). Click (function () {
if (document.all. text box name. value.length==0) {
Alert ("Input cannot be empty");
return false;
}
document.all. Form name Submit ();
return true;});
});
</script>

2. Receive information to the servlet file that the URL points to when the form is submitted, and get the parameter values passed in.

Java code

String search = Java.net.URLDecoder.decode (request.getparameter ("text box name"), "Utf-8");
SYSTEM.OUT.PRINTLN ("Search parameter received in the servlet of search"--"+search");

(ii) from servlet to database

1. Get data (MySQL for example)

① Creating a database connection pool

Create a configuration file,

Make sure the name is the same

XML code

<?xml version= "1.0" encoding= "UTF-8"?>
<Context>
<resource name= "Jdbc/lele"
Auth= "Container"
Type= "Javax.sql.DataSource"
Maxactive= "50"
Maxidle= "5"
Maxwait= "10000"
Logabandoned= "true"
Username= ""
Password= ""
Driverclassname= "Com.mysql.jdbc.Driver"
Url= "Jdbc:mysql://localhost:3306/lele"/>
</Context>
<!--Jdbc/lele for project name--

② Getting Links

Java code

public static Connection getconnection () {

Connection con = null; Create a Connection object to connect to the database
DataSource ds = null;
try {

Context initcontext = new InitialContext ();
Context Envcontext = (context) initcontext.lookup ("java:/comp/env");
ds = (DataSource) envcontext.lookup ("Jdbc/lele");
System.out.println (Ds.getconnection ());
} catch (Exception E1) {
SYSTEM.OUT.PRINTLN ("Load Database driver failed" +e1);
return null;
}//load MySQL Data driver
try {
con = ds.getconnection ();//Create a data connection
SYSTEM.OUT.PRINTLN ("Database connection succeeded");
return con; Returns the database connection that was established

} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Database connection Failed" + e.getmessage ());
return null;
}
}

③ executes the SQL statement and returns the result

Java code

/* Query the database to output records that match the requirements */
private static Connection Conn;
private static Statement St;
private static ResultSet Rs;
public static void Main (String [] args) {
Query ("SELECT * from Agreement");
// }
public static ResultSet query (String sql) {
System.out.println ("function Dbquery log");
if (conn = = null) {
conn = Dbconnection.getconnection (); Also, to get the connection first, connect to the database
if (conn = = null) {
SYSTEM.OUT.PRINTLN ("Database connection failed");
return null;
}
}
SYSTEM.OUT.PRINTLN ("Connect to database data successfully in Query function" +conn);

try {
St = (Statement) conn.createstatement (); Create a statement object for executing static SQL statements, ST local variables
rs = (ResultSet) st.executequery (SQL); Executes a SQL query statement that returns the result set of the query data
if (!rs.next ()) {
SYSTEM.OUT.PRINTLN ("Data not queried in the database");
return null;
}
SYSTEM.OUT.PRINTLN ("Data has been queried in the database");
String agreement_id = rs.getstring (1);
String agreement_content = rs.getstring (2);
SYSTEM.OUT.PRINTLN ("Data that has been queried for data is----agreement_id:" +agreement_id+ "\tagreement_content:" +agreement_content);
Return RS;
} catch (SQLException e) {
SYSTEM.OUT.PRINTLN ("Database failed to check data");
return null;
}

}

public static void Closedb () throws sqlexception{
if (null! = RS)
Rs.close ();
if (null! = ST)
St.close ();
if (null! = conn)
Conn.close (); To close a database connection
}

2, processing data (using JavaBean to save data)
Java Code Collection Code
if (rs! = null) {
do{
User User0=new User ();//a JavaBean instantiation object
USER0.SETUSER_ID (rs.getstring ("user_id"));
User0.setuser_name (rs.getstring ("user_name"));
User0.setuser_email (rs.getstring ("User_email"));
User0.setuser_password (rs.getstring ("User_password"));
Collection.add (USER0);
System.out.println (rs.getstring ("user_id"));
System.out.println (rs.getstring ("user_name"));
System.out.println (rs.getstring ("User_email"));
System.out.println (rs.getstring ("User_password"));
}while (Rs.next ());
}

Java code

public class User {
Private String user_id;//User number
Private String user_email;//User zip code
Private String user_name;//User name
Private String user_password;//User password

Public String getuser_id () {
return user_id;
}
public void setuser_id (String userId) {
user_id = userId;
}
Public String Getuser_email () {
return user_email;
}
public void Setuser_email (String useremail) {
User_email = UserEmail;
}
Public String Getuser_name () {
return user_name;
}
public void Setuser_name (String userName) {
user_name = UserName;
}
Public String Getuser_password () {
return user_password;
}
public void Setuser_password (String userpassword) {
User_password = UserPassword;
}
}

(iii) from servlet to JSP

1. Send data

Use redirection to forward request and response to a JSP

Java code

Sending data to a JSP
RequestDispatcher rd = Request.getrequestdispatcher ("index_search.jsp");
Request.setattribute ("Test", collection);//Stored value
Rd.forward (request,response);//Start jump

2. Receive data

Come to the URL to redirect to get the data just sent over and displayed on the page

Java code

Collection<user> collectionuser= (collection<user>) request.getattribute ("test");
Iterator It=collectionuser.iterator ();
while (It.hasnext ())
{
User user= (user) it.next ();
Out.println ("<td ><div align= ' center ' >" +user.getuser_name () + "</td>");
Out.println ("<td ><div align= ' center ' ><a href= ' # ' Onclick=window.open (' myjsp.jsp?usid= ' + USER.GETUSER_ID (). Trim () + "', ' newwindow ', ' width=600,height=350,top=300,left=300 ') > Management </a></td>");
Out.println ("</tr>");
}

Data transfer between JSP, Servlet, and SQL (foreground and background data interaction)

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.