Basic steps of Web database login

Logic of thinking:

1. Layout the login page, which sets the form to submit to the servlet class in a better way to post.
2. The servlet class obtains the content of the request body (parameter content)
3. Setting up and verifying the content of receiving parameters of database verification class
	1. Using JdbcTemplate to simplify development details requires setting up JavaBean entity classes
	2. The Druid database connection pool tool class provides access to DataSource, and the Connection method gives the JDBCTemplate class
	3.Druid uses static code blocks to complete configuration and generate DataSource class objects
 4. Verify that the results are true or false, using requests within the server to forward to other servlet classes
 5. Other servlet classes set response and write information to each other

Basic steps:

first:

1. Simplify bootstrap development. (css,fonts,js folders should be placed under WebContent[html also exists here])
	Then the basic framework is used for form layout, and the css is also used for assistant style layout.
	The action of the form is introduced into the servlet on the Tomcat server, and the method is set to post.
	Then complete the layout of login.html

login.html

(Be careful: 
 action="http://localhost:8080/WebServlet/RequestDemo1"
	:RequestDemo1 by WebServlet Engineering servlet class
		//And annotated as @WebServlet("/RequestDemo1")
)			


<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above three meta Label*Must*Put it first, anything else*Must*Follow it! -->
    <title>Bootstrap 101 Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">


    <style type="text/css">
    .place{
    	font-size: 30px;
    	border: 2px solid black;
    	padding-top: 100px;
    	padding-bottom: 100px;
    }
    .form-group{
    	align-content: center;
    	margin-top: 40px;
    }
    .login{font-size: 25px;}
    </style>
    


	<!-- HTML5 shim and Respond.js For the sake of making IE8 Support HTML5 Element and Media Query( media queries)function -->
    <!-- Warning: Pass file:// Respond.js doesn't work when the protocol (that is, dragging html pages directly into the browser) accesses the page - >
    <!--[if lt IE 9]>
      <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <form action="http://localhost:8080/WebServlet/RequestDemo1" class = "form-horizontal place"  method = "post">
		<div class="form-group">
			<label for = "user"  class = "col-sm-5 control-label" >Sign in:</label>
			<div class = "col-sm-5">
			<input id = "user" name = "username" placeholder="enter one user name"></input>
			</div>
	 	</div>	
	  <div class="form-group">
			<label for = "pwd" class = "col-sm-5 control-label">Password:</label> 
			<div class = "col-sm-5">
				<input id = "pwd" type = "password" name = "password" placeholder="Input password"></input>
			</div>
	  </div>
	  
   		<div class = "col-sm-5 form-group"> </div>
   		<button type="submit" class="btn btn-danger col-sm-3 login" >Sign in</button>
	</form>
	
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <!-- Load Bootstrap All JavaScript Plug-in unit. You can also load only a single plug-in as needed. -->
    <script src="../js/bootstrap.min.js"></script>
  </body>
</html>

second:

2. Complete the creation and insertion of database tables and table data, and set the JavaBean entity class User
	The member variables should correspond to the data in the database table one by one.

mysql_code:

