MVC框架实现登录与数据查询
下面是效果展示:
下面是我的项目布局:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>登录页面</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">
-->
<script src="js/jquery.js" type="text/javascript"></script>
<style type="text/css">
body {
background-image: url("img/1.jpg");
background-size: 100% 100%;
background-repeat: no-repeat;
}
form {
margin-top: 250px;
border: 2px solid white;
width: 250px;
height: 145px;
text-align: center;
line-height: 50px;
border: 2px solid white;
background-image: url("img/1.jpg");
}
#name,#pwd {
width: 140px;
height: 22px;
}
</style>
</head>
<body>
<center>
<form action="#" method="post">
账户: <input type="text" name="name" id="name" /> <br /> 密码: <input
type="text" name="pwd" id="pwd" /> <br /> <input type="button"
value="登录" />
</form>
</center>
<script type="text/javascript">
$(function() {
$(":button").on("click", function() {
//ajax请求
$.ajax({
url : "LoginServlet",
type : "post",
//发送数据到服务器
data : {
name : $("#name").val(),
pwd : $("#pwd").val()
},
dataType : "text",
//success 当请求之后调用。传入返回后的数据,进行判断。
success : function(data) {
if (data == "ok") {
//如果服务器返回的是 ok 则进行跳转到index.jsp页面
window.location.href = "listbook.jsp";
} else if (data == "error") {
//反之进行弹框提示 登录失败
alert("登录失败!!!");
//如果账户错误则清空账户
$("#name").val("");
} else if (data == "no") {
//反之进行弹框提示 登录失败
alert("登录失败!!!");
//如果密码错误则清空密码
$("#pwd").val("");
} else {
alert("登录失败!!!");
//如果账户和密码都错误则清空账户密码
$("#name").val("");
$("#pwd").val("");
}
}
});
});
//失去焦点进行输入框校验
$("#name").blur(function() {
//用户名: 大写字母开头 6-20位字符(不允许有符号但是允许有_)
var limitierName = /^[A-Z]\w{4,19}$/;
reg("name", limitierName);
});
//失去焦点进行输入框校验
$("#pwd").blur(function() {
//密码:大写开头 数字字母符号混合 8-15位
var limitierPwd = /^[A-Z][\w\W]{7,14}$/;
reg("pwd", limitierPwd);
});
//验证的函数
function reg(eleId, rule) {
var inputValue = document.getElementById(eleId).value;
var result = rule.test(inputValue.trim());
if (result) {
//如果符合输入框格式则设边框为蓝色
document.getElementById(eleId).style.borderColor = "blue";
} else {
//如果不符合输入框格式则设边框为红色
document.getElementById(eleId).style.borderColor = "red";
}
}
});
</script>
</body>
</html>
listbook.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>数据页面</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">
-->
<script src="js/jquery.js" type="text/javascript"></script>
<style type="text/css">
body {
background-color:#ccc;
background-size: 100% 100%;
background-repeat: no-repeat;
}
table, td {
border: 1px solid black;
border-collapse: collapse;
}
td{
text-align: center;
width: 150px;
height: 30px;
}
</style>
<script type="text/javascript">
$(function () {
$(":button").on("click", function () {
$.ajax({
url: "BookSelect",//提交地址
type: "post",//提交方式
dataType: "json",
success: function (data) {//请求回调
$("tbody").empty();
$.each(data,function(i){
var trString = "";
trString = "<tr><td>" + data[i].id + "</td><td>" + data[i].name + "</td><td>" + data[i].author + "</td><td>" + data[i].isbn + "</td><td>" + data[i].publish + "</td></tr>";
$("tbody").append(trString);
});
}
});
});
});
</script>
</head>
<body>
<center>
<input type="button" value="获取数据"/>
<table>
<thead>
<tr>
<td>ID</td>
<td>图书名称</td>
<td>图书作者</td>
<td>图书编号</td>
<td>图书出版社</td>
</tr>
</thead>
<tbody></tbody>
</table>
</center>
</body>
</html>
建一个抽象类
Book.java
package cn.hnpi.bean;
public class Book {
private Integer id;// ID
private String name;// 图书名称
private String author;// 图书作者
private String isbn;// 图书编号
private String publish;// 图书出版社
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(Integer id, String name, String author, String isbn,
String publish) {
super();
this.id = id;
this.name = name;
this.author = author;
this.isbn = isbn;
this.publish = publish;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getPublish() {
return publish;
}
public void setPublish(String publish) {
this.publish = publish;
}
}
建一个接口
BookService.java
package cn.hnpi.service;
import java.util.List;
import cn.hnpi.bean.Book;
public interface BookService {
/**
* 查询数据
* @return
*/
List<Book> list();
}
实现接口
BookServiceImpl.java
package cn.hnpi.service.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import cn.hnpi.bean.Book;
import cn.hnpi.service.BookService;
import cn.hnpi.util.DButil;
public class BookServiceImpl implements BookService {
public List<Book> list() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Book> list = new ArrayList<Book>();
try {
conn = DButil.getConn();
String sql = "select * from book";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Book book = new Book();
book.setId(rs.getInt(1));
book.setName(rs.getString(2));
book.setAuthor(rs.getString(3));
book.setIsbn(rs.getString(4));
book.setPublish(rs.getString(5));
list.add(book);
}
} catch (SQLException e) {
// TODO: handle exception
} finally {
DButil.close(rs, ps, conn);
}
return list;
}
}
BookSelect.java
package cn.hnpi.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import cn.hnpi.bean.Book;
import cn.hnpi.service.BookService;
import cn.hnpi.service.impl.BookServiceImpl;
public class BookSelect extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset = utf-8");
PrintWriter out = response.getWriter();
BookService service = new BookServiceImpl();
List<Book> lists = service.list();
String json = JSON.toJSONString(lists);
out.print(json);
out.flush();
out.close();
}
}
LoginServlet.java
package cn.hnpi.servlet;
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;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html,charset = utf-8");
PrintWriter out = response.getWriter();
// 定义两个变量账户name,密码pwd并赋值
String name = "Admin";
String pwd = "Admin123456";
// 获取输入框账户,密码的数据
String ajaxName = request.getParameter("name");
String ajaxPwd = request.getParameter("pwd");
// 进行账户,密码的正确判断
if (name.equals(ajaxName) && pwd.equals(ajaxPwd)) {
// 如果正确则为ok
out.print("ok");
} else if (!name.equals(ajaxName) && pwd.equals(ajaxPwd)) {
// 反之则为error
out.print("error");
} else if (name.equals(ajaxName) && !pwd.equals(ajaxPwd)) {
// 反之则为error
out.print("no");
}
out.flush();
out.close();
}
}
建一个与数据库交互的类
DButil.java
package cn.hnpi.util;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DButil {
public static Connection getConn() {
Connection conn = null;
try {
Driver.class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=MyDB", "sa", "1");
}catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs,PreparedStatement ps,Connection conn) {
try {
if(rs != null)
rs.close();
if(ps != null)
ps.close();
if(conn != null)
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
记得导入数据架包和json的架包