preface
In the previous two issues, we completed the creation of Mysql database tables and the design of Html interface. In this issue, we will complete the last part - the design of user login function.
It mainly uses: JDBC, Servlet, Java, object-oriented and other knowledge
Its basic principle: after the login interface is submitted, a servlet applet is used to judge the relevant information submitted by the user, the implementation of the judgment is connected to the database through JDBC, a user class is implemented through Java code, the relevant data information is compared with the content in Mysql database, and the request is forwarded after the judgment is completed; If it is correct to turn to the web page after login, if it fails, turn to the interface with relevant prompts.
text
Java code section:
Ⅰ. User class: corresponding to the information in the database, it is used to store the user information in the request header
public class User {//User class private int id; private String userName; private String userCipher; public User() { } public User(int id, String userName, String userCipher) { this.id = id; this.userName = userName; this.userCipher = userCipher; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserCipher() { return userCipher; } public void setUserCipher(String userCipher) { this.userCipher = userCipher; } @Override public String toString() { return "User{" + "id=" + id + ", userName='" + userName + '\'' + ", userCipher='" + userCipher + '\'' + '}'; } }
Ⅱ. userdao class (login instance class): realize the comparison of user information
import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; public class UserDao { private JdbcTemplate jdbcTemplate = new JdbcTemplate(MyJDBCUtils.getDataSource()); public User login(User loginUser) { try { String sql = "select * from userdata where username = ? and usercipher = ?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUserName(), loginUser.getUserCipher()); return user; } catch (DataAccessException e) { e.printStackTrace(); return null; } } }
Ⅲ. JDBC utils class: realize database connection
import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; //JDBC utils package to simplify the steps of linking database pools public class MyJDBCUtils { private static DataSource dataSource;//Database pool static { try { Properties pro = new Properties();//Get information from file InputStream inputStream=MyJDBCUtils.class.getClassLoader().getResourceAsStream("javaDemo/druid.properties"); pro.load(inputStream); dataSource = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } //Get link public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } //Release resources public static void close(ResultSet resultSet, Connection connection, PreparedStatement preparedStatement) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } //Get database pool public static DataSource getDataSource() { return dataSource; } }
Ⅳ. Test class: used to test whether the database can be successfully connected
import org.junit.Test; import java.lang.annotation.Target; import java.sql.SQLException; public class TestDome { @Test public void testLogin() throws SQLException { User user=new User(); user.setUserName("Xiao Wang"); user.setUserCipher("123456"); UserDao dao=new UserDao(); User nuser =dao.login(user); System.out.println(nuser); } }
Ⅴ. properties configuration file
driverClassName = com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/db_1?&useSSL=false&serverTimezone=UTC&characterEncoding=utf8&characterSetResults=utf8 username=""Your database user name" password=""Your database password" # Number of initialization connections initialSize=5 # maximum connection maxActive=10 # Maximum waiting time (timeout) maxWait=3000
Servlet part:
Ⅰ. Login servlet: used for processing and forwarding user request headers
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(value = "/loginServlet") public class loginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String usercipher = request.getParameter("usercipher"); User loginuser=new User(); loginuser.setUserName(username); loginuser.setUserCipher(usercipher); UserDao dao = new UserDao(); User user = dao.login(loginuser); if (user == null) { request.getRequestDispatcher("/failServlet").forward(request, response); } else { //Save to request field request.setAttribute("user",user); /*Forward to servlet*/ Servletrequest.getRequestDispatcher("/successServlet").forward(request, response); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
Ⅱ. successServlet: status of successful login
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(value = "/successServlet") public class successServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = (User) request.getAttribute("user"); if (user != null) { response.setContentType("text/html;charset=utf-8"); response.getWriter().write("<h1>user" + user.getUserName() + "welcome back</h1>"); response.sendRedirect("/Web_war_exploded/CC-Page.html"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
Ⅲ. failServlet: status of login failure
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(value = "/failServlet") public class failServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.getWriter().write("<h1>Login failed,Wrong user name or password</h1>"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
Package used
Final effect:
epilogue
The above is all the contents of this user login project. In the initial implementation process, we may not be plain sailing. The author has also encountered many thorny problems. However, through the CSDN community, although the process is tortuous, the difficulties are finally successfully solved. In the following articles, the author will also share some common problems in the user's login case and solutions to these problems. Please look forward to it!!!