简单的MySQL数据库连接例子
1、在项目中加入MySQL对应的JDBC的驱动jar包
LoginWeb/WebRoot/WEB-INF/lib/mysql-connector-java-3.2.0-alpha-bin.jar
配置文件
代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginSvlt</servlet-name>
<servlet-class>com.qdu.sun.LoginSvlt</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginSvlt</servlet-name>
<url-pattern>/LoginSvlt</url-pattern>
</servlet-mapping>
<filter>
<filter-name>FormFilter</filter-name>
<filter-class>com.qdu.sun.FormFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FormFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2、前台页面login.html
代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录</title>
<meta http-equiv="content-type" content="text/html; charset=GBK">
</head>
<script type="text/javascript">
// 验证输入不为空的脚本代码
function checkForm(form) {
if(form.username.value == "") {
alert("用户名不能为空!");
form.username.focus();
return false;
}
if(form.password.value == "") {
alert("密码不能为空!");
form.password.focus();
return false;
}
return true;
}
</script>
<body>
请登录
<br>
<form action="LoginSvlt" method="post"
onsubmit="return checkForm(this);">
用户名:
<input type="text" name="username">
<br>
密码:
<input type="password" name="password">
<br>
<input type="submit" value="登录" name="submit1">
<input type="reset" value="重置" name="reset1">
</form>
</body>
</html>
3、后台处理LoginSvlt.java登录处理
代码
package com.qdu.sun;
import java.io.IOException;
import java.io.PrintWriter;
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 java.sql.*;
public class LoginSvlt extends HttpServlet {
private String username;
private String password;
public LoginSvlt() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
username=request.getParameter("username");
password=request.getParameter("password");
//先定义变量,后使用和关闭
Connection conn = null;//声明数据库连接对象
Statement stmt = null; //声明数据库表达式对象
ResultSet rs = null;//声明结果集对象
try {
// 载入Mysql的驱动字符串
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库的连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "123456");
// 获取表达式对象实例
stmt = conn.createStatement();
rs=stmt.executeQuery("select * from user where username='"+username+"'and password='"+password+"'");
if(rs.next())
{
HttpSession session=request.getSession(true);
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
}
else
{
response.sendRedirect("error.jsp");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
FormFilter.java中文处理
代码
package com.qdu.sun;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class FormFilter implements Filter {
/**
* Request.java 对 HttpServletRequestWrapper 进行扩充, 不影响原来的功能并能提供所 有的
* HttpServletRequest 接口中的功能. 它可以统一的对 Tomcat 默认设置下的中文问题进行解决而只 需要用新的 Request
* 对象替换页面中的 request 对象即可.
*/
class Request extends HttpServletRequestWrapper {
public Request(HttpServletRequest request) {
super(request);
}
/**
* 转换由表单读取的数据的内码. 从 ISO 字符转到 GBK.
*/
public String toChi(String input) {
try {
byte[] bytes = input.getBytes("ISO8859-1");
return new String(bytes, "GBK");
} catch (Exception ex) {
}
return null;
}
/**
* Return the HttpServletRequest holded by this object.
*/
private HttpServletRequest getHttpServletRequest() {
return (HttpServletRequest) super.getRequest();
}
/**
* 读取参数 -- 修正了中文问题.
*/
public String getParameter(String name) {
return toChi(getHttpServletRequest().getParameter(name));
}
/**
* 读取参数列表 - 修正了中文问题.
*/
public String[] getParameterValues(String name) {
String values[] = getHttpServletRequest().getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = toChi(values[i]);
}
}
return values;
}
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpreq = (HttpServletRequest) request;
if (httpreq.getMethod().equals("POST")) {
request.setCharacterEncoding("GBK");
} else {
request = new Request(httpreq);
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
4、成功页面
代码
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'MyJsp.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
欢迎用户:${sessionScope.username}<br>
</body>
</html>