jquery水平垂直居中_Java Web应用程序集成的jQuery UI选项卡(水平和垂直)示例

jquery水平垂直居中

jQuery UI is built on top of jQuery JavaScript Library to help web developers in creating awesome web pages with different types of effects. Today we will look into jQuery UI Tabs feature that we can use to create tabs in the view pages easily. We will use this in a simple java web application where user can register and then login. Both registration and login forms will be part of the home page, in two different tabs.

jQuery UI建立在jQuery JavaScript库的基础上,可帮助Web开发人员创建具有不同类型效果的出色网页。 今天,我们将研究jQuery UI Tabs功能,我们可以使用该功能轻松地在视图页面中创建选项卡。 我们将在一个简单的Java Web应用程序中使用它,用户可以在其中注册然后登录。 注册和登录表单都将是主页的一部分,位于两个不同的选项卡中。

Just to get an idea, below image shows the home page of the web application after integrating all the bits and pieces.

只是为了获得一个主意,下图显示了将所有点滴整合后的Web应用程序主页。

Java Web应用程序设置 (Java Web Application Setup)

Below image shows the final structure of our web application. Before we proceed with the code, we need to setup our application with required JS and CSS libraries.

下图显示了我们的Web应用程序的最终结构。 在继续进行代码之前,我们需要使用必需的JS和CSS库设置应用程序。

  1. Create a “Dynamic Web Project” in Eclipse, you can choose any name but if you want to use the same name as my project, use jQueryUITabsLoginExample. After project is created, convert it to maven project so that we can add required dependencies.

    在Eclipse中创建“动态Web项目”,您可以选择任何名称,但是如果要使用与我的项目相同的名称,请使用jQueryUITabsLoginExample 。 创建项目后,将其转换为Maven项目,以便我们可以添加所需的依赖项。
  2. I am using MySQL DB to store user information, below script can be used to create the Users table.
    CREATE TABLE `Users` (
      `email` varchar(30) NOT NULL DEFAULT '',
      `name` varchar(30) NOT NULL DEFAULT '',
      `password` varchar(30) NOT NULL DEFAULT '',
      `address` varchar(50) NOT NULL DEFAULT '',
      PRIMARY KEY (`email`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    我正在使用MySQL DB存储用户信息,下面的脚本可用于创建Users表。
  3. Since I am using MySQL database, we need to add MySQL Java driver to the project. Below is our final pom.xml, it’s simple and straight-forward.

    pom.xml

    <project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>jQueryUITabsLoginExample</groupId>
    	<artifactId>jQueryUITabsLoginExample</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>war</packaging>
    
    	<dependencies>
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<version>5.0.5</version>
    		</dependency>
    	</dependencies>
    	
    	<build>
    		<sourceDirectory>src</sourceDirectory>
    		<plugins>
    			<plugin>
    				<artifactId>maven-war-plugin</artifactId>
    				<version>2.3</version>
    				<configuration>
    					<warSourceDirectory>WebContent</warSourceDirectory>
    					<failOnMissingWebXml>false</failOnMissingWebXml>
    				</configuration>
    			</plugin>
    			<plugin>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.1</version>
    				<configuration>
    					<source>1.7</source>
    					<target>1.7</target>
    				</configuration>
    			</plugin>
    		</plugins>
    		<finalName>${project.artifactId}</finalName>
    	</build>
    </project>

    由于我使用的是MySQL数据库,因此我们需要将MySQL Java驱动程序添加到项目中。 下面是我们最终的pom.xml,它简单明了。

    pom.xml

  4. Download jQuery JavaScript library from https://jquery.com/download/ and put in the js directory as shown in the project image.

    https://jquery.com/download/下载jQuery JavaScript库,并将其放入js目录,如项目图像所示。
  5. Download jQuery UI library from https://jqueryui.com/download/, you will get a lot of JS and CSS files. You need to include only jquery-ui.js and jquery-ui.css files for the project. jQuery UI provides a lot of themes that we can use as base and then customize it according to our requirements. The layout in the project homepage is the Cupertino theme, you can choose one of the theme from the Download page.

    https://jqueryui.com/download/下载jQuery UI库,您将获得很多JS和CSS文件。 您只需要为项目包括jquery-ui.jsjquery-ui.css文件。 jQuery UI提供了许多主题,我们可以将它们用作基础主题,然后根据我们的要求对其进行自定义。 项目主页中的布局是Cupertino主题,您可以从“下载”页面中选择主题之一。

Our project setup is ready now, we can move to our business logic part now.

现在我们的项目设置已准备就绪,现在可以移至业务逻辑部分。

型号类别 (Model Class)

We have User class to map the database table, below is the User model class code.

我们有User类来映射数据库表,下面是User模型类的代码。

User.java

User.java

package com.journaldev.servlet.model;

public class User {
	
	private String name;
	private String email;
	private String password;
	private String address;
	
	public User(){}
	
	public User(String name, String email, String password, String address){
		this.name=name;
		this.email=email;
		this.password=password;
		this.address=address;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}

}

数据库连接实用程序类 (Database Connection Utility Class)

We have a simple utility class for database connection, it’s not optimized and just for example purposes.

我们有一个简单的实用程序类用于数据库连接,它没有经过优化,仅出于示例目的。

JDBCUtil.java

JDBCUtil.java

package com.journaldev.servlet.jdbc;

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

public class JDBCUtil {
	
private static Connection connection = null;

public static Connection getConnection() {
	if (connection != null)
		return connection;
	else {
		// database URL
		String dbUrl = "jdbc:mysql://localhost/TestDB";
		try 
		{
		Class.forName("com.mysql.jdbc.Driver");
		
		// set the url, username and password for the database
		connection = DriverManager.getConnection(dbUrl, "pankaj", "pankaj123");
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
	}
}

DAO实施类 (DAO Implementation Classes)

UseDAO interface defines the contract for the services that will be exposed for operations on Users table.

UseDAO接口定义将针对“用户”表上的操作公开的服务的合同。

UserDAO.java

UserDAO.java

package com.journaldev.servlet.dao;

import com.journaldev.servlet.model.User;

public interface UserDAO {

	public int createUser(User user);
	
	public User loginUser(User user);
	
}

Below is the implementation class, we could have used Hibernate or any other ORM tools for the implementation too.

下面是实现类,我们也可以使用Hibernate或任何其他ORM工具进行实现。

UserDAOImpl.java

UserDAOImpl.java

package com.journaldev.servlet.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.journaldev.servlet.jdbc.JDBCUtil;
import com.journaldev.servlet.model.User;

public class UserDAOImpl implements UserDAO {

	private Connection dbConnection;
	private PreparedStatement pStmt;

	private String SQL_SELECT = "SELECT name, address FROM users WHERE email = ? AND password = ?";
	private String SQL_INSERT = "INSERT INTO users (name,email,password,address) VALUES (?,?,?,?)";

	public UserDAOImpl() {
		dbConnection = JDBCUtil.getConnection();
	}

	public User loginUser(User user) {
		try {
			pStmt = dbConnection.prepareStatement(SQL_SELECT);
			pStmt.setString(1, user.getEmail());
			pStmt.setString(2, user.getPassword());
			ResultSet rs = pStmt.executeQuery();
			while (rs.next()) {
				user.setName(rs.getString("name"));
				user.setAddress(rs.getString("address"));
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		return user;
	}

	public int createUser(User user) {
		int result = 0;
		try {
			pStmt = dbConnection.prepareStatement(SQL_INSERT);
			pStmt.setString(1, user.getName());
			pStmt.setString(2, user.getEmail());
			pStmt.setString(3, user.getPassword());
			pStmt.setString(4, user.getAddress());
			result = pStmt.executeUpdate();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		return result;
	}
}

Servlet类和配置 (Servlet Classes and Configuration)

We have two servlet controller classes for registration and login process. There are some simple validations present to avoid common errors.

我们有两个用于注册和登录过程的servlet控制器类。 存在一些简单的验证以避免常见错误。

RegistrationController.java

RegistrationController.java

package com.journaldev.servlet.controller;

import java.io.IOException;

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

import com.journaldev.servlet.dao.UserDAO;
import com.journaldev.servlet.dao.UserDAOImpl;
import com.journaldev.servlet.model.User;

public class RegistrationController extends HttpServlet {

	private static final long serialVersionUID = -4006561145676424435L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String address = request.getParameter("address");

		if ((name == null || "".equals(name))
				|| (email == null || "".equals(email))
				|| (password == null || "".equals(password))
				|| (address == null || "".equals(address))) {
			String error = "Mandatory Parameters Missing";
			request.getSession().setAttribute("errorReg", error);
			response.sendRedirect("index.jsp#register");
		} else {
			User user = new User(name, email, password, address);

			UserDAO userDAO = new UserDAOImpl();

			int result = userDAO.createUser(user);
			if (result == 1) {
				request.getSession().removeAttribute("errorReg");
				response.sendRedirect("success.jsp");
			}else{
				request.getSession().setAttribute("errorReg", "Internal Server Error, Please try again later.");
				response.sendRedirect("index.jsp#register");
			}
		}
	}
}

LoginController.java

LoginController.java

package com.journaldev.servlet.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.journaldev.servlet.dao.UserDAO;
import com.journaldev.servlet.dao.UserDAOImpl;
import com.journaldev.servlet.model.User;

public class LoginController extends HttpServlet {

	private static final long serialVersionUID = -4602272917509602701L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String error;
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		
		User user = new User();
		user.setEmail(email); user.setPassword(password);
		
		HttpSession session = request.getSession();
		UserDAO userDAO = new UserDAOImpl();

		User userDB = userDAO.loginUser(user);

		if (userDB.getName() == null) {
			error = "Invalid Email or password";
			session.setAttribute("error", error);
			response.sendRedirect("index.jsp");
		} else {
			session.setAttribute("user", userDB.getName());
			session.removeAttribute("error");
			response.sendRedirect("welcome.jsp");
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if ("logout".equalsIgnoreCase(request.getParameter("param"))) {
			HttpSession session = request.getSession();
			if(session != null){
			session.invalidate();
			}
			response.sendRedirect("index.jsp");
		}
	}
}

It’s time to configure these servlets in web.xml file, below is the final web.xml file.

现在该在web.xml文件中配置这些servlet了,下面是最终的web.xml文件。

web.xml

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" xmlns:web="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>jQueryTabsWebAppExample</display-name>
	
	<servlet>
		<servlet-name>LoginController</servlet-name>
		<servlet-class>com.journaldev.servlet.controller.LoginController
		</servlet-class>
	</servlet>
	<servlet>
		<servlet-name>RegistrationController</servlet-name>
		<servlet-class>com.journaldev.servlet.controller.RegistrationController
		</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>LoginController</servlet-name>
		<url-pattern>/LoginController</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>RegistrationController</servlet-name>
		<url-pattern>/RegistrationController</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

项目CSS文件 (Project CSS File)

Below is our custom CSS file for view pages.

以下是我们用于查看页面的自定义CSS文件。

style.css

style.css

body {
	background-color: #e7e7e7;
	font-family: Helvetica;
	font-size: 14px;
	color: #666;
	margin: 0px;
	padding: 0px;
}

.wrapper {
	width: 900px;
	height: 500px;
	margin: 0 auto;
	background: white;
	margin: 0 auto;
}

.container {
	min-height: 400px;
	border-top: 1px solid gray;
	padding: 50px;
}

jQuery UI选项卡查看页面 (jQuery UI Tabs View Page)

Below is the home page JSP code, where we are using jQuery UI tags.

下面是主页JSP代码,我们在其中使用jQuery UI标签。

index.jsp

index.jsp

<!DOCTYPE html>
<html>
<head>
<title>Login and Registration Page</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">

<script src="js/jquery-1.11.1.js"></script>
<script src="js/jquery-ui.js"></script>

<script>
$(function() {
  $( "#tabs" ).tabs();
});
</script>

</head>

<body>
	<div class="wrapper">
		<div class="container">
			<div id="tabs">
				<ul>
					<li><a href="#login">Login</a></li>
					<li><a href="#register">Register</a></li>
				</ul>
				<div id="login">
					<% 
  	if((String)session.getAttribute("error") != null){ %>
					<h4>Invalid Email or Password. Please try again.</h4>
					<%} %>
					<form method="post" action="LoginController">
						<label for="email">Email:</label> <br /> <input type="text"
							name="email" id="email" /> <br /> <label for="password">Password:</label>
						<br /> <input type="password" name="password" id="password" /> <br />
						<br /> <input type="submit" value="Login">
					</form>
				</div>
				<div id="register">
					<% 
  	if((String)session.getAttribute("errorReg") != null){ %>
					<h4><%=session.getAttribute("errorReg") %></h4>
					<%} %>
					<form method="post" action="RegistrationController">
						<label for="name">Name:</label><br /> <input type="text"
							name="name" id="name" /> <br /> <label for="email">Email:</label><br />
						<input type="text" name="email" id="email" /> <br /> <label
							for="password">Password:</label><br /> <input type="password"
							name="password" id="password" /> <br /> <label for="address">Address:</label><br />
						<input type="text" name="address" id="address" /> <br /> <br /> <input
							type="submit" value="Register">
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>

jQuery JS Code for creating tags is:

用于创建标签的jQuery JS代码是:

$(function() {
  $( "#tabs" ).tabs();
});

Above code will convert the tabs div into different tabs. For different tabs, this div should have an unordered list of elements, for us it’s

上面的代码会将选项卡 div转换为不同的选项卡。 对于不同的标签,此div应该具有无序的元素列表,对我们来说

<ul>
	<li><a href="#login">Login</a></li>
	<li><a href="#register">Register</a></li>
</ul>

Notice that every list item contains anchored URL, they should be the other div elements that will form the view of the tabs. That’s why we have two further divs – login and register. That’s it, other parts of the JSP page are simple HTML and JSP scriptlets. I know that we should not use scriptlets, but again it’s an example and I didn’t wanted to add another technology into it, if you haven’t guessed till now, I am talking about JSTL.

请注意,每个列表项都包含锚定URL,它们应该是将构成选项卡视图的其他div元素。 这就是为什么我们还有两个div的原因- 登录注册 。 就是这样,JSP页面的其他部分是简单HTML和JSP scriptlet 。 我知道我们不应该使用scriptlet,但是这又是一个例子,我也不想在其中添加其他技术,如果您到目前为止还没有猜到,我在谈论JSTL

We have couple more simple JSP pages for registration success and login success.

我们有几个简单的JSP页面,用于注册成功和登录成功。

success.jsp

success.jsp

<!DOCTYPE html>
<html>
<head>
<title>Registration Success Page</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">

</head>
<body>
<div class="wrapper">
	<div class="container">
		<h4>
			You have been successfully registered. 
			[ <a href="index.jsp">Back to login page</a> ]
		</h4>
	</div>
</div>
</body>
</html>

welcome.jsp

welcome.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Welcome Page</title>
<link rel="stylesheet" href="js/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">
</head>

<body>
<div class="wrapper">
	<div class="container">
		<%
			String user = (String) session.getAttribute("user");
			if (user != null) {
		%>
		<h3>
			Welcome
			<%
				out.print(user);
			%>
			</h3>
			<a href="LoginController?param=logout">Logout</a>
			<%
				} else {
			%>
			<h3>Your don't have permission to access this page</h3>
			<%
				}
			%>
	</div>
</div>
</body>
</html>

jQuery UI Tabs项目测试 (jQuery UI Tabs Project Test)

Our web application is ready, just build and deploy the project. Below are some of the images for different pages.

我们的Web应用程序已准备就绪,只需构建和部署项目即可。 以下是不同页面的一些图像。

jQuery UI垂直选项卡示例 (jQuery UI Vertical Tabs Example)

By default, jQuery UI create horizontal tabs. But we can add some extra jQuery code to create vertical tabs too. Below is another form of JSP page with vertical tabs.

默认情况下,jQuery UI创建水平选项卡。 但是我们也可以添加一些额外的jQuery代码来创建垂直标签。 下面是带有垂直选项卡的JSP页面的另一种形式。

index-vertical.jsp

index-vertical.jsp

<!DOCTYPE html>
<html>
<head>
<title>Login and Registration Page</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">

<script src="js/jquery-1.11.1.js"></script>
<script src="js/jquery-ui.js"></script>

<script>
$(function() {
  $( "#tabs" ).tabs().addClass( "ui-tabs-vertical ui-helper-clearfix" );
  $( "#tabs li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" );
});
</script>

<!-- Below style for Vertical Tabs -->
<style>
  .ui-tabs-vertical { width: 45em; }
  .ui-tabs-vertical .ui-tabs-nav { padding: .1em .1em .1em .1em; float: left; width: 8em; }
  .ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; }
  .ui-tabs-vertical .ui-tabs-nav li a { display:block; }
  .ui-tabs-vertical .ui-tabs-nav li.ui-tabs-active { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; border-right-width: 1px; }
  .ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 30em;}
  </style>
  
</head>

<body>
<div class="wrapper">	
<div class="container">
<div id="tabs">
  <ul>
    <li><a href="#login">Login</a></li>
    <li><a href="#register">Register</a></li>
  </ul>
  <div id="login">
  	<% 
  	if((String)session.getAttribute("error") != null){ %>
  		<h4> Invalid Email or Password. Please try again.</h4>
  	<%} %>
    <form method="post" action="LoginController">
    	<label for="email">Email:</label>
    	<br/>
    	<input type="text" name="email" id="email"/>
    	<br/>
    	<label for="password">Password:</label>
    	<br/>
    	<input type="password" name="password" id="password"  />
    	<br/>
    	<br/>
    	<input type="submit" value="Login">
    </form>
  </div>
  <div id="register">
  	<% 
  	if((String)session.getAttribute("errorReg") != null){ %>
  		<h4><%=session.getAttribute("errorReg") %></h4>
  	<%} %>
  	<form method="post" action="RegistrationController">
  		<label for="name">Name:</label><br/>
    	<input type="text" name="name" id="name" />
    	<br/>
    	<label for="email">Email:</label><br/>
    	<input type="text" name="email" id="email" />
    	<br/>
    	<label for="password">Password:</label><br/>
    	<input type="password" name="password" id="password" />
    	<br/>
    	<label for="address">Address:</label><br/>
    	<input type="text" name="address" id="address" />
    	<br/>
    	<br/>
    	<input type="submit" value="Register">
  	</form>
  </div>
</div>
</div>
</div>
</body>
</html>

Below are some of the images for vertical tabs output.

以下是一些用于垂直制表符输出的图像。

摘要 (Summary)

We have posted a lot of jQuery tutorials here, this example was meant to show how easy it is to integrate jQuery and jQuery UI into a java web application. You can download the final project from below link, don’t miss to share it with other too.

我们在这里发布了很多jQuery教程,该示例旨在说明将jQuery和jQuery UI集成到Java Web应用程序中有多么容易。 您可以从下面的链接下载最终项目,也不要错过与其他人共享的项目。

翻译自: https://www.journaldev.com/4792/jquery-ui-tabs-horizontal-and-vertical-example-with-java-web-application-integration

jquery水平垂直居中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值