Servlet 是Java Web应用中最核心的组件,也是Web服务器组件,它是一个中间控制层,负责处理客户端提交过来的请求数据以及调用业务逻辑对象,根据业务逻辑来控制页面转发。
而jdbc是Java用来访问数据库的,Java可以通过不同的编程接口和类,来访问各种不同的数据库。接下来我要使用的是MySQL的JDBC API。
第一步,创建一个jdbc.properties文件,配置连接MySQL的参数。
然后加载jdbc驱动。
package com.gx.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.sql.ResultSet;
public class DbUtil {
private static String url = "";
private static String username = "";
private static String password = "";
static {
Properties properties = new Properties();
try {
//加载jdbc,传入一个文件(路径)
properties.load(new FileReader(new File("C:\\Users\\张益达\\Workspaces\\MyEclipse\\myDemo2\\src\\jdbc.properties")));
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
String driver = properties.getProperty("driver");
Class.forName(driver);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
接下来创建一个实体类,存放表格字段。
package com.gx.vo;
public class UserVo {
private static int UserID;
private String UserNuber;
private String Password;
private boolean ToVoidNo;
private String Email;
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public int getUserID() {
return UserID;
}
public void setUserID(int userID) {
//以下略....
第二步,创建一个接口,声明查询方法,返回值是UserVo类型。
package com.gx.dao;
import com.gx.vo.UserVo;
public interface User{
//创建接口,声明查询方法
public UserVo selectUserByUser(String UserNuber);
public UserVo selectUserByEmail(String Email);
}
实现该接口,调用接口内的方法。
package com.gx.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.gx.dao.User;
import com.gx.util.DbUtil;
import com.gx.vo.UserVo;
//实现接口,就要调用该接口内所有方法
public class UserImpl implements User {
private static Connection con = null;//连接数据库
private static ResultSet rs = null;//接收返回值
private static PreparedStatement ps = null;
UserVo userVo = null;
//声明SQL语句,传递参数
//查询用户ByName
@Override
public UserVo selectUserByUser(String UserNuber) {
String str = "select * from pw_user where UserNuber = ?";
getInfo(str, UserNuber);
return userVo;
}
//查询用户By邮箱
@Override
public UserVo selectUserByEmail(String Email) {
String str = "select * from pw_user where Email = ?";
getInfo(str, Email);
return userVo;
}
//Select
public UserVo getInfo(String sql, String Info) {
try {
con = DbUtil.getConnection();
ps = con.prepareStatement(sql);
ps.setString(1, Info);
rs = ps.executeQuery();
userVo = new UserVo();
while (rs.next()) {
//循环结果,并添加到实体类中
userVo.setUserID(rs.getInt("UserID"));
userVo.setPassword(rs.getString("Password"));
userVo.setUserNuber(rs.getString("UserNuber"));
userVo.setToVoidNo(rs.getBoolean("ToVoidNo"));
userVo.setEmail(rs.getString("Email"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DbUtil.close(con, ps, rs);//关闭连接
}
// TODO Auto-generated method stub
return userVo;
}
第三步,搭建login.jsp页面,在form表单中设置请求路径和请求方法,将请求提交到LoginiServlet,在LoginiServlet调用UserImpl中的查询方法。
<form action="<%=basePath%>servlet/LoginServlet" method="post" id="form">
<table>
<tr>
<th>用户名:</th>
<td><input name="UserNuber" type="text" />
</td>
</tr>
<tr>
<th>密码:</th>
<td><input name="password" type="password" />
</td>
</tr>
<tr>
<th></th>
<td>
<button type="button" id="login">登录</button>
</td>
</tr>
<tr>
<th></th>
<td>
<a href="jsp/register.jsp">没有账号?去注册--></a>
</td>
</tr>
</table>
</form>
<script type="text/javascript">
$("#login").click(function() {
var name = $("#form input[name='UserNuber']").val();
var password = $("#form input[name='password']").val();
if (name == null || password == "") {
layer.msg("用户名不能为空!", {offset : '150px'});
} else {
if (password == null || password == "") {
layer.msg("密码不能为空!", {offset : '150px'});
} else {
$("#form").ajaxSubmit(function(data) {
if (data != "success") {
layer.alert(data, {icon : 0,title : '提示',offset : '150px'});
} else {
layer.msg("登录成功!", {offset : '150px'});
window.location.href="jsp/index.jsp";
}
});
//以下部分代码略...
public void doPost(HttpServletRequest request, HttpServletResponse response) {
response.setCharacterEncoding("utf-8");//设置返回参数的编码类型
String UserNuber = request.getParameter("UserNuber");//接收页面传递来的参数
String password = request.getParameter("password");
try {
UserVo userVo = userImpl.selectUserByUser(UserNuber);//调用查询方法
//页面根据返回的结果进行提示或者页面跳转
if (userVo.getUserNuber() != null) {
if (password.equals(userVo.getPassword())) {
request.getSession().setAttribute("UserNuber", UserNuber);
request.setAttribute("UserNuber", UserNuber);
response.getWriter().write("success");
} else {
response.getWriter().write("密码错误!请注意大小写!");
}
} else {
response.getWriter().write("该用户不存在!");
}
在页面可以通过弹窗提示出错误信息