jsp+servlet+mysql综合案例总结

原创 2020-05-22 19:29

本篇将实现用户登录注册、页面的增删改查、界面的分页三个案例

本篇案例采用MVC思想实现

一、登录注册案例

login页面

项目结构图

代码实现

界面: login.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>

<%
// 我们将绝对路径封装成一个对象
String ctx = request.getContextPath();
pageContext.setAttribute("ctx",ctx);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>login</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
background: #f3f3f3;
}
.control{
width: 340px;
background: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
border-radius: 5px;
}
.item{
width: 340px;
height: 60px;
background: #eeeeee;
}
.item div{
width: 170px;
height: 60px;
display: inline-block;
color: black;
font-size: 18px;
text-align: center;
line-height: 60px;
cursor: pointer;
}
.content{
width: 100%;
}
.content div{
margin: 20px 30px;
display: none;
text-align: left;
}
p{
color: #4a4a4a;
margin-top: 30px;
margin-bottom: 6px;
font-size: 15px;
}
.content input[type="text"], .content input[type="password"]{
width: 100%;
height: 40px;
border-radius: 3px;
border: 1px solid #adadad;
padding: 0 10px;
box-sizing: border-box;
}
.content input[type="submit"]{
margin-top: 40px;
width: 100%;
height: 40px;
border-radius: 5px;
color: white;
border: 1px solid #adadad;
background: #00dd60;
cursor: pointer;
letter-spacing: 4px;
margin-bottom: 40px;
}
.active{
background: white;
}
.item div:hover{
background: #f6f6f6;
}
</style>
<script>
window.onload = function(){
var item = document.getElementsByClassName("item");
var it = item[0].getElementsByTagName("div");

var content = document.getElementsByClassName("content");
var con = content[0].getElementsByTagName("div");

for(let i=0;i<it.length;i++){
it[i].onclick = function(){
for(let j=0;j<it.length;j++){
it[j].className = '';
con[j].style.display = "none";
}
this.className = "active";
it[i].index=i;
con[i].style.display = "block";
}
}
}

</script>
</head>
<body>
<div class="control">
<div class="item">
<div class="active">登录</div><div>注册</div>
</div>
<div class="content">
<div style="display: block;">
<form action="${ctx}/userServlet?action=login" method="post">
<p>账号</p>
<input type="text" placeholder="username" name="name"/>
<p>密码</p>
<input type="password" placeholder="password" name="password" />
<br/>
<input type="submit" value="登录" />
</form>
</div>
<div>
<form action="${ctx}/userServlet?action=register" method="post">
<p>用户名</p>
<input type="text" placeholder="username" name="name"/>
<p>密码</p>
<input type="password" placeholder="password" name="password"/>
<p>邮箱</p>
<input type="text" placeholder="email" name="email"/>
<br/>
<input type="submit" value="登录" />
</form>
</div>
<div style="test-algin:center">${show}</div>
</div>
</div>
</body>
</html>

Servlet: UserServlet.java这个类使用了反射优化了一下,详细请看Servlet优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package servlet;

