Struts Operation Database - a simple example

xiaoxiao2021-03-06  43

Some basic steps for database programming:

Registration driver

Create a database connection

Execute SQL statement get the result

Some basic classes to use

CONNECTION Class

Statement class and PeparedStatement classes

Resultset class

Need to pay attention

When the database operation, it will appear, pay attention to capture and process.

Use the following code to explain the driver of the database (hereinafter given below is to connect the ODBC database)

String striver = "sun.jdbc.odbc.jdbcodbcdriver"; // Define the URL of the data (name)

String strConnection = "jdbc: odbc: myFirstData"; // user name data access String strConnectUsername = ""; // password for database access String strConnectPassword = ""; Connection conn = null; Statement stmt = null; ResultSet rs = null String SQL_TEMP = "Select * from tablename" try {

Class.forName (strDriver); // Register drive} catch (ClassNotFoundException ex1) {ex1.printStackTrace (); // capture driver registration process anomalies obtained} try {// database connection conn = DriverManager.getConnection (strConnection, strConnectUsername , strConnectPassword); stmt = conn.CreateStatement (); // create a Statement object stmtrs = stmt.executeQuery (sql_temp); // stmt using SQL operations to return a result set rs} catch (SQLException ex2) {ex2.printStackTrace ();

Come an example to explain how? Function Description Write a user login program, the user enters the password, click the "Login" button, find it in the user data sheet, if there is a corresponding record, tell: Hello, welcome you! If there is no user, it will be prompted: the username or password is incorrect, please re-login. Wow, I finally went to write a little person to touch the dog-like program. I used to call the procedure before, it is simply the name of the three-structured structure to deceive people. . .

Create a database: In order to simply use Access to build one, the name of the database is User, set it in ODBC. What, don't know how to set it? Oh, I really don't have a mood to explain with you. Please solve this problem and look down.

Create a data table: useertable

User number Userno text

User password Password text

The department number DEPARTNO text

Fill in a few values

111 111 001

222 222 002

333 333 003 Landing JSP (I am afraid I will tell you how to write such JSP)

Login.jsp

<% @ Page ContentType = "text / html; charset = GB2312"%>

<% @ Taglib Uri = "/ Web-INF / STRUTS-TILES.TLD" prefix = "tiles"%>

<% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%>

<% @ Taglib URI = "/ Web-INF / STRUTS-LOGIC.TLD" prefix = "logic"%>

<% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%>

