I. JSP database access method:
1. Create your own virtual directory and create web-inflib, web-infclass, and web-infjar under the virtual directory. The directories are described as follows:
The web-infweb.xml configures access Servlet in this file and configures some initial parameters, for example:
<Servlet>
<Servlet-name> TestServlet </servlet-name> <! -- Servlet name -->
<Servlet-class> com. myweb. TestServlet </servlet-class> <! -- Servlet class name includes package name -->
</Servlet>
<Servlet-mapping>
<Servlet-name> TestServlet </servlet-name> <! -- Servlet name -->
<Url-pattern>/Servlet/TestServlet </url-pattern> <! -- Access the servlet url relative to the root directory -->
</Servlet-mapping>
</Servlet>
Web-inflib is stored in jsp, and the jar accessed by javabean includes some database drivers we use (not supported by java itself, such as mysql ).
Web-infclasses is stored in jsp. The class used in javabean is a class file. If it is a package, you need to store the class according to the package directory.
II. JSP database access problems and solutions:
1. Class cannot be found: The main problem is that the class used is not stored in a proper location, jar is stored in lib, and class files are stored in class.
III. Access database instance: access Mysql through JSP
1. Create the directory test and create the relevant directory below. Web-inf, web-inflib.
2. Configure the virtual directory to point to test.
3. Run mysql-conn. Copy jar to lib.
4. The testdbtext. jsp code is as follows:
<% @ Page language = "java" %>
<% @ Page contentType = "text/html; charset = gb2312" %>
<% @ Page import = "java. SQL. *" %>
<%
Connection sqlConn;
ResultSet sqlRst;
Statement sqlStmt;
String database = "test ";
String user = "root ";
String pass = "123456 ";
Class. forName ("org. gjt. mm. mysql. Driver"). newInstance ();
// Connect to the database
SqlConn = java. SQL. DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/" + database, user, pass );
// Create a statement object
SqlStmt = sqlConn. createStatement ();
// Execute the SQL statement
String sqlQuery = "select * from test ";
SqlRst=sqlStmt.exe cuteQuery (sqlQuery );
While (sqlRst. next ())
{
Out. println (sqlRst. getString (1 ));
Out. println (sqlRst. getString (2 ));
}
%>
Note: To access a database, you must first confirm the corresponding permissions.
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.