Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the function of user logging in and connecting to database with JSP

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to achieve the function of JSP to log in and connect to the database". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Catalogue

Details about JSP users logging in to the database

1. First create the po class

2. Create the underlying UserDao

3. Create a UserService (UserDao is usually called)

4. Write web layer UserSrevlet

4.1 rewriting method

4.2 create a vo layer and create a ResultInfo class in it to encapsulate the returned data

5. Start writing from Dao

6. Start writing service layer

7. Write the final Servelt layer

7.1 user login

8. Example

Details about JSP users logging in to the database

1. First create the po class

Correspond to the database one by one

Lombok generating get set method

Package com.ftzlover.demo.po;import lombok.Getter;import lombok.Setter;@Getter@Setterpublic class User {private Integer userId; / / user ID private String uname; / / user name private String upwd; / / user password private String nick; / / user nickname private String head; / / user avatar private String mood; / / user signature} 2, create the underlying UserDao

Here are all the layers that have been created

3. Create a UserService (UserDao is usually called)

Private UserDao userDao = new UserDao ()

4. Write web layer UserSrevlet

Note:

First you need to write @ WebServlet ("/ user") at the top

Next, let it call the service layer private UserService userService = new UserService ()

Then let this class inherit HttpServlet

Public class UserServlet extends HttpServlet {

4.1 rewrite method @ Override protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {4.2 create a vo layer and create a ResultInfo class in it to encapsulate the returned data

Create status code code prompt message return object

@ Getter@Setterpublic class ResultInfo {private Integer code; / / status code success = 1, failure = 0 private String msg; / / prompt message private T result; / / returned objects (string, JavaBean, collection, Map, etc.)} 5, start writing from Dao

Dao layer: (data access layer: add, delete, modify and query operations in the database) query user objects through user names and return user objects

Get database connection

Define sql statement

Pre-compilation

Set parameters

Execute the query and return the result set

Judge and analyze the result set

Close the resource

Package com.ftzlover.demo.dao;import com.ftzlover.demo.po.User;import com.ftzlover.demo.util.DBUtil;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;/** * Dao layer: (data access layer: add, delete, modify and query operations in the database) * query the user object through the user name and return the user object * 1. Get database connection * 2. Define sql statement * 3. Pre-compiled * 4. Set parameter * 5. Execute the query and return the result set * 6. Judge and analyze the result set * 7. Close the resource * / public class UserDao {public User queryUserByName (String userName) {/ / first create the object User user = null; Connection connection = null; PreparedStatement preparedStatement = null; / / precompiled object ResultSet resultSet = null; try {/ / 1. Get the database connection connection = DBUtil.getConnetion (); / / 2. Define the sql statement String sql = "select * from tb_user where uname =?"; / / 3. Precompiled preparedStatement = connection.prepareStatement (sql); / / 4. Set the parameter preparedStatement.setString (1, userName); / / 5. Execute the query and return the result set resultSet = preparedStatement.executeQuery (); / / 6. Judge and analyze the result set if (resultSet.next ()) {user = new User (); user.setUserId (resultSet.getInt ("userId")); user.setUname (userName); user.setHead (resultSet.getString ("head")); user.setMood (resultSet.getString ("mood")) User.setNick (resultSet.getString ("nick")); user.setUpwd (resultSet.getString ("upwd"));} catch (Exception e) {e.printStackTrace ();} finally {/ / 7. Close the resource DBUtil.close (resultSet,preparedStatement,connection);} return user;}} 6 and start writing the service layer

Package com.ftzlover.demo.service;import cn.hutool.core.util.StrUtil;import cn.hutool.crypto.digest.DigestUtil;import com.ftzlover.demo.dao.UserDao;import com.ftzlover.demo.po.User;import com.ftzlover.demo.vo.ResultInfo;/*Service layer: (business logic layer: parameter judgment, business logic processing) 1. Determine whether the parameter is empty. If empty, set the status code and prompt of the ResultInfo object to return resultInfo object 2. If it is not empty, query user object 3. 0 by user name. Determine whether the user object is empty. If empty, set the status code and prompt of the ResultInfo object to return resultInfo object 4. 0. If the user object is not empty, compare the password of the user object queried in the database with the password passed by the foreground (encrypt the password and then compare it) if the password does not set the status code and prompt information of the ResultInfo object correctly, return resultInfo object 5. If the password correctly sets the status code and prompt message of the ResultInfo object 6. Return resultInfo object * / public class UserService {private UserDao userDao = new UserDao (); public ResultInfo userLogin (String userName,String userPwd) {ResultInfo resultInfo = new ResultInfo (); / / data echo: when login is implemented, the login information is returned to the page to display User u = new User (); u.setUname (userName); u.setUpwd (userPwd) / / set to resultInfo.setResult (u) in the resultInfo object; / / 1. Determine whether the parameter is empty if (StrUtil.isBlank (userName) | | StrUtil.isBlank (userPwd)) {/ / if empty set the status code and prompt message of the ResultInfo object resultInfo.setCode (0); resultInfo.setMsg ("user name or password cannot be empty!") ; / / return resultInfo object return resultInfo;} / / 2. If it is not empty, query the user object User user = userDao.queryUserByName (userName) by user name; / / 3. Determine whether the user object is empty if (user = = null) {/ / if it is empty, set the status code and prompt message resultInfo.setCode (0) of the ResultInfo object; resultInfo.setMsg ("this user does not exist!") ; / / returns the resultInfo object return resultInfo;} / / 4. If the user object is not empty, compare the password of the user object queried in the database with the password passed by the foreground (encrypt the password and then compare it) / / encrypt the password passed by the foreground userPwd = DigestUtil.md5Hex (userPwd) according to the MD5 algorithm / / determine whether the encrypted password is consistent with the if (! userPwd.equals (user.getUpwd ()) in the database) {/ / if the password is incorrect resultInfo.setCode (0); resultInfo.setMsg ("incorrect user password!") ; return resultInfo;} resultInfo.setCode (1); resultInfo.setResult (user); return resultInfo;}} 7, write the final Servelt layer

7.1 user login

Package com.ftzlover.demo.web;import com.ftzlover.demo.po.User;import com.ftzlover.demo.service.UserService;import com.ftzlover.demo.vo.ResultInfo;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet ("/ user") public class UserServlet extends HttpServlet {private UserService userService = new UserService () @ Override protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/ / receive user behavior String actionName = request.getParameter ("actionName"); if ("login" .equals (actionName)) {/ / user login userLogin (request, response);}} / * * user login 1. Get parameter (name, password) 2. Call the method of the Service layer and return ResultInfo object 3. 0. Determine whether the login is successful if the resultInfo object is set to the request scope and the request is forwarded to the login page if the user information is successfully set to the session scope to determine whether the user chooses to remember the password (the value of rem is 1) if yes, save the user name and password in cookie and set the expiration time And respond to the client if no, clear the original cookie object redirect to the index page * @ param request * @ param response * / private void userLogin (HttpServletRequest request, HttpServletResponse response) {/ / 1. Get parameters (name, password) String userName = request.getParameter ("userName"); String userPwd = request.getParameter ("userPwd"); / / 2. Call the method of the Service layer and return the ResultInfo object ResultInfo resultInfo = userService.userLogin (userName, userPwd); / / 3. Determine whether the login is successful if (resultInfo.getCode () = 1) {/ / if successful / / set the user information to the session scope request.getSession () .setAttribute ("user", resultInfo.getResult ()); / / determine whether the user chooses to remember the password (the value of rem is 1) String rem = request.getParameter ("rem") / / if yes, save the user name and password in cookie, set the expiration time, and respond to the client if ("1" .equals (rem)) {/ / get the Cookie object Cookie cookie = new Cookie ("user", userName + "-" + userPwd) / / set the expiration time cookie.setMaxAge (3: 24: 60: 60); / / respond to the client response.addCookie (cookie);} else {/ / if not, clear the original cookie object Cookie cookie = new Cookie ("user", null) / / delete cookie and set maxage to 0 cookie.setMaxAge (0); / / respond to client response.addCookie (cookie);} / / Redirect to index page try {response.sendRedirect ("index.html") } catch (IOException e) {e.printStackTrace ();}} else {/ / failed / / set the resultInfo object to request.setAttribute in the request scope ("resultInfo", resultInfo) / / request forwarding jumps to login page try {request.getRequestDispatcher ("login.jsp") .forward (request, response);} catch (ServletException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}

Attachment: DBUtil of util layer

Package com.ftzlover.demo.util;import java.io.InputStream;import java.sql.*;import java.util.Properties;public class DBUtil {/ / get the configuration file object private static Properties properties = new Properties (); static {try {/ / load the configuration file (input stream) InputStream in = DBUtil.class.getClassLoader () .getResourceAsStream ("db.properties") System.out.println ("get stream object:" + in); System.out.println ("stream object:" + properties); / / load the contents of the input stream into the configuration file object through the load () method properties.load (in) / obtain the driver name through the getProperty () method of the configuration file object, and load the driver Class.forName (properties.getProperty ("jdbcName"));} catch (Exception e) {e.printStackTrace ();}} public static Connection getConnetion () {Connection connection = null Try {/ / get information about database connection String dbUrl = properties.getProperty ("dbUrl"); System.out.println (dbUrl); String dbName = properties.getProperty ("dbName"); System.out.println (dbName); String dbPwd = properties.getProperty ("dbPwd"); System.out.println (dbName) / / get the database connection connection = DriverManager.getConnection (dbUrl, dbName, dbPwd); System.out.println (connection);} catch (SQLException throwables) {throwables.printStackTrace ();} return connection } public static void close (ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {try {/ / determines that if the resource object is not empty, close if (resultSet! = null) {resultSet.close () } if (preparedStatement! = null) {preparedStatement.close ();} if (connection! = null) {connection.close ();}} catch (Exception e) {e.printStackTrace ();} 8, example

Very cool login interface plus perfect background login interface screenshot:

Database code: the new database is called my and the table name is tb_user.

CREATE TABLE `User` (`userId` int (11) NOT NULL AUTO_INCREMENT COMMENT 'primary key, auto-growth', `uname` varchar (50) NOT NULL COMMENT 'username', `upwd` varchar (50) DEFAULT NULL COMMENT 'password', `nick`varchar (50) DEFAULT NULL COMMENT 'nickname', `head`varchar (100) DEFAULT NULL COMMENT 'avatar', `mood` varchar (500) DEFAULT NULL COMMENT 'mood', PRIMARY KEY (`userId`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 This is the end of the content of "how JSP enables users to log in and connect to the database". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report