login </ title> <center> <pre> <html: form action = "execute.do" method = "post"> <h3> Please enter </ h3> User Name: <HTML : Text Property = "UserID" size = "12" /> Password: <html: Text Property = "Password" size = "12" /> <html: submit value = "Submit" /> <html: reset value = "Reset" /> </ html: form> </ pre> </ center> </ html: html></p> <p>Page Success.jsp displaying the correct result</p> <p><% @ page contenttype = "text / html; charset = GB2312"%> <center> welcome you! ! </ center> prompts to warned the page</p> <p>Error.jsp</p> <p><% @ page contenttype = "text / html; charset = GB2312"%> <center> Don't mean, your username or password is incorrect! </ center></p> <p>Ok, let's go to the programmer to do the job, that is, write the Java code.</p> <p>First, don't ask where to write Java code</p> <p>Second, don't ask what way to compile the Java code into class files.</p> <p>Third, don't ask where Java files and class files are placed</p> <p>... I won't answer any more such a problem.</p> <p>Don't forget to import two JAR packages.</p> <p>FORM used to save data</p> <p>Userform.java</p> <p>Import org.apache.struts.action. *;</p> <p>Public Class Userform Extends ActionForm</p> <p>{</p> <p>PRIVATE STRING UserId = NULL;</p> <p>Private string password = null;</p> <p>Public string getUserid () {</p> <p>RETURN UserID == NULL? ": UserId.trim ();</p> <p>Public void setUserid (String UserID) {</p> <p>this. Userid = UserId;</p> <p>}</p> <p>Public string getpassword () {</p> <p>RETURN Password == NULL? ": Password.trim ();</p> <p>}</p> <p>Public void setpassword (string str2) {</p> <p>THIS. Password = password;</p> <p>}</p> <p>}</p> <p>I saw FORM, there is nothing, is some attributes and GET and SET methods about attributes.</p> <p>Action used to process data</p> <p>UserAction.java</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import org.apache.struts.Action.Actionerro;</p> <p>Import org.apache.struts.Action.actionform;</p> <p>Import org.apache.struts.Action.actionForward;</p> <p>Import org.apache.struts.action.actionmapping;</p> <p>Import org.apache.struts.Actions.dispatchaction;</p> <p>Public Class UseerAction Extends Dispatchction</p> <p>{</p> <p>Public ActionForward Execute (ActionMapping Mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>Httpservletresponse response</p> <p>Throws Exception</p> <p>{</p> <p>// Get page form information</p> <p>Userform uform = (userform) Form;</p> <p>/ / Get two data already submitted from the FROM</p> <p>String temp_id = uform. GetUserid ();</p> <p>String Temp_pass = uform. Getpassword ();</p> <p>IF (! "". Equals (TEMP_ID) &&! "" "Equals (TEMP_PASS))</p> <p>{</p> <p>/ / Define the driver of the database (hereinafter given below is to connect the ODBC database)</p> <p>String striver = "sun.jdbc.odbc.jdbcodbcdriver";</p> <p>/ / Define the URL of the database (name)</p> <p>String strconnection = "JDBC: ODBC: User";</p> <p>// Username</p> <p>String strconnectusername = "";</p> <p>// Database Access password</p> <p>String strconnectpassword = ""</p> <p>Connection conn = NULL;</p> <p>Statement Stmt = NULL;</p> <p>ResultSet RS = NULL;</p> <p>String SQL_TEMP = "SELECT * from UserTable Where</p> <p>Userno = '" TEMP_ID "' AND</p> <p>Password = '" TEMP_PASS "' ";</p> <p>Try</p> <p>{</p> <p>Class.Forname (strDriver); // Register Driver}</p> <p>Catch (ClassNotFoundException EX1)</p> <p>{// capture exceptions during the driver registration</p> <p>EX1.PRINTSTACKTRACE ();</p> <p>}</p> <p>Try</p> <p>{</p> <p>Conn = // Get database connections</p> <p>Drivermanager.getConnection (STRCONNECTION,</p> <p>StrConnectusername,</p> <p>StrConnectPassword;</p> <p>// Create a StMT STMT</p> <p>STMT = conn.createstatement ();</p> <p>// Use STMT to perform SQL operation returns to RS</p> <p>RS = stmt.executequery (SQL_TEMP);</p> <p>Catch (SQLEXCEPTION EX2)</p> <p>{</p> <p>EX2.PRINTSTACKTRACE ();</p> <p>}</p> <p>INT TEMP_COUNT = 0;</p> <p>// How many records have been queried from the database through this cycle</p> <p>While (rs.next ())</p> <p>{</p> <p>TEMP_COUNT ;</p> <p>}</p> <p>// If the query has a record, it indicates that the username and password are correct.</p> <p>IF (Temp_count> 0)</p> <p>{</p> <p>Return mapping.findforward ("ok");</p> <p>}</p> <p>Else // If the query is not recorded, indicate the username or password error</p> <p>{</p> <p>Return mapping.findforward ("ERR");</p> <p>}</p> <p>}</p> <p>Else</p> <p>{</p> <p>Return mapping.findforward ("ERR");</p> <p>}</p> <p>}</p> <p>}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-73474.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="73474" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.050</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '8YJqlszK9VpWXn4aXKtYBsbqAPUKRDuVyQ1USomfISNWcoQeyOm4YFNvIuUHfyxf1PfaO2zIkynLyG7PG2Pc1g_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>