servlet jdbc_Servlet JDBC数据库连接示例

本文档提供了一个完整的Servlet JDBC示例,涵盖了从数据库连接到日志记录的Web应用程序开发。用户可以注册并登录,信息存储在数据库中,使用log4j进行日志记录。教程包括设计决策、数据库设置、HTML页面、部署描述符配置、模型类、上下文监听器、异常处理、过滤器、Servlet类和JSP主页。应用支持会话管理,提供详细的错误处理和日志记录功能。
摘要由CSDN通过智能技术生成

servlet jdbc

Servlet JDBC Database connection and Log4j integration is the topic of this tutorial. We have provided a lot of tutorials on servlets in java, this tutorial is aimed to use all of those information to create a full-fledged web application with database connectivity and log4j integration for logging.

Servlet JDBC数据库连接和Log4j集成是本教程的主题。 我们提供了许多有关Java Servlet的教程,该教程旨在使用所有这些信息来创建具有数据库连接性和log4j集成的完整Web应用程序以进行日志记录。

I strongly recommend to check out following tutorials if you are not familiar with any of these. All of them contains sample project that you can download and run for understanding the core concepts of Servlet API.

如果您不熟悉这些教程,我强烈建议您查看以下教程。 它们全部包含样本项目,您可以下载并运行它们以了解Servlet API的核心概念。

  1. J2EE Web Application Overview

    J2EE Web应用程序概述
  2. Servlet Tutorial for Beginners

    Servlet初学者教程
  3. Session Management in Servlets

    Servlet中的会话管理
  4. Servlet Filter

    Servlet过滤器
  5. Servlet Listener

    Servlet侦听器
  6. Servlet Exception Handling

    Servlet异常处理
  7. Servlet Cookie Example

    Servlet Cookie示例

Servlet JDBC示例 (Servlet JDBC Example)

Develop a web application that should have following features.

开发应具有以下功能的Web应用程序。

  1. User can register and then login to the application.

    用户可以注册,然后登录到该应用程序。
  2. The users information should be maintained in database.

    用户信息应保存在数据库中。
  3. Use standard logging framework log4j.

    使用标准的日志记录框架log4j。
  4. The application should support session management, no JSPs should be visible without session. Users can logout anytime from the application.

    该应用程序应支持会话管理,没有会话的任何JSP都不可见。 用户可以随时从应用程序注销。
  5. We should not show application and server details to user incase of any exception in application or other common errors like 404.

    如果应用程序出现任何异常或其他常见错误(例如404),我们不应向用户显示应用程序和服务器的详细信息。

Once we have our basic application ready, we can move on to add other features.

准备好基本应用程序后,就可以继续添加其他功能。