CREATE TABLE  IF NOT EXISTS userinfo (
	username VARCHAR(20) PRIMARY KEY,
	PASSWORD VARCHAR(20) NOT NULL,
	loggingTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO UserInfo (username,PASSWORD) VALUES ("Li Bai",123456);
INSERT INTO UserInfo (username,PASSWORD) VALUES ("Du Fu",123456);
SELECT * FROM UserInfo;

JavaBean Entity Class Requirements:

1. Classes are modified with public	
2. Having a parametric constructor
 3. Membership variables are modified with private	
4. There are Getter and Setter methods for member methods
 JavaBean properties:
	Remove the set,get capitalizes the rest of the initials as JavaBean attributes

User

public class User{
	private String username;
	private String password;
	private Timestamp loggingTime;
	public User(String username, String password,Timestamp loggingTime) {
		this.username = username;
		this.password = password;
		this.loggingTime = loggingTime;
	}
	public User() {
		super();
	}
	public Timestamp getLoggingTime() {
		return loggingTime;
	}
	public void setLoggingTime(Timestamp loggingTime) {
		this.loggingTime = loggingTime;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", loggingTime=" + loggingTime + "]";
	}
}

third:

3. Import a series of jar packages under WebContent/WEB-INF/lib in the current project to assist JdbcTemplate.
	Druid.properties(Druid configuration file) is placed under src
	Complete the static configuration of Druid tool class and complete the method of obtaining DataSource.
	Used to provide JdbcTemplate objects

jar

	commons-beanutils-1.8.0.jar
	commons-logging-1.2.jar
	druid-1.0.13.jar
	mysql-connector-java-8.0.16.jar
	spring-beans-5.0.0.RELEASE.jar
	spring-core-5.0.0.RELEASE.jar
	spring-jdbc-5.0.0.RELEASE.jar
	spring-tx-5.0.0.RELEASE.jar	

Druid.properties

	driverClassName = com.mysql.cj.jdbc.Driver
	url = jdbc:mysql://localhost:3306/db1?useSSL=false&serverTimezone=UTC
	username = root
	password = 123456
	initialSize = 5
	maxActive = 10
	maxWait = 3000

Druid Tool Class

(For auxiliary purposes only JdbcTemplate,No need to write close Release of resources and other methods,
					//But set up the static configuration and get the DataSource method)

public class SQLDruidHelp {
	private static DataSource dSource ;
	static {
		try {
			ClassLoader cLoader = SQLDruidHelp.class.getClassLoader();
			InputStream resourceAsStream = cLoader.getResourceAsStream("druid.properties");
			Properties properties = new Properties();
			properties.load(resourceAsStream);
			dSource =  DruidDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static DataSource getDataSource() {
		return dSource;
	}
}

fourth:

4. Through the JdbcTemplate class, the implementation method completes the query to the database by using the User object parameters correctly or not.

JDBCLogCheck

(Be careful:JdbcTemplate Object creation passes the third step Druid Tool class getDataSource())

public class JDBCLogCheck {
	public static boolean checkInfo(User user) {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(SQLDruidHelp.getDataSource());
		String sql = "select * from userInfo where username = ? && password = ?";
		List<User> lists = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class),user.getUsername(),user.getPassword());
		if(lists.size() > 0 ) {
			return true;
		}
		return false;
	}
}

fifth:

5. Implement the form submission servlet on login.html to get the username and password submitted by the page	
	JavaBean entity class: User user = new User();  
	Map :			request.getParameterMap();
Use: BeanUtils.populate(user, map);
		setter() that automatically executes each parameter internally
 Finally, use the JDBCLogCheck test class completed in the fourth step to verify the User class object.
	If it exists, the Username data is shared, so it is set to request.setAttribute.
				And forward the request to the "/successdemo"servlet class
	If not, the request is forwarded to the "/faildemo"servlet class

RequestDemo1

@WebServlet("/RequestDemo1")
public class RequestDemo1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		User user = new User();
		Map<String, String[]> map = request.getParameterMap();
			try {
				BeanUtils.populate(user, map);
			} catch (IllegalAccessException | InvocationTargetException e) {
				
				e.printStackTrace();
			}
		
		boolean flag = JDBCLogCheck.checkInfo(user);
		if(flag) {
			request.setAttribute("username",user.getUsername());
			request.getRequestDispatcher("/successdemo").forward(request, response);
			
		}else {
			request.getRequestDispatcher("/faildemo").forward(request, response);
		}
	}

}

sixth:

Implement the'/ successdemo'and'/ faildemo' servlet classes in step 5.
Complete the entry into the doPost method under the doGet method, because the request forwarded is equivalent to the doGet method to another servlet class
 Subsequently, under the doPost method, the text type of the response header of the response Reponse object is set up, and the information is simply output.
	(where sucessdemo also gets the shared data username on request for reponse output)

faildemo

@WebServlet("/faildemo")
public class faildemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("Unmatchable password and username");
	}
}

successdemo

@WebServlet("/successdemo")
public class successdemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("Welcome members:"+request.getAttribute("username")+"  You have landed successfully!");
	}
}

Keywords: Druid Database Spring npm

Added by KPH71 on Wed, 28 Aug 2019 06:32:28 +0300