Complete process parsing for JSP + Servlet making Java Web login function, servletjava

Source: Internet
Author: User

Complete process parsing for JSP + Servlet making Java Web login function, servletjava

0. Create a web Project
First, create a java web project named login in MyEclipse. In this case, the project contains a src folder and a WebRoot folder, a jre library folder and a J2EE library folder that comes with Java Web. Where, under the WebRoot folder, contains the WEB-INF folder and an index. jsp page file.
Next, create a new JSP page named login. jsp.
The structure of the project file is as follows:

1. design the login. jsp page
Open the login. jsp page and modify the first line of code to pageEncoding = "UTF-8" to prevent Chinese garbled characters on the page. Next, define the form in the body section for the user to enter the user name and password. The page code is 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"> 

2. Create a servlet File
Next, create a new loginServlet. java in MyEclipse and define it under Package a (the package name is determined by yourself ). The folder directory is as follows:

Double-click to open loginServlet. java file, in the doPost method, through the request. getParameter () method to get the username and password of the login page, and use response. the sendRedirect () method redirects to index. jsp page. The page code is as follows:

Package a; import java. io. IOException; import javax. servlet. servletConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class loginServlet implements javax. servlet. servlet {public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String userName = request. getParameter ("username"); // obtain the username String password = request. getParameter ("password"); // get the password response. sendRedirect ("index. jsp ");} public void destroy () {} public ServletConfig getServletConfig () {return null;} public String getServletInfo () {return null;} public void init (ServletConfig arg0) throws ServletException {} public void service (ServletRequest request, response) throws ServletException, IOException {HttpServletRequest rq = (HttpServletRequest) request; response rs = (response) response; doPost (rq, rs );}}

3. Configure servlet
Open the web. xml file under the WEB-INF folder by setting the home page for this website to login. jsp. Configure the servlet. The page code is as follows:

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5"  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_2_5.xsd"> <servlet><servlet-name>LoginServlet</servlet-name> <servlet-class>a.loginServlet</servlet-class> </servlet>  <servlet-mapping><servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>  <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list></web-app> 

 
4. Test page
Finally, let's take a look at the running effect, select Run, and select a certain version of tomcat to start. The page effect is as follows:

5. Configure the data source
(1) Create a database
Open mysql database, create a database, name it a login database, create a table login in the database, and set the username and password fields. The database design table is as follows:

The id in the table as the primary key makes the database table at least meet the requirements of the second paradigm. the username and password fields are unique fields in the login table, so this table meets the requirements of the third paradigm.
Next, fill in the data in the login table. The data in this example is as follows:

(2) connecting to the database
Connect to the database in MyEclipse. The JDBC driver is loaded to connect to the database. First download the mysql driver, then import the mysql jar package to our project, right-click the JRE system library in the package resource manager, and select the build path-configure build path tab, in the pop-up Java build path tab, use the Add external JAR (X) button to load mysql. jar file.
Next, create the DBUtil. java file in the project to connect to the mysql database. Here, the principle of database connection is omitted. the source code of the DBUtil. java file is as follows. Please change the database name in the source code and the username and password used to connect to mysql:

Package a; import java. SQL. *; public class DBUtil {boolean bInited = false; // load the public void initJDBC () throws ClassNotFoundException {// load the mysql jdbc Driver Class. forName ("com. mysql. jdbc. driver "); bInited = true; System. out. println ("Success loading Mysql Driver! ");} Public Connection getConnection () throws ClassNotFoundException, SQLException {if (! BInited) {initJDBC ();} // The Connection URL is jdbc: mysql // server address/Database Name // the two parameters are respectively the login user name and password Connection conn = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/Database Name", "userName", "password"); return conn;} public boolean loginSuccess (String userName, String password) {boolean returnValue = false; String SQL = "SELECT * FROM login"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try {conn = getConnection (); stmt = conn. createStatement (); rs = stmt.exe cuteQuery (SQL); while (rs. next () {String userNameInDB = rs. getString ("username"); String passwordInDB = rs. getString ("password"); if (userNameInDB. equals (userName) & passwordInDB. equals (password) {returnValue = true; break ;}} catch (ClassNotFoundException e) {e. printStackTrace ();} catch (SQLException e) {e. printStackTrace ();} return returnValue ;}}

In the above loginSuccess () method, it is used to find the matching conditions between the user name and password in the database and the input parameter username and password. Returns true if it is found.

(3) Modifying Servlet business logic
Modify the business logic of the loginServlet. java file and add the statement to connect to the database. The main page Jump logic contains the doPost () method. The modified doPost () method is as follows:

Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String userName = request. getParameter ("username"); // obtain the username String password = request. getParameter ("password"); // obtain the password DBUtil db = new DBUtil (); // construct the database object boolean canLogin = db. loginSuccess (userName, password); if (canLogin) {// jump to the page response according to the login situation. sendRedirect ("index. jsp ");} else {response. sendRedirect ("login. jsp ");}}

(4) test page
After debugging, the page effect is as follows:

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.