设计决策 (Design Decisions)

  1. Since login page is the entry point of application, we will have a simple login.html where user can enter their credentials; email and password. We can’t rely on javascript validations, so we will do server side validation and incase of missing information we will redirect user to login page with error details.

    由于登录页面是应用程序的入口点,因此我们将有一个简单的login.html,用户可以在其中输入其凭据; 电子邮件和密码。 我们不能依靠javascript验证,因此我们将进行服务器端验证,如果信息丢失,我们会将用户重定向到带有错误详细信息的登录页面。
  2. We will have a register.html from where user can register to our application, we will provide it’s link in the login page for new user. User should provide email, password, name and country details for registration.

    If any information is missing, user will remain on same page with error message. If registration is successful, user will be forwarded to the login page with registration success information and they can use email and password to login.

    如果缺少任何信息,则用户将停留在同一页上,并显示错误消息。 如果注册成功,用户将被引导到带有注册成功信息的登录页面,他们可以使用电子邮件和密码登录。

  3. We will use MySql database for persisting user information. We will create a new database, user and Users table for our application. Since our application totally depends on Database Connection, we will create a servlet context listener to initialize the database connection and set it as context attribute for other servlets.

    We will keep DB configuration details configurable through deployment descriptor. We will also add MySql Java Connector jar to the application libraries.

    我们将通过部署描述符保持数据库配置细节的可配置性。 我们还将MySql Java Connector jar添加到应用程序库中。

  4. Since we want to use log4j and configure it properly before usage, we will utilize servlet context listener to configure log4j and keep the log4j configuration XML file location in web.xml init parameters. We will write our application logs in a separate log file dbexample.log for easier debugging.

    由于我们要使用log4j并在使用前正确配置它,我们将利用servlet上下文侦听器来配置log4j并将log4j配置XML文件的位置保留在web.xml init参数中。 我们将在单独的日志文件dbexample.log中编写应用程序日志,以便于调试。
  5. Incase of any exceptions like “Database Connection Error” or 404 errors, we want to present a useful page to user. We will utilize servlet exception handling and write our own Exception Handler servlet and configure it in deployment descriptor.

    如果出现“数据库连接错误”或404错误之类的异常,我们希望向用户展示一个有用的页面。 我们将利用servlet异常处理,并编写我们自己的Exception Handler servlet,并在部署描述符中对其进行配置。
  6. Once the user logins successfully, we will create a session for the user and forward them to home.jsp where we will show basic information of the user. We will have a model class User that will store the user data into session. User home page also provide logout button that will invalidate the session and forward them to login page.

    一旦用户成功登录,我们将为该用户创建一个会话并将其转发到home.jsp,其中将显示该用户的基本信息。 我们将有一个模型类User,它将用户数据存储到会话中。 用户主页还提供注销按钮,该按钮将使会话无效并将其转发到登录页面。
  7. We need to make sure all the JSPs and other resources are accessible only when user has a valid session, rather than keeping session validation login in all the resources, we will create a Servlet Filter for session validation and configure it in deployment descriptor.

    我们需要确保仅当用户具有有效的会话时,才能访问所有JSP和其他资源,而不是在所有资源中保留会话验证登录,我们将创建一个用于会话验证的Servlet过滤器,并在部署描述符中对其进行配置。
  8. We will use Servlet 3.0 features for servlet configuration, listeners and filters rather than keeping all of these in deployment descriptor. We will use Eclipse for development and Tomcat 7 for deployment.

    我们将使用Servlet 3.0功能进行Servlet配置,侦听器和过滤器,而不是将所有这些功能都保留在部署描述符中。 我们将使用Eclipse进行开发,并使用Tomcat 7进行部署。

Based on above requirements and design decisions, we will create our dynamic web project whose project structure will look like below image.

基于上述要求和设计决策,我们将创建动态Web项目,其项目结构如下图所示。

Let’s understand each one of the components and understand their implementation.

让我们了解每个组件并了解其实现。

Servlet JDBC示例–数据库设置 (Servlet JDBC Example – Database Setup)

We will use below MySql script for new Database, User and Table setup to be used in our application.

我们将在MySql脚本下面使用新的数据库,用户和表设置,以在我们的应用程序中使用。

-- login with root to create user, DB and table and provide grants
 
create user 'pankaj'@'localhost' identified by 'pankaj123';

grant all on *.* to 'pankaj'@'localhost' identified by 'pankaj123';

create database UserDB;

use UserDB;