import java.io.IOException;
import java.lang.reflect.Method;

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 molde.User;
import service.UserService;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String action = req.getParameter("action");
// 利用反射来优化Servlet
try {
Class<? extends UserServlet> clazz = this.getClass();
Method method = clazz.getMethod(action,HttpServletRequest.class,HttpServletResponse.class);
if(method!=null) {

String returns=(String) method.invoke(this, req,resp);

if(returns != null) {
if("/index.jsp".equals(returns)) {
req.getRequestDispatcher(returns).forward(req, resp);
}else {
req.setAttribute("show", returns);
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

// 处理登录请求
public String login(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
UserService us = new UserService();
boolean obj = us.login(req.getParameter("name"),req.getParameter("password"));
if(obj == true) {
return "/index.jsp";
}else {
return "登录失败!";
}
}

// 处理注册请求
public String register(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
User user = new User(req.getParameter("name"),req.getParameter("password"),req.getParameter("email"));
UserService us = new UserService();
boolean obj = false;
if(us != null) {
obj = us.register(user);
}
if(obj == true) {
return "注册成功!";
}else {
return "注册失败!";
}
}
}

UserInterface.java 这是一个接口,用来约束UserDao和UserService。

1
2
3
4
5
6
7
8
9
10
package Interface;

import molde.User;
// user接口约束
public interface UserInterface {
// 处理登录
public boolean login(String name,String password);
// 处理注册
public boolean register(User user);
}

Service: UserService.java 实现了 UserInterface接口,用来处理具体业务操作!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package service;

import Interface.UserInterface;
import dao.UserDao;
import molde.User;

public class UserService implements UserInterface{
UserDao ud = new UserDao();
// 登录
@Override
public boolean login(String name, String password) {
System.out.println(ud.login(name, password));
return ud.login(name, password);
}
// 注册
@Override
public boolean register(User user) {
return ud.register(user);
}

}

Dao: UserDao.java实现了实现了 UserInterface接口,然后进行数据的保存验证!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package dao;

import java.sql.*;
import Interface.UserInterface;
import molde.User;
import utils.jdbcUtils;
// 实现UserInterface
public class UserDao implements UserInterface{
private Connection conn;
private ResultSet res;
private PreparedStatement ps;
// 登录验证
@Override
public boolean login(String name, String password) {
boolean ble = false;
try {
conn = jdbcUtils.getConn();
String sql = "select * from user where uname=? and upassword=?";
ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2,password);
res = ps.executeQuery();
ble=res.next();
} catch (Exception e) {
e.printStackTrace();
}finally {
jdbcUtils.closes(ps, conn, res);
}
return ble;
}
// 注册存储
@Override
public boolean register(User user) {
boolean ble = false;
try {
conn = jdbcUtils.getConn();
String sql = "insert into user(uname,upassword,ueamil) value(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
res = ps.executeQuery();
ble=res.next();
} catch (Exception e) {
e.printStackTrace();
}finally {
jdbcUtils.closes(ps, conn, res);
}
System.out.println("dao:"+ble);
return ble;
}
}

Utils: jdbcUtils.java实现数据库连接!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Statement;

public class jdbcUtils {
// 获取Connection连接对象
public static Connection getConn() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
return DriverManager.getConnection(url,"root","123456");
}
// 释放资源
public static void closes(PreparedStatement ps,Connection conn,ResultSet res) {
try {
if(ps != null) {ps.close();}
if(conn != null) {conn.close();}
if(res != null) {res.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}

}

二、增删改查案例

1、jsp界面

2、项目结构

3、Java代码
BookDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package dao;

import java.sql.*;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import model.Book;
import utils.dbUtils;
public class BookDao {

// dbutils
QueryRunner qr = new QueryRunner();
dbUtils db = new dbUtils();
// 添加
public Object addBook(Book book) throws Exception {
Connection conn = db.getConn();
String sql = "insert into books(bname,bisbn,bauthor,bpress,btype,bstok) value(?,?,?,?,?,?)";
return qr.update(conn,sql,book.getBname(),book.getBisbn(),book.getBauthor(),book.getBpress(),book.getBtype(),book.getBstok() );
}
// 查询所有
public List<Book> findAll() throws Exception {
Connection conn = db.getConn();
String sql = "select * from books";

return qr.query(conn, sql, new BeanListHandler<Book>(Book.class));
}
// 更新
public Object updateBook(Book book) throws Exception {
Connection conn = db.getConn();
String sql = "update set books bname=?,bisbn=?,bauthor=?,bpress=?,btype=?,bstok=? where bid = ?";
return qr.update(conn, sql,book.getBname(),book.getBisbn(),book.getBauthor(),book.getBpress(),book.getBtype(),book.getBstok(),book.getBid());
}
// 删除
public Object deleteBook(int id) throws Exception {
Connection conn = db.getConn();
String sql = "delete * from books where bid = ?";
return qr.update(conn,sql, id, null);
}

}

BookService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package service;

import java.util.List;
import dao.BookDao;
import model.Book;

public class BookService {

BookDao bd = new BookDao();
// 添加
public Object addBook(Book book) throws Exception {

return bd.addBook(book);
}
// 查询所有
public List<Book> findAll() throws Exception {

return bd.findAll();
}

// 更新
public Object updateBook(Book book) throws Exception {

return bd.updateBook(book);
}

// 删除
public Object deleteBook(int id) throws Exception {

return bd.deleteBook(id);
}
}

BookServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package servlet;

import java.io.IOException;
import java.lang.reflect.Method;

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 model.Book;
import service.BookService;


/**
* Servlet implementation class BookServlet
*/
@WebServlet("/books")
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 根据请求参数来判断处理方法
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
Class<? extends BookServlet> clazz = this.getClass();
try {
Method metod = clazz.getMethod(action,HttpServletRequest.class,HttpServletResponse.class);
if(metod != null) {
String returns = (String) metod.invoke(this,req,resp);
if(returns != null) {
req.getRequestDispatcher(returns).forward(req, resp);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 新增
public String insert(HttpServletRequest req, HttpServletResponse resp) {
// bid、bname、bisbn、bauthor、、btype、bstok

int bstok = Integer.getInteger(req.getParameter("bstok"));
Book book = new Book(req.getParameter("bname"),req.getParameter("bisbn"),
req.getParameter("bauthor"),req.getParameter("bpress"),req.getParameter("btype"),bstok);
BookService bs = new BookService();
String url = null;
try {
Object obj = bs.addBook(book);
if("1".equals(obj.toString())) {
url = "/showServlet";
}
url = "/add.jsp";
} catch (Exception e) {
throw new RuntimeException(e);
}

return url;


}
// 删除
public String delete(HttpServletRequest req, HttpServletResponse resp) {
int id = Integer.getInteger(req.getParameter("bid"));
BookService bs = new BookService();
String url = null;
try {
Object obj = bs.deleteBook(id);
if("1".equals(obj.toString())) {
url = "/showServlet";
}
url = "/list.jsp";
} catch (Exception e) {

e.printStackTrace();
}
return url;


}
// 更新
public String update(HttpServletRequest req, HttpServletResponse resp) {
int bid = Integer.getInteger(req.getParameter("bid"));
int bstok = Integer.getInteger(req.getParameter("bstok"));
Book book = new Book(bid,req.getParameter("bname"),req.getParameter("bisbn"),
req.getParameter("bauthor"),req.getParameter("bpress"),req.getParameter("btype"),bstok);
BookService bs = new BookService();

String url = null;
try {

Object obj = bs.updateBook(book);
if("1".equals(obj.toString())) {
url = "/showServlet";
}
url = "/update.jsp";
} catch (Exception e) {
throw new RuntimeException(e);
}

return url;

}
}

ShowServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ShowServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 回显页面
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BookService bs = new BookService();
try {
List<Book> books = bs.findAll();
request.setAttribute("books", books);
request.getRequestDispatcher("/list.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}

连接数据库的工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class dbUtils {
private static String url;
private static String name;
private static String pwd;
private static Connection con;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
url="jdbc:mysql://localhost:3306/test";
name="root";
pwd="123456";
con= DriverManager.getConnection(url, name, pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConn() throws Exception{
return con;
}
public void close(Connection conn){
try {
conn.close();
} catch (SQLException e) {

e.printStackTrace();
}
}
}

分页案例

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×