Java Web login and Java Web login

Source: Internet
Author: User

Java Web login and Java Web login

First, we need the basic process of logging on to JavaWeb: send a request on the JSP page --> Servlet obtains data from the database by calling the method and returns the result to the page.

We first create three jsp pages, including login. jsp (login page), index. jsp (display information after successful login), error. jsp (logon Failure page), the content of the last two pages can be freely written, while login. the main content of the jsp page is as follows:

1 <form action = "LoginServlet" method = "post"> 2 userName: <input type = "text" name = "userName"/> 3 password: <input type = "password" name = "password"/> 4 <input type = "submit" value = "submit"/> 5 </form>

At the beginning of the login. jsp file, we need to change pageEncoding = "ISO-8859-1" to pageEncoding = "UTF-8" (and do not forget to set the encoding format of the development tool, otherwise the jsp page will display garbled characters)

Based on the username and password attributes, create an object class and add the get and set methods. The Code is as follows:

 1 public class User { 2     private String userName; 3     private String password; 4     public String getUserName() { 5         return userName; 6     } 7     public void setUserName(String userName) { 8         this.userName = userName; 9     }10     public String getPassword() {11         return password;12     }13     public void setPassword(String password) {14         this.password = password;15     }16 }

The action = "LoginServlet" in the jsp page refers to sending requests to the Servlet for processing. Next we will go to Servlet for processing:

1 import java. io. IOException; 2 3 import javax. servlet. servletException; 4 import javax. servlet. http. httpServlet; 5 import javax. servlet. http. httpServletRequest; 6 import javax. servlet. http. httpServletResponse; 7 8 import com. test. dao. userDao; 9 // Servlet instead of Class at creation, which must be in the web. configure in xml. The configured code Myeclipse will automatically generate 10 public class LoginServlet extends HttpServlet {11 // create the UserDao object to facilitate query database 12 UserDao userDao = new UserDao (); 13 // The following doGet and doPost Methods correspond to method = "get" and method = "post" 14 public void doGet (HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException {16} 17 public void doPost (HttpServletRequest request, HttpServletResponse response) 18 throws ServletException, IOException {19 // get the value entered in the foreground text box using the getParameter method, the content in the brackets is the name attribute 20 String userName = request in the <input/> label. getParameter ("userName"); 21 String password = request. getParameter ("password"); 22 // call the getSelect method in UserDao and obtain the return value 23 boolean flag = userDao. getSelect (userName, password); 24 // if the user name and password exist, it is forwarded to index. jsp page, otherwise redirect to error. jsp page 25 if (flag) {26 request. getRequestDispatcher ("index. jsp "). forward (request, response); 27} 28 else29 response. sendRedirect ("error. jsp "); 30} 31 32}

The comments have already been quite clear, so we will not repeat them any more. You can check lines 26th and 29, of which 26 are forwarding and 29 are redirection, interested partners can check the differences between the two. The rest is the database query operation we mentioned earlier. We called the database in line 23. The following describes how to call the database query operation:

1 package com. test. dao; 2 3 import java. SQL. connection; 4 import java. SQL. driverManager; 5 import java. SQL. preparedStatement; 6 import java. SQL. resultSet; 7 8 public class UserDao {9 // code 10 public Connection getCon () {11 // database Connection name 12 String username = "root "; 13 // database connection password 14 String password = ""; 15 String driver = "com. mysql. jdbc. driver "; 16 // Where test is the database name 17 String url =" jdbc: mysql: // localhost: 3306/test "; 18 Connection conn = null; 19 try {20 Class. forName (driver); 21 conn = (Connection) DriverManager. getConnection (url, username, password); 22} catch (Exception e) {23 e. printStackTrace (); 24} 25 return conn; 26} 27 // query method. If any data that meets the conditions is found, true28 public boolean getSelect (String userName, String password) is returned) {29 boolean flag = false; 30 String SQL = "select * from user where userName = '" + userName + "' and password = '" + password + "'"; 31 Connection conn = getCon (); 32 PreparedStatement pst = null; 33 try {34 pst = (PreparedStatement) conn. prepareStatement (SQL); 35 ResultSet rs = pst.exe cuteQuery (); 36 if (rs. next () {37 flag = true; 38} 39} catch (Exception e) {40} 41 return flag; 42} 43}

In this method, we first connect to the database, and then input the userName and password obtained from the jsp page in the query method to determine whether the user name and password exist in the database, if yes, true is returned; otherwise, false is returned (do not forget to import the database link package ).

The fields in the database can be created by referring to the object class User, that is, the attributes userName and password are included. If there is still a problem with the database link, please refer to the previous articles about the database.

Finally, let's take a look at the configuration in web. xml:

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3   <servlet> 4     <servlet-name>LoginServlet</servlet-name> 5     <servlet-class>com.test.servlet.LoginServlet</servlet-class> 6   </servlet> 7  8   <servlet-mapping> 9     <servlet-name>LoginServlet</servlet-name>10     <url-pattern>/LoginServlet</url-pattern>11   </servlet-mapping>12 </web-app>

<Servlet-name> in <servlet> can be written at will. You only need to ensure that the upper and lower parts are the same.

Then, the <servlet-class> is the Servlet Path (including the package name) defined by myself, and the last is <url-pattern>. The content can also be written at will, however, the action attribute of the form on the jsp page must be the same as this name (the action does not contain "/")

Finally, we need to publish the web Project to tomcat and enter http: // localhost: 8080/project name/login. jsp in the browser to access and log in.

This is just a simple application. The purpose is to help you understand the basic process of jsp + servlet development. Of course, we will perform more refined segmentation during actual development, including interfaces, implementation class.

I hope you can study hard and learn from each other every day !! (Study hard and make progress every day !!)

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.