CREATE TABLE `Users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '',
  `email` varchar(20) NOT NULL DEFAULT '',
  `country` varchar(20) DEFAULT 'USA',
  `password` varchar(20) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

登录和注册HTML页面 (Login and Registration HTML Pages)

Login and Registration HTML pages are simple pages with form to submit the user information, their code looks like below.

登录和注册HTML页面是简单的页面,具有用于提交用户信息的表单,其代码如下所示。

login.html code:

login.html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Login with email and password</h3>
<form action="Login" method="post">
<strong>User Email</strong>:<input type="text" name="email"><br>
<strong>Password</strong>:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
<br>
If you are new user, please <a href="register.html">register</a>.
</body>
</html>

register.html code:

register.html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Register Page</title>
</head>
<body>
<h3>Provide all the fields for registration.</h3>
<form action="Register" method="post">
<strong>Email ID</strong>:<input type="text" name="email"><br>
<strong>Password</strong>:<input type="password" name="password"><br>
<strong>Name</strong>:<input type="text" name="name"><br>
<strong>Country</strong>:<input type="text" name="country"><br>
<input type="submit" value="Register">
</form>
<br>
If you are registered user, please <a href="login.html">login</a>.
</body>
</html>

部署描述符和log4j配置 (Deployment Descriptor and log4j configuration)

We will have log4j configuration file inside WEB-INF folder and it will be packaged with the application WAR file.

我们将在WEB-INF文件夹中拥有log4j配置文件,它将与应用程序WAR文件打包在一起。

log4j.xml code:

log4j.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="https://jakarta.apache.org/log4j/"
	debug="false">
	<appender name="dbexample" class="org.apache.log4j.RollingFileAppender">
		<param name="File" value="${catalina.home}/logs/dbexample.log"/>
		<param name="Append"            value="true" />
		<param name="ImmediateFlush"    value="true" />
		<param name="MaxFileSize"       value="20MB" />
		<param name="MaxBackupIndex"    value="10" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
		</layout>
	</appender>
	
	<logger name="com.journaldev" additivity="false">
		<level value="DEBUG" />
		<appender-ref ref="dbexample"/>
	</logger>
	
	<root>
		<level value="debug" />
		<appender-ref ref="dbexample" />
	</root>
	
</log4j:configuration>

Our deployment descriptor (web.xml) looks like below.

我们的部署描述符(web.xml)如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ServletDBLog4jExample</display-name>
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>dbUser</param-name>
    <param-value>pankaj</param-value>
  </context-param>
  <context-param>
    <param-name>dbPassword</param-name>
    <param-value>pankaj123</param-value>
  </context-param>
  <context-param>
    <param-name>dbURL</param-name>
    <param-value>jdbc:mysql://localhost:3306/UserDB</param-value>
  </context-param>
  <context-param>
    <param-name>log4j-config</param-name>
    <param-value>WEB-INF/log4j.xml</param-value>
  </context-param>
  
  <error-page>
    <error-code>404</error-code>
    <location>/AppErrorHandler</location>
  </error-page>
  <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/AppErrorHandler</location>
  </error-page>
  
  <filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>com.journaldev.servlet.filters.AuthenticationFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app>

Notice following points in the web.xml configuration.

请注意web.xml配置中的以下几点。

  1. login.html is provided welcome file in the welcome files list.

    在“欢迎文件”列表中提供了login.html欢迎文件。
  2. Database connection parameters are made configurable and kept as servlet context init params.

    数据库连接参数可配置,并作为servlet上下文初始化参数保存。
  3. log4j configuration file location is also configurable and relative location is provided as context init param.

    log4j配置文件的位置也是可配置的,相对位置作为上下文初始化参数提供。
  4. Our custom exception handler servlet AppErrorHandler is configured to handle all the exceptions thrown by our application code and 404 errors.

    我们的自定义异常处理程序Servlet AppErrorHandler已配置为处理应用程序代码和404错误引发的所有异常。
  5. AuthenticationFilter is configured to filter all the incoming requests to the application, this is the place where we will have session validation logic.

    AuthenticationFilter配置为过滤对应用程序的所有传入请求,这是我们拥有会话验证逻辑的地方。

模型类和数据库连接管理器类 (Model Classes and Database Connection Manager Class)

User.java is a simple java bean that will hold the user information as session attribute.

User.java是一个简单的Java Bean,它将用户信息保存为会话属性。

package com.journaldev.util;

import java.io.Serializable;

public class User implements Serializable{
	
	private static final long serialVersionUID = 6297385302078200511L;
	
	private String name;
	private String email;
	private int id;
	private String country;
	
	public User(String nm, String em, String country, int i){
		this.name=nm;
		this.id=i;
		this.country=country;
		this.email=em;
	}

	public void setName(String name) {
		this.name = name;
	}


	public void setEmail(String email) {
		this.email = email;
	}


	public void setId(int id) {
		this.id = id;
	}


	public void setCountry(String country) {
		this.country = country;
	}


	public String getName() {
		return name;
	}

	public String getEmail() {
		return email;
	}

	public int getId() {
		return id;
	}

	public String getCountry() {
		return country;
	}
	
	@Override
	public String toString(){
		return "Name="+this.name+", Email="+this.email+", Country="+this.country;
	}
}

DBConnectionManager.java is the utility class for MySql database connection and it has a method that returns the connection object. We will use this class for database connection and then set the connection object to servlet context attribute that other servlets can use.

DBConnectionManager.java是MySql数据库连接的实用程序类,它具有一个返回连接对象的方法。 我们将使用此类进行数据库连接,然后将连接对象设置为其他servlet可以使用的servlet上下文属性。

package com.journaldev.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnectionManager {

	private Connection connection;
	
	public DBConnectionManager(String dbURL, String user, String pwd) throws ClassNotFoundException, SQLException{
		Class.forName("com.mysql.jdbc.Driver");
		this.connection = DriverManager.getConnection(dbURL, user, pwd);
	}
	
	public Connection getConnection(){
		return this.connection;
	}
}

Servlet JDBC示例–上下文侦听器 (Servlet JDBC Example – Context Listener)

AppContextListener.java is the servlet context listener implementation that will initialize the Database connection when application context is initialized and it also configures the log4j using it’s configuration xml file. Notice the use of context init params for DB connection and log4j configuration.

AppContextListener.java是servlet上下文侦听器实现,它将在初始化应用程序上下文时初始化数据库连接,并且还使用其配置xml文件配置log4j。 注意,将上下文初始化参数用于数据库连接和log4j配置。

When context will be destroyed, we are closing database connection in contextDestroyed() method.

当上下文将被销毁时,我们将在contextDestroyed()方法中关闭数据库连接。

Since we are using Servlet 3, we don’t need to configure it in web.xml and we just need to annotate it with @WebListener annotation.

因为我们使用的是Servlet 3,所以我们不需要在web.xml中对其进行配置,而只需要使用@WebListener注释对其进行注释。

package com.journaldev.servlet.listeners;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

import com.journaldev.util.DBConnectionManager;

@WebListener
public class AppContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent servletContextEvent) {
    	ServletContext ctx = servletContextEvent.getServletContext();
    	
    	//initialize DB Connection
    	String dbURL = ctx.getInitParameter("dbURL");
    	String user = ctx.getInitParameter("dbUser");
    	String pwd = ctx.getInitParameter("dbPassword");
    	
    	try {
			DBConnectionManager connectionManager = new DBConnectionManager(dbURL, user, pwd);
			ctx.setAttribute("DBConnection", connectionManager.getConnection());
			System.out.println("DB Connection initialized successfully.");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	
    	//initialize log4j
    	String log4jConfig = ctx.getInitParameter("log4j-config");
    	if(log4jConfig == null){
    		System.err.println("No log4j-config init param, initializing log4j with BasicConfigurator");
			BasicConfigurator.configure();
    	}else {
			String webAppPath = ctx.getRealPath("/");
			String log4jProp = webAppPath + log4jConfig;
			File log4jConfigFile = new File(log4jProp);
			if (log4jConfigFile.exists()) {
				System.out.println("Initializing log4j with: " + log4jProp);
				DOMConfigurator.configure(log4jProp);
			} else {
				System.err.println(log4jProp + " file not found, initializing log4j with BasicConfigurator");
				BasicConfigurator.configure();
			}
		}
    	System.out.println("log4j configured properly");
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    	Connection con = (Connection) servletContextEvent.getServletContext().getAttribute("DBConnection");
    	try {
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
	
}

异常和错误处理程序 (Exception and Error Handler)

AppErrorHandler.java is our application exception handler servlet configured in deployment descriptor, it provides useful information to the user incase of 404 errors or application level exceptions and provide them hyperlink to go to login page of application.

AppErrorHandler.java是在部署描述符中配置的我们的应用程序异常处理程序servlet,它在出现404错误或应用程序级异常的情况下向用户提供有用的信息,并提供超链接以转到应用程序的登录页面。

package com.journaldev.servlet.errorhandler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/AppErrorHandler")
public class AppErrorHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processError(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processError(request, response);
	}
	
	private void processError(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// Analyze the servlet exception
		Throwable throwable = (Throwable) request
				.getAttribute("javax.servlet.error.exception");
		Integer statusCode = (Integer) request
				.getAttribute("javax.servlet.error.status_code");
		String servletName = (String) request
				.getAttribute("javax.servlet.error.servlet_name");
		if (servletName == null) {
			servletName = "Unknown";
		}
		String requestUri = (String) request
				.getAttribute("javax.servlet.error.request_uri");
		if (requestUri == null) {
			requestUri = "Unknown";
		}
		
		// Set response content type
	      response.setContentType("text/html");
	 
	      PrintWriter out = response.getWriter();
	      out.write("<html><head><title>Exception/Error Details</title></head><body>");
	      if(statusCode != 500){
	    	  out.write("<h3>Error Details</h3>");
	    	  out.write("<strong>Status Code</strong>:"+statusCode+"<br>");
	    	  out.write("<strong>Requested URI</strong>:"+requestUri);
	      }else{
	    	  out.write("<h3>Exception Details</h3>");
	    	  out.write("<ul><li>Servlet Name:"+servletName+"</li>");
	    	  out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
	    	  out.write("<li>Requested URI:"+requestUri+"</li>");
	    	  out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
	    	  out.write("</ul>");
	      }
	      
	      out.write("<br><br>");
	      out.write("<a href=\"login.html\">Login Page</a>");
	      out.write("</body></html>");
	}
}

Servlet过滤器 (Servlet Filter)

AuthenticationFilter.java is our Filter implementation and we are validating user session here.

AuthenticationFilter.java是我们的Filter实现,我们在这里验证用户会话。

package com.journaldev.servlet.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

@WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {

	private Logger logger = Logger.getLogger(AuthenticationFilter.class);
	
	public void init(FilterConfig fConfig) throws ServletException {
		logger.info("AuthenticationFilter initialized");
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		
		String uri = req.getRequestURI();
		logger.info("Requested Resource::"+uri);
		
		HttpSession session = req.getSession(false);
		
		if(session == null && !(uri.endsWith("html") || uri.endsWith("Login") || uri.endsWith("Register"))){
			logger.error("Unauthorized access request");
			res.sendRedirect("login.html");
		}else{
			// pass the request along the filter chain
			chain.doFilter(request, response);
		}	
	}

	public void destroy() {
		//close any resources here
	}
}

Notice the use of @WebFilter annotation, we can also provide URL Patterns for filter here but sometimes it’s good to have in web.xml to easily disable the filters.

请注意,使用@WebFilter批注,我们还可以在此处提供用于过滤器的URL模式,但有时最好在web.xml中轻松禁用过滤器。

Servlet类 (Servlet Classes)

LoginServlet resource is used to validate the user input for login and forward them to home page or incase of missing data, provide useful information to user.

LoginServlet资源用于验证用户的登录信息,并将其转发到主页或数据丢失的情况下,向用户提供有用的信息。

package com.journaldev.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.journaldev.util.User;

@WebServlet(name = "Login", urlPatterns = { "/Login" })
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	static Logger logger = Logger.getLogger(LoginServlet.class);
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String errorMsg = null;
		if(email == null || email.equals("")){
			errorMsg ="User Email can't be null or empty";
		}
		if(password == null || password.equals("")){
			errorMsg = "Password can't be null or empty";
		}
		
		if(errorMsg != null){
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
			PrintWriter out= response.getWriter();
			out.println("<font color=red>"+errorMsg+"</font>");
			rd.include(request, response);
		}else{
		
		Connection con = (Connection) getServletContext().getAttribute("DBConnection");
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = con.prepareStatement("select id, name, email,country from Users where email=? and password=? limit 1");
			ps.setString(1, email);
			ps.setString(2, password);
			rs = ps.executeQuery();
			
			if(rs != null && rs.next()){
				
				User user = new User(rs.getString("name"), rs.getString("email"), rs.getString("country"), rs.getInt("id"));
				logger.info("User found with details="+user);
				HttpSession session = request.getSession();
				session.setAttribute("User", user);
				response.sendRedirect("home.jsp");;
			}else{
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
				PrintWriter out= response.getWriter();
				logger.error("User not found with email="+email);
				out.println("<font color=red>No user found with given email id, please register first.</font>");
				rd.include(request, response);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("Database connection problem");
			throw new ServletException("DB Connection problem.");
		}finally{
			try {
				rs.close();
				ps.close();
			} catch (SQLException e) {
				logger.error("SQLException in closing PreparedStatement or ResultSet");;
			}
			
		}
		}
	}

}

LogoutServlet is simple and invalidates the user session and forward them to login page.

LogoutServlet很简单,它会使用户会话无效并将其转发到登录页面。

package com.journaldev.servlet;

import java.io.IOException;

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 javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

@WebServlet(name = "Logout", urlPatterns = { "/Logout" })
public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static Logger logger = Logger.getLogger(LogoutServlet.class);
       
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("text/html");
    	Cookie[] cookies = request.getCookies();
    	if(cookies != null){
    	for(Cookie cookie : cookies){
    		if(cookie.getName().equals("JSESSIONID")){
    			logger.info("JSESSIONID="+cookie.getValue());
    			break;
    		}
    	}
    	}
    	//invalidate the session if exists
    	HttpSession session = request.getSession(false);
    	logger.info("User="+session.getAttribute("User"));
    	if(session != null){
    		session.invalidate();
    	}
    	response.sendRedirect("login.html");
    }

}

RegisterServlet is used by users to register to the application and then forward them to login page with registration success message.

用户使用RegisterServlet来注册到应用程序,然后将其转发到带有注册成功消息的登录页面。

package com.journaldev.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
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 org.apache.log4j.Logger;

@WebServlet(name = "Register", urlPatterns = { "/Register" })
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	static Logger logger = Logger.getLogger(RegisterServlet.class);
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String country = request.getParameter("country");
		String errorMsg = null;
		if(email == null || email.equals("")){
			errorMsg = "Email ID can't be null or empty.";
		}
		if(password == null || password.equals("")){
			errorMsg = "Password can't be null or empty.";
		}
		if(name == null || name.equals("")){
			errorMsg = "Name can't be null or empty.";
		}
		if(country == null || country.equals("")){
			errorMsg = "Country can't be null or empty.";
		}
		
		if(errorMsg != null){
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/register.html");
			PrintWriter out= response.getWriter();
			out.println("<font color=red>"+errorMsg+"</font>");
			rd.include(request, response);
		}else{
		
		Connection con = (Connection) getServletContext().getAttribute("DBConnection");
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement("insert into Users(name,email,country, password) values (?,?,?,?)");
			ps.setString(1, name);
			ps.setString(2, email);
			ps.setString(3, country);
			ps.setString(4, password);
			
			ps.execute();
			
			logger.info("User registered with email="+email);
			
			//forward to login page to login
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
			PrintWriter out= response.getWriter();
			out.println("<font color=green>Registration successful, please login below.</font>");
			rd.include(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("Database connection problem");
			throw new ServletException("DB Connection problem.");
		}finally{
			try {
				ps.close();
			} catch (SQLException e) {
				logger.error("SQLException in closing PreparedStatement");
			}
		}
		}
		
	}

}

JSP主页 (Home JSP Page)

home.jsp is the home page for user after successful login, we are just showing some user information here and providing them option to logout.

home.jsp是成功登录后用户的主页,我们仅在此处显示一些用户信息,并为他们提供注销选项。

home.jsp code:

home.jsp代码:

<%@page import="com.journaldev.util.User"%>
<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Home Page</title>
</head>
<body>
<%User user = (User) session.getAttribute("User"); %>
<h3>Hi <%=user.getName() %></h3>
<strong>Your Email</strong>: <%=user.getEmail() %><br>
<strong>Your Country</strong>: <%=user.getCountry() %><br>
<br>
<form action="Logout" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>

The JSP page still contains a lot of java code because we are not using JSP tags, we will look into this in JSP tutorials. As of now please bear with this.

JSP页面仍然包含许多Java代码,因为我们没有使用JSP标记,我们将在JSP教程中对此进行研究。 截至目前,请忍受这一点。

运行Servlet JDBC示例应用程序 (Run the Servlet JDBC Example Application)

Our application is ready for execution, I would suggest to export it as WAR file and then deploy to tomcat rather than deploying it directly to Tomcat server from Eclipse so that you can easily look into the log4j log file for debugging.

我们的应用程序可以执行了,我建议将其导出为WAR文件,然后部署到tomcat,而不是将其直接从Eclipse部署到Tomcat服务器,以便您可以轻松地查看log4j日志文件以进行调试。

Some sample execution pages are shown in below images.

下图显示了一些示例执行页面。

User Registration Page:

用户注册页面

Registration Success Page:

注册成功页面

Login Page:

登录页面

User Home Page:

用户主页

404 Error Page:

404错误页面

Input Validation Error Page:

输入验证错误页面

log4j Log File:

log4j日志文件

dbexample.log:

dbexample.log:

0    [localhost-startStop-1] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - AuthenticationFilter initialized
1    [localhost-startStop-1] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - AuthenticationFilter initialized
37689 [http-bio-8080-exec-3] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/
37689 [http-bio-8080-exec-3] ERROR com.journaldev.servlet.filters.AuthenticationFilter  - Unauthorized access request
37693 [http-bio-8080-exec-4] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/login.html
51844 [http-bio-8080-exec-5] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/register.html
77818 [http-bio-8080-exec-7] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Login
77835 [http-bio-8080-exec-7] INFO  com.journaldev.servlet.LoginServlet  - User found with details=Name=Pankaj Kumar, Email=pankaj@apple.com, Country=India
77840 [http-bio-8080-exec-8] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/home.jsp
98251 [http-bio-8080-exec-9] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Logout
98251 [http-bio-8080-exec-9] INFO  com.journaldev.servlet.LogoutServlet  - JSESSIONID=367DE255789AC02F7C0E0298B825877C
98251 [http-bio-8080-exec-9] INFO  com.journaldev.servlet.LogoutServlet  - User=Name=Pankaj Kumar, Email=pankaj@apple.com, Country=India
98254 [http-bio-8080-exec-10] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/login.html
109516 [http-bio-8080-exec-10] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Register
109517 [http-bio-8080-exec-10] INFO  com.journaldev.servlet.RegisterServlet  - User registered with email=abc@abc.com
127848 [http-bio-8080-exec-10] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Login
223055 [http-bio-8080-exec-2] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Login
223056 [http-bio-8080-exec-2] INFO  com.journaldev.servlet.LoginServlet  - User found with details=Name=Pankaj Kumar, Email=pankaj@apple.com, Country=India
223059 [http-bio-8080-exec-2] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/home.jsp
231931 [http-bio-8080-exec-2] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/invalidurl.jsp

下载资源 (Download Resources)

  1. MySql Java Connector Jar

    MySql Java连接器Jar
  2. Log4j Jar

    Log4j罐

I hope you liked the article and understand the core concepts of Servlet JDBC and Log4j integration, please share and let me know your opinions through comments.

希望您喜欢这篇文章,并了解Servlet JDBC和Log4j集成的核心概念,请分享并通过评论让我知道您的意见。

翻译自: https://www.journaldev.com/1997/servlet-jdbc-database-connection-example

servlet jdbc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值