博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
servlet jdbc_Servlet JDBC数据库连接示例
阅读量:2532 次
发布时间:2019-05-11

本文共 29689 字,大约阅读时间需要 98 分钟。

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的核心概念。

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代码:

Login Page

Login with email and password

User Email:
Password:
If you are new user, please register.

register.html code:

register.html代码:

Register Page

Provide all the fields for registration.

Email ID:
Password:
Name:
Country:
If you are registered user, please login.

部署描述符和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代码:

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

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

ServletDBLog4jExample
login.html
dbUser
pankaj
dbPassword
pankaj123
dbURL
jdbc:mysql://localhost:3306/UserDB
log4j-config
WEB-INF/log4j.xml
404
/AppErrorHandler
java.lang.Throwable
/AppErrorHandler
AuthenticationFilter
com.journaldev.servlet.filters.AuthenticationFilter
AuthenticationFilter
/*

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;@WebListenerpublic 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("Exception/Error Details");	      if(statusCode != 500){	    	  out.write("

Error Details

"); out.write("Status Code:"+statusCode+"
"); out.write("Requested URI:"+requestUri); }else{ out.write("

Exception Details

"); out.write("
  • Servlet Name:"+servletName+"
  • "); out.write("
  • Exception Name:"+throwable.getClass().getName()+"
  • "); out.write("
  • Requested URI:"+requestUri+"
  • "); out.write("
  • Exception Message:"+throwable.getMessage()+"
  • "); out.write("
"); } out.write("
"); out.write("Login Page"); out.write(""); }}

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(""+errorMsg+"");			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("No user found with given email id, please register first.");				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(""+errorMsg+"");			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("Registration successful, please login below.");			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"%>
Home Page<%User user = (User) session.getAttribute("User"); %>

Hi <%=user.getName() %>

Your Email: <%=user.getEmail() %>
Your Country: <%=user.getCountry() %>

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 initialized1    [localhost-startStop-1] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - AuthenticationFilter initialized37689 [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 request37693 [http-bio-8080-exec-4] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/login.html51844 [http-bio-8080-exec-5] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/register.html77818 [http-bio-8080-exec-7] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Login77835 [http-bio-8080-exec-7] INFO  com.journaldev.servlet.LoginServlet  - User found with details=Name=Pankaj Kumar, Email=pankaj@apple.com, Country=India77840 [http-bio-8080-exec-8] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/home.jsp98251 [http-bio-8080-exec-9] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Logout98251 [http-bio-8080-exec-9] INFO  com.journaldev.servlet.LogoutServlet  - JSESSIONID=367DE255789AC02F7C0E0298B825877C98251 [http-bio-8080-exec-9] INFO  com.journaldev.servlet.LogoutServlet  - User=Name=Pankaj Kumar, Email=pankaj@apple.com, Country=India98254 [http-bio-8080-exec-10] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/login.html109516 [http-bio-8080-exec-10] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Register109517 [http-bio-8080-exec-10] INFO  com.journaldev.servlet.RegisterServlet  - User registered with email=abc@abc.com127848 [http-bio-8080-exec-10] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Login223055 [http-bio-8080-exec-2] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/Login223056 [http-bio-8080-exec-2] INFO  com.journaldev.servlet.LoginServlet  - User found with details=Name=Pankaj Kumar, Email=pankaj@apple.com, Country=India223059 [http-bio-8080-exec-2] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/home.jsp231931 [http-bio-8080-exec-2] INFO  com.journaldev.servlet.filters.AuthenticationFilter  - Requested Resource::/ServletDBLog4jExample/invalidurl.jsp

下载资源 (Download Resources)

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集成的核心概念,请分享并通过评论让我知道您的意见。

翻译自:

servlet jdbc

转载地址:http://hnlzd.baihongyu.com/

你可能感兴趣的文章
《BI那点儿事》数据流转换——百分比抽样、行抽样
查看>>
哈希(1) hash的基本知识回顾
查看>>
Leetcode 6——ZigZag Conversion
查看>>
dockerfile_nginx+PHP+mongo数据库_完美搭建
查看>>
Http协议的学习
查看>>
【转】轻松记住大端小端的含义(附对大端和小端的解释)
查看>>
设计模式那点事读书笔记(3)----建造者模式
查看>>
ActiveMQ学习笔记(1)----初识ActiveMQ
查看>>
Java与算法之(2) - 快速排序
查看>>
Windows之IOCP
查看>>
机器学习降维之主成分分析
查看>>
CTP2交易所成交回报
查看>>
WebSocket & websockets
查看>>
openssl 升级
查看>>
ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
查看>>
CVE-2010-2883Adobe Reader和Acrobat CoolType.dll栈缓冲区溢出漏洞分析
查看>>
使用正确的姿势跨域
查看>>
AccountManager教程
查看>>
Android学习笔记(十一)——从意图返回结果
查看>>
算法导论笔记(四)算法分析常用符号
查看>>