Java Server Pages: java服务器端页面
可以理解为:一个特殊的页面,其中既可以指定定义html标签,又可以定义java代码
用于简化书写!!!
SP本质上就是一个Servlet3.
JSP定义Java代码的方式
<% 代码 %>:定义的java代码,在service方法中。service方法中可以定义什么,该脚本中就可以定义什么。
<%! 代码 %>:定义的java代码,在jsp转换后的java类的成员位置。
<%= 代码 %>:定义的java代码,会输出到页面上。输出语句中可以定义什么,该脚本中就可以定义什么。
在jsp页面中不需要获取和创建,可以直接使用的对象
jsp一共有9个内置对象。
可以将数据输出到页面上。和response.getWriter()类似
response.getWriter()和out.write()的区别:
在tomcat服务器真正给客户端做出响应之前,会先找response缓冲区数据,再找out缓冲区数据。 response.getWriter()数据输出永远在out.write()之前
<%@ page import="java.util.Date" %> <%@ page import="java.text.SimpleDateFormat" %> <%@ page import="java.net.URLEncoder" %> <%@ page import="java.net.URLDecoder" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>itcast</title> </head> <body> <% //1.获取所有Cookie Cookie[] cookies = request.getCookies(); boolean flag = false;//没有cookie为lastTime //2.遍历cookie数组 if(cookies != null && cookies.length > 0){ for (Cookie cookie : cookies) { //3.获取cookie的名称 String name = cookie.getName(); //4.判断名称是否是:lastTime if("lastTime".equals(name)){ //有该Cookie,不是第一次访问 flag = true;//有lastTime的cookie //设置Cookie的value //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); System.out.println("编码前:"+str_date); //URL编码 str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println("编码后:"+str_date); cookie.setValue(str_date); //设置cookie的存活时间 cookie.setMaxAge(60 * 60 * 24 * 30);//一个月 response.addCookie(cookie); //响应数据 //获取Cookie的value,时间 String value = cookie.getValue(); System.out.println("解码前:"+value); //URL解码: value = URLDecoder.decode(value,"utf-8"); System.out.println("解码后:"+value); %> <h1>欢迎回来,您上次访问时间为:<%=value%></h1> <input> <% break; } } } if(cookies == null || cookies.length == 0 || flag == false){ //没有,第一次访问 //设置Cookie的value //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); System.out.println("编码前:"+str_date); //URL编码 str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println("编码后:"+str_date); Cookie cookie = new Cookie("lastTime",str_date); //设置cookie的存活时间 cookie.setMaxAge(60 * 60 * 24 * 30);//一个月 response.addCookie(cookie); %> <h1>您好,欢迎您首次访问</h1> <span></span> <% } %> <input> </body> </html>
作用:用于配置JSP页面,导入资源文件
格式:
<%@ 指令名称 属性名1=属性值1 属性名2=属性值2 ... %>
分类:
page: 配置JSP页面的
include : 页面包含的。导入页面的资源文件
<%@include file="top.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> prefix:前缀,自定义的
在jsp页面中不需要创建,直接使用的对象
变量名 | 真实类型 | 作用 |
---|---|---|
pageContext | PageContext | 当前页面共享数据,还可以获取其他八个内置对象 |
request | HttpServletRequest | 一次请求访问的多个资源(转发) |
session | HttpSession | 一次会话的多个请求间 |
application | ServletContext | 所有用户间共享数据 |
response | HttpServletResponse | 响应对象 |
page | Object | 当前页面(Servlet)的对象 this |
out | JspWriter | 输出对象,数据输出到页面上 |
config | ServletConfig | Servlet的配置对象 |
exception | Throwable | 异常对象 |
耦合性低,方便维护,可以利于分工协作
重用性高
${域名称.键名}:从指定域中获取指定键的值
${键名}:表示依次从最小的域中查找是否有该键对应的值,直到找到为止。
获取对象、List集合、Map集合的值
对象:${域名称.键名.属性名}
本质上会去调用对象的getter方法
<% User user=new User("张三",34,new Date()); request.setAttribute("u",user); %> <h1>el获取对象的值</h1> ${requestScope.u}<br> ${requestScope.u.name}<br> ${u.age}<br> ${u.birthday}<br>
List集合:${域名称.键名[索引]}
Map集合:
${域名称.键名.key名称} ${域名称.键名["key名称"]}
隐式对象:
el表达式中有11个隐式对象
pageContext:
获取jsp其他八个内置对象
${pageContext.request.contextPath}:动态获取虚拟目录
概念:JavaServer Pages Tag Library
JSP标准标签库
是由Apache组织提供的开源的免费的jsp标签
作用:用于简化和替换jsp页面上的java代码
导入jstl相关jar包
引入标签库:taglib指令: <%@ taglib %>
使用标签
属性:
test 必须属性,接受boolean表达式
如果表达式为true,则显示if标签体内容,如果为false,则不显示标签体内容
一般情况下,test属性值会结合el表达式一起使用
注意: c:if标签没有else情况,想要else情况,则可以在定义一个c:if标签
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: Lenovo Date: 2021/7/24 Time: 19:04 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>c:if</title> </head> <body> <c:if test="true"> 我是真。。。。 </c:if> <% int a=6; %> <c:if test="${number % 2 == 0}"> 是偶数。。。。 </c:if> </body> </html>
相当于switch声明
使用when标签做判断 ,相当于case
使用otherwise标签做其他情况的声明 ,相当于default 、
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: Lenovo Date: 2021/7/24 Time: 19:12 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>c:choose</title> </head> <body> <% request.setAttribute("number",5); %> <c:choose> <c:when test="${number==1}">周一</c:when> <c:when test="${number==2}">周二</c:when> <c:when test="${number==3}">周三</c:when> <c:when test="${number==4}">周四</c:when> <c:when test="${number==5}">周五</c:when> <c:when test="${number==6}">周六</c:when> <c:when test="${number==7}">周七</c:when> <c:otherwise>您输入的有误!!!</c:otherwise> </c:choose> </body> </html>
完成重复的操作
for(int i = 0; i < 10; i ++){
}
属性:
begin:开始值
end:结束值
var:临时变量
step:步长
varStatus:循环状态对象
遍历容器
List< User> list;
for(User user : list){
}
属性:
items:容器对象
var:容器中元素的临时变量
varStatus:循环状态对象
index:容器中元素的索引,从0开始
count:循环次数,从1开始
<%@ page import="java.util.ArrayList" %> <%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>foreach标签</title> </head> <body> <c:forEach begin="1" end="10" var="i" step="2" varStatus="s"> ${i} <h3>${s.index}<h3> <h4> ${s.count} </h4><br> </c:forEach> <hr> <% List list = new ArrayList(); list.add("aaa"); list.add("bbb"); list.add("ccc"); request.setAttribute("list",list); %> <c:forEach items="${list}" var="str" varStatus="s"> ${s.index} ${s.count} ${str}<br> </c:forEach> </body> </html>
需求:在request域中有一个存有User对象的List集合。需要使用jstl+el将list集合数据展示到jsp页面的表格table中
package itcast.pojo; import java.util.Date; public class User { private String name; private int age; private Date birthday; public User(String name, int age, Date birthday) { this.name = name; this.age = age; this.birthday = birthday; } public User() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", birthday=" + birthday + '}'; } }
<%@ page import="cn.itcast.domain.User" %> <%@ page import="java.util.List" %> <%@ page import="java.util.ArrayList" %> <%@ page import="java.util.Date" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>test</title> </head> <body> <% List list = new ArrayList(); list.add(new User("张三",23,new Date())); list.add(new User("李四",24,new Date())); list.add(new User("王五",25,new Date())); request.setAttribute("list",list); %> <table border="1" width="500" align="center"> <tr> <th>编号</th> <th>姓名</th> <th>年龄</th> <th>生日</th> </tr> <%--数据行--%> <c:forEach items="${list}" var="user" varStatus="s"> <c:if test="${s.count % 2 != 0}"> <tr bgcolor="red"> <td>${s.count}</td> <td>${user.name}</td> <td>${user.age}</td> <td>${user.birStr}</td> </tr> </c:if> <c:if test="${s.count % 2 == 0}"> <tr bgcolor="green"> <td>${s.count}</td> <td>${user.name}</td> <td>${user.age}</td> <td>${user.birStr}</td> </tr> // </c:if> </c:forEach> </table> </body> </html>
界面层(表示层web):用户看的得界面。用户可以通过界面上的组件和服务器进行交互
业务逻辑层service:处理业务逻辑的。
数据访问层dao:操作数据存储文件。
需求:用户信息的增删改查操作
设计:
技术选型:Servlet+JSP+MySQL+JDBCTempleat+Duird+BeanUtilS+tomcat
数据库设计:
开发:
create database day17; -- 创建数据库 use day17; -- 使用数据库 create table user( -- 创建表 id int primary key auto_increment, name varchar(20) not null, gender varchar(5), age int, address varchar(32), qq varchar(20), email varchar(50) );
INSERT INTO `user` VALUES (1, '张三', '男', 23, '河北省', '2623222222', '2623222222@qq.com'); INSERT INTO `user` VALUES (2, '李四', '男', 33, '河南省', '2625555555', '2625555555@qq.com'); INSERT INTO `user` VALUES (3, '王五', '女', 27, '重庆', '4522222268', '4522222268@qq.com'); INSERT INTO `user` VALUES (4, '柳六', '男', 13, '陕西', '12345', 'zhangsan@itcast.cn'); INSERT INTO `user` VALUES (5, '钱七', '女', 15, '北京', '88888', 'ls@itcast.cn');
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql:///javawebs username=root password=root # 初始化连接数量 initialSize=5 # 最大连接数 maxActive=10 # 最大等待时间 maxWait=3000
package cn.gtt.pojo; public class User { private int id; private String name; private String genter; private int age; private String address; private String qq; private String email; public User(int id, String name, String genter, int age, String address, String qq, String email) { this.id = id; this.name = name; this.genter = genter; this.age = age; this.address = address; this.qq = qq; this.email = email; } public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenter() { return genter; } public void setGenter(String genter) { this.genter = genter; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", genter='" + genter + '\'' + ", age=" + age + ", address='" + address + '\'' + ", qq='" + qq + '\'' + ", email='" + email + '\'' + '}'; } }
package cn.gtt.dao; import cn.gtt.pojo.User; import java.util.List; /** * 用户操作的dao */ public interface UserDao { /** * 查询所有用户信息 */ public List<User> findAll(); }
package cn.gtt.dao.Impl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.util.JDBCUtils; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; public class UserDaoImpl implements UserDao { private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource()); /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 使用JDBC操作数据库 String sql="select * from user"; List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } }
package cn.gtt.service; import cn.gtt.pojo.User; import java.util.List; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); }
package cn.gtt.service.Impl; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl() ; /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 调用userDao完成 return userDao.findAll(); } }
package cn.gtt.util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * Druid连接池的工具类 */ public class JDBCUtils { // 定义成员变量DataSource private static DataSource dataSource; static { try { // 加载配置文件 Properties properties = new Properties(); properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); // 获取DataSource dataSource= DruidDataSourceFactory.createDataSource(properties); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接 */ public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } /** * 释放资源 */ public static void close(ResultSet resultSet,Statement statement, Connection connection){ if(resultSet!=null){ try { resultSet.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(statement!=null){ try { statement.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } /** * 获取连接池方法 */ public static DataSource getDataSource(){ return dataSource; } }
package cn.gtt.web.servlet; import cn.gtt.pojo.User; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; 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 java.io.IOException; import java.util.List; @WebServlet("/userListServlet") public class UserListServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 调用UserService完成查询 UserService userService = new UserServiceImpl(); List<User> users = userService.findAll(); // 将list存入request域 req.setAttribute("users",users); // 转发到list.jsp req.getRequestDispatcher("/list.jsp").forward(req,resp); } }
<%-- Created by IntelliJ IDEA. User: Lenovo Date: 2021/7/24 Time: 20:37 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>首页</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <script type="text/javascript"> </script> </head> <body> <div align="center"> <a <%-- ${pageContext.request.contextPath}来表示请求路径--%> href="${pageContext.request.contextPath}/userListServlet" style="text-decoration:none;font-size:33px">查询所有用户信息 </a> </div> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach var="user" varStatus="s" items="${users}"> <tr> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td><a class="btn btn-default btn-sm" href="update.html">修改</a> <a class="btn btn-default btn-sm" href="">删除</a></td> </tr> </c:forEach> <tr> <td colspan="8" align="center"><a class="btn btn-primary" href="add.html">添加联系人</a></td> </tr> </table> </div> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float:left;"> <form class="form-inline"> <div class="form-group"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2"> </div> <div class="form-group"> <label for="exampleInputEmail2">籍贯</label> <input type="email" class="form-control" id="exampleInputEmail2" > </div> <div class="form-group"> <label for="exampleInputEmail2">E-mail</label> <input type="email" class="form-control" id="exampleInputEmail2" > </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right;margin: 5px;"> <a class="btn btn-primary" href="add.html">添加联系人</a> <a class="btn btn-primary" href="add.html">删除选中</a> </div> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach var="user" varStatus="s" items="${users}"> <tr> <td><input type="checkbox"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td><a class="btn btn-default btn-sm" href="update.html">修改</a> <a class="btn btn-default btn-sm" href="">删除</a></td> </tr> </c:forEach> </table> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px;margin-left: 20px">共16条记录,共4页</span> </ul> </nav> </div> </div> </body> </html>
验证码问题
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>管理员登录</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <script type="text/javascript"> //切换验证码 function refreshCode(){ //1.获取验证码图片对象 var vcode = document.getElementById("vcode"); //2.设置其src属性,加时间戳 vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime(); } </script> </head> <body> <div class="container" style="width: 400px;"> <h3 style="text-align: center;">管理员登录</h3> <form action="${pageContext.request.contextPath}/loginServlet" method="post"> <div class="form-group"> <label for="user">用户名:</label> <input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/> </div> <div class="form-group"> <label for="password">密码:</label> <input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/> </div> <div class="form-inline"> <label for="vcode">验证码:</label> <input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/> <a href="javascript:refreshCode();"> <img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/> </a> </div> <hr/> <div class="form-group" style="text-align: center;"> <input class="btn btn btn-primary" type="submit" value="登录"> </div> </form> <!-- 出错显示的信息框 --> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" > <span>×</span> </button> <strong>${login_msg}</strong> </div> </div> </body> </html>
<%-- Created by IntelliJ IDEA. User: Lenovo Date: 2021/7/24 Time: 20:37 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>首页</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <script type="text/javascript"> </script> </head> <body> <div align="center"> <a <%-- ${pageContext.request.contextPath}来表示请求路径--%> href="${pageContext.request.contextPath}/userListServlet" style="text-decoration:none;font-size:33px">查询所有用户信息 </a> </div> </body> </html>
package cn.gtt.pojo; public class User { private int id; private String name; private String gender; private int age; private String address; private String qq; private String email; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User(int id, String name, String gender, int age, String address, String qq, String email) { this.id = id; this.name = name; this.gender = gender; this.age = age; this.address = address; this.qq = qq; this.email = email; } public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", gender='" + gender + '\'' + ", age=" + age + ", address='" + address + '\'' + ", qq='" + qq + '\'' + ", email='" + email + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
package cn.gtt.dao; import cn.gtt.pojo.User; import java.util.List; /** * 用户操作的dao */ public interface UserDao { /** * 查询所有用户信息 */ public List<User> findAll(); /** * 登录 * @param username * @param password * @return */ User findUserByUsernamePassword(String username,String password); }
package cn.gtt.dao.Impl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.util.JDBCUtils; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; public class UserDaoImpl implements UserDao { private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource()); /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 使用JDBC操作数据库 String sql="select * from user"; List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } /** * 登录 * @param username * @param password * @return */ @Override public User findUserByUsernamePassword(String username, String password) { try { String sql="select * from user where username=? and password=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password); return user; }catch (Exception e){ e.printStackTrace(); return null; } } }
package cn.gtt.service; import cn.gtt.pojo.User; import java.util.List; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 登录 * @param user * @return */ User login(User user); }
package cn.gtt.service.Impl; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl() ; /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 调用userDao完成 return userDao.findAll(); } /** * 登录 * @param user * @return */ @Override public User login(User user) { return userDao.findUserByUsernamePassword(user.getUsername(),user.getPassword()); } }
package cn.gtt.web.servlet; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.pojo.User; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; import org.apache.commons.beanutils.BeanUtils; 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 javax.servlet.http.HttpSession; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.设置编码格式 req.setCharacterEncoding("utf-8"); // 2.获取数据 // 2.1 获取用户填写验证码 String verifycode = req.getParameter("verifycode"); // 3.验证码校验 HttpSession session = req.getSession(); String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER"); // 确保验证码一次性 session.removeAttribute("CHECKCODE_SERVER"); if (!checkcode_server.equalsIgnoreCase(verifycode)){ // 验证码不正确 // 提示信息 req.setAttribute("login_msg","验证码错误!!!"); // 转跳登录页面 req.getRequestDispatcher("/login.jsp").forward(req,resp); return; } // 4.封装user对象 Map<String, String[]> parameterMap = req.getParameterMap(); User user=new User(); try { BeanUtils.populate(user,parameterMap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // 5.调用service查询 UserService userService = new UserServiceImpl(); User login = userService.login(user); // 6.判断是否登录成功 if (login!=null){ // 将用户存入session session.setAttribute("user",login); // 跳转页面 resp.sendRedirect(req.getContextPath()+"/index.jsp"); }else{ // 提示信息 req.setAttribute("login_msg","用户名或密码错误!!!"); // 转跳登录页面 req.getRequestDispatcher("/login.jsp").forward(req,resp); } } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float:left;"> <form class="form-inline"> <div class="form-group"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2"> </div> <div class="form-group"> <label for="exampleInputEmail2">籍贯</label> <input type="email" class="form-control" id="exampleInputEmail2" > </div> <div class="form-group"> <label for="exampleInputEmail2">E-mail</label> <input type="email" class="form-control" id="exampleInputEmail2" > </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right;margin: 5px;"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <a class="btn btn-primary" href="add.html">删除选中</a> </div> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach var="user" varStatus="s" items="${users}"> <tr> <td><input type="checkbox"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td><a class="btn btn-default btn-sm" href="update.html">修改</a> <a class="btn btn-default btn-sm" href="">删除</a></td> </tr> </c:forEach> </table> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px;margin-left: 20px">共16条记录,共4页</span> </ul> </nav> </div> </div> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!-- HTML5文档--> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>添加用户</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> </head> <body> <div class="container"> <center><h3>添加联系人页面</h3></center> <form action="${pageContext.request.contextPath}/addUserServlet" method="post"> <div class="form-group"> <label for="name">姓名:</label> <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名"> </div> <div class="form-group"> <label>性别:</label> <input type="radio" name="gender" value="男" checked="checked"/>男 <input type="radio" name="gender" value="女"/>女 </div> <div class="form-group"> <label for="age">年龄:</label> <input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄"> </div> <div class="form-group"> <label for="address">籍贯:</label> <select name="address" class="form-control" id="address"> <option value="陕西">陕西</option> <option value="北京">北京</option> <option value="上海">上海</option> </select> </div> <div class="form-group"> <label for="qq">QQ:</label> <input type="text" class="form-control" id="qq" name="qq" placeholder="请输入QQ号码"/> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱地址"/> </div> <div class="form-group" style="text-align: center"> <input class="btn btn-primary" type="submit" value="提交" /> <input class="btn btn-default" type="reset" value="重置" /> <input class="btn btn-default" type="button" value="返回" /> </div> </form> </div> </body> </html>
package cn.gtt.dao; import cn.gtt.pojo.User; import java.util.List; /** * 用户操作的dao */ public interface UserDao { /** * 查询所有用户信息 */ public List<User> findAll(); /** * 登录 * @param username * @param password * @return */ User findUserByUsernamePassword(String username,String password); /** * 添加 * @param user */ public void addUser(User user); }
package cn.gtt.dao.Impl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.util.JDBCUtils; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; public class UserDaoImpl implements UserDao { private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource()); /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 使用JDBC操作数据库 String sql="select * from user"; List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } /** * 登录 * @param username * @param password * @return */ @Override public User findUserByUsernamePassword(String username, String password) { try { String sql="select * from user where username=? and password=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password); return user; }catch (Exception e){ e.printStackTrace(); return null; } } /** * 添加 * @param user */ @Override public void addUser(User user) { String sql="insert into user values(null,?,?,?,?,?,?,null,null)"; jdbcTemplate.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail()); } }
package cn.gtt.service; import cn.gtt.pojo.User; import java.util.List; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 登录 * @param user * @return */ User login(User user); /** * 添加 * @param user */ void addUser(User user); }
package cn.gtt.service.Impl; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl() ; /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 调用userDao完成 return userDao.findAll(); } /** * 登录 * @param user * @return */ @Override public User login(User user) { return userDao.findUserByUsernamePassword(user.getUsername(),user.getPassword()); } /** * 添加 * @param user */ @Override public void addUser(User user) { userDao.addUser(user); } }
package cn.gtt.web.servlet; import cn.gtt.pojo.User; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; import org.apache.commons.beanutils.BeanUtils; 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 java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/addUserServlet") public class AddUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.设置编码格式 req.setCharacterEncoding("utf-8"); // 获取参数 Map<String, String[]> parameterMap = req.getParameterMap(); // 封装对象 User user=new User(); try { BeanUtils.populate(user,parameterMap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // 调用service保存 UserService userService=new UserServiceImpl(); userService.addUser(user); // 转跳到userListServlet resp.sendRedirect(req.getContextPath()+"/userListServlet"); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> <script> function deleteUser(id){ // 用户安全显示 if(confirm("您确定要删除么?")){ // 访问路径 location.href=" ${pageContext.request.contextPath}/delUserServlet?id="+id; } } </script> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float:left;"> <form class="form-inline"> <div class="form-group"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2"> </div> <div class="form-group"> <label for="exampleInputEmail2">籍贯</label> <input type="email" class="form-control" id="exampleInputEmail2" > </div> <div class="form-group"> <label for="exampleInputEmail2">E-mail</label> <input type="email" class="form-control" id="exampleInputEmail2" > </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right;margin: 5px;"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <a class="btn btn-primary" href="">删除选中</a> </div> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach var="user" varStatus="s" items="${users}"> <tr> <td><input type="checkbox"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td> <a class="btn btn-default btn-sm" href="update.html">修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td> </tr> </c:forEach> </table> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px;margin-left: 20px">共16条记录,共4页</span> </ul> </nav> </div> </div> </body> </html>
package cn.gtt.dao; import cn.gtt.pojo.User; import java.util.List; /** * 用户操作的dao */ public interface UserDao { /** * 查询所有用户信息 */ public List<User> findAll(); /** * 登录 * @param username * @param password * @return */ User findUserByUsernamePassword(String username,String password); /** * 添加 * @param user */ public void addUser(User user); /** * 删除 * @param id */ public void deleteUser(int id); }
package cn.gtt.dao.Impl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.util.JDBCUtils; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; public class UserDaoImpl implements UserDao { private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource()); /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 使用JDBC操作数据库 String sql="select * from user"; List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } /** * 登录 * @param username * @param password * @return */ @Override public User findUserByUsernamePassword(String username, String password) { try { String sql="select * from user where username=? and password=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password); return user; }catch (Exception e){ e.printStackTrace(); return null; } } /** * 添加 * @param user */ @Override public void addUser(User user) { String sql="insert into user values(null,?,?,?,?,?,?,null,null)"; jdbcTemplate.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail()); } /** * 删除 */ @Override public void deleteUser(int id) { String sql="delete from user where id=?"; jdbcTemplate.update(sql,id); } }
package cn.gtt.service; import cn.gtt.pojo.User; import java.util.List; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 登录 * @param user * @return */ User login(User user); /** * 添加 * @param user */ void addUser(User user); /** * 删除 */ void deleteUser(String id); }
package cn.gtt.service.Impl; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl() ; /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 调用userDao完成 return userDao.findAll(); } /** * 登录 * @param user * @return */ @Override public User login(User user) { return userDao.findUserByUsernamePassword(user.getUsername(),user.getPassword()); } /** * 添加 * @param user */ @Override public void addUser(User user) { userDao.addUser(user); } @Override public void deleteUser(String id) { userDao.deleteUser(Integer.parseInt(id)); } }
package cn.gtt.web.servlet; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; 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 java.io.IOException; @WebServlet("/delUserServlet") public class DelUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取id String id = req.getParameter("id"); // 调用service层删除 UserService userService=new UserServiceImpl(); userService.deleteUser(id); // 转跳到查询所有servlet resp.sendRedirect(req.getContextPath()+"/userListServlet"); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> <script> function deleteUser(id){ // 用户安全显示 if(confirm("您确定要删除么?")){ // 访问路径 location.href=" ${pageContext.request.contextPath}/delUserServlet?id="+id; } } </script> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float:left;"> <form class="form-inline"> <div class="form-group"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2"> </div> <div class="form-group"> <label for="exampleInputEmail2">籍贯</label> <input type="email" class="form-control" id="exampleInputEmail2" > </div> <div class="form-group"> <label for="exampleInputEmail2">E-mail</label> <input type="email" class="form-control" id="exampleInputEmail2" > </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right;margin: 5px;"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <a class="btn btn-primary" href="">删除选中</a> </div> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach var="user" varStatus="s" items="${users}"> <tr> <td><input type="checkbox"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td> <a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td> </tr> </c:forEach> </table> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px;margin-left: 20px">共16条记录,共4页</span> </ul> </nav> </div> </div> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>修改用户</title> <link href="css/bootstrap.min.css" rel="stylesheet"> <script src="js/jquery-2.1.0.min.js"></script> <script src="js/bootstrap.min.js"></script> </head> <body> <div class="container" style="width: 400px;"> <h3 style="text-align: center;">修改联系人</h3> <form action="${pageContext.request.contextPath}/updateUserServlet" method="post"> <!-- 隐藏域 提交id--> <input type="hidden" name="id" value="${user.id}"> <div class="form-group"> <label for="name">姓名:</label> <input type="text" class="form-control" id="name" name="name" value="${user.name}" readonly="readonly" placeholder="请输入姓名" /> </div> <div class="form-group"> <label>性别:</label> <c:if test="${user.gender == '男'}"> <input type="radio" name="gender" value="男" checked />男 <input type="radio" name="gender" value="女" />女 </c:if> <c:if test="${user.gender == '女'}"> <input type="radio" name="gender" value="男" />男 <input type="radio" name="gender" value="女" checked />女 </c:if> </div> <div class="form-group"> <label for="age">年龄:</label> <input type="text" class="form-control" value="${user.age}" id="age" name="age" placeholder="请输入年龄" /> </div> <div class="form-group"> <label for="address">籍贯:</label> <select name="address" id="address" class="form-control" > <c:if test="${user.address == '陕西'}"> <option value="陕西" selected>陕西</option> <option value="北京">北京</option> <option value="上海">上海</option> </c:if> <c:if test="${user.address == '北京'}"> <option value="陕西" >陕西</option> <option value="北京" selected>北京</option> <option value="上海">上海</option> </c:if> <c:if test="${user.address == '上海'}"> <option value="陕西" >陕西</option> <option value="北京">北京</option> <option value="上海" selected>上海</option> </c:if> </select> </div> <div class="form-group"> <label for="qq">QQ:</label> <input type="text" id="qq" class="form-control" value="${user.qq}" name="qq" placeholder="请输入QQ号码"/> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" id="email" class="form-control" value="${user.email}" name="email" placeholder="请输入邮箱地址"/> </div> <div class="form-group" style="text-align: center"> <input class="btn btn-primary" type="submit" value="提交" /> <input class="btn btn-default" type="reset" value="重置" /> <input class="btn btn-default" type="button" value="返回"/> </div> </form> </div> </body> </html>
package cn.gtt.dao; import cn.gtt.pojo.User; import java.util.List; /** * 用户操作的dao */ public interface UserDao { /** * 查询所有用户信息 */ public List<User> findAll(); /** * 登录 * @param username * @param password * @return */ User findUserByUsernamePassword(String username,String password); /** * 添加 * @param user */ public void addUser(User user); /** * 删除 * @param id */ public void deleteUser(int id); /** * 修改 */ User findUserById(int id); public void updateUser(User user); }
package cn.gtt.dao.Impl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.util.JDBCUtils; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; public class UserDaoImpl implements UserDao { private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource()); /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 使用JDBC操作数据库 String sql="select * from user"; List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } /** * 登录 * @param username * @param password * @return */ @Override public User findUserByUsernamePassword(String username, String password) { try { String sql="select * from user where username=? and password=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password); return user; }catch (Exception e){ e.printStackTrace(); return null; } } /** * 添加 * @param user */ @Override public void addUser(User user) { String sql="insert into user values(null,?,?,?,?,?,?,null,null)"; jdbcTemplate.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail()); } /** * 删除 */ @Override public void deleteUser(int id) { String sql="delete from user where id=?"; jdbcTemplate.update(sql,id); } /** * 修改 * @param id */ @Override public User findUserById(int id) { String sql="select * from user where id=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id); return user; } @Override public void updateUser(User user) { String sql="update user set name=?,gender=?,age=?,address=?,qq=?,email=? where id=?"; jdbcTemplate.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId()); } }
package cn.gtt.service; import cn.gtt.pojo.User; import java.util.List; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 登录 * @param user * @return */ User login(User user); /** * 添加 * @param user */ void addUser(User user); /** * 删除 */ void deleteUser(String id); /** * 修改 */ User findUserById(String id); public void updateUser(User user); }
package cn.gtt.service.Impl; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl() ; /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 调用userDao完成 return userDao.findAll(); } /** * 登录 * @param user * @return */ @Override public User login(User user) { return userDao.findUserByUsernamePassword(user.getUsername(),user.getPassword()); } /** * 添加 * @param user */ @Override public void addUser(User user) { userDao.addUser(user); } /** * 删除 * @param id */ @Override public void deleteUser(String id) { userDao.deleteUser(Integer.parseInt(id)); } /** * 修改 * @param id */ @Override public User findUserById(String id) { return userDao.findUserById(Integer.parseInt(id)); } @Override public void updateUser(User user) { userDao.updateUser(user); } }
package cn.gtt.web.servlet; import cn.gtt.pojo.User; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; 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 java.io.IOException; @WebServlet("/findUserServlet") public class FindUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); // 获取id String id = req.getParameter("id"); // 调用service查询 UserService userService=new UserServiceImpl(); User user=userService.findUserById(id); // 将user存入request req.setAttribute("user",user); req.getRequestDispatcher("/update.jsp").forward(req,resp); } }
package cn.gtt.web.servlet; import cn.gtt.pojo.User; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; import org.apache.commons.beanutils.BeanUtils; 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 java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/updateUserServlet") public class UpdateUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); // 获取map Map<String, String[]> parameterMap = req.getParameterMap(); // 封装对象 User user=new User(); try { BeanUtils.populate(user,parameterMap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // 调用service保存 UserService userService=new UserServiceImpl(); userService.updateUser(user); // 转跳到userListServlet resp.sendRedirect(req.getContextPath()+"/userListServlet"); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> <script> function deleteUser(id){ // 用户安全显示 if(confirm("您确定要删除么?")){ // 访问路径 location.href=" ${pageContext.request.contextPath}/delUserServlet?id="+id; } } window.onload=function (){ // 给删除选中按钮添加单击事件 document.getElementById("delSelected").onclick=function (){ if(confirm("您确定要删除选中条目吗?")){ var flag = false; //判断是否有选中条目 var cbs = document.getElementsByName("uid"); for (var i = 0; i < cbs.length; i++) { if(cbs[i].checked){ //有一个条目选中了 flag = true; break; } } if(flag){//有条目被选中 //表单提交 document.getElementById("form").submit(); } } } //1.获取第一个cb document.getElementById("firstCb").onclick = function(){ //2.获取下边列表中所有的cb var cbs = document.getElementsByName("uid"); //3.遍历 for (var i = 0; i < cbs.length; i++) { //4.设置这些cbs[i]的checked状态 = firstCb.checked cbs[i].checked = this.checked; } } } </script> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float:left;"> <form class="form-inline"> <div class="form-group"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2"> </div> <div class="form-group"> <label for="exampleInputEmail3">籍贯</label> <input type="email" class="form-control" id="exampleInputEmail3" > </div> <div class="form-group"> <label for="exampleInputEmail4">E-mail</label> <input type="email" class="form-control" id="exampleInputEmail4" > </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right;margin: 5px;"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">删除选中</a> </div> <form action="${pageContext.request.contextPath}/delSelectedServlet" method="post" id="form"> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox" id="firstCb"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach var="user" varStatus="s" items="${users}"> <tr> <td><input type="checkbox" name="uid" value="${user.id}"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td> <a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td> </tr> </c:forEach> </table> </form> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px;margin-left: 20px">共16条记录,共4页</span> </ul> </nav> </div> </div> </body> </html>
package cn.gtt.service; import cn.gtt.pojo.User; import java.util.List; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 登录 * @param user * @return */ User login(User user); /** * 添加 * @param user */ void addUser(User user); /** * 删除 */ void deleteUser(String id); /** * 修改 */ User findUserById(String id); public void updateUser(User user); /** * 删除选中 */ void delSelecteUser(String[] ids); }
package cn.gtt.service.Impl; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl() ; /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 调用userDao完成 return userDao.findAll(); } /** * 登录 * @param user * @return */ @Override public User login(User user) { return userDao.findUserByUsernamePassword(user.getUsername(),user.getPassword()); } /** * 添加 * @param user */ @Override public void addUser(User user) { userDao.addUser(user); } /** * 删除 * @param id */ @Override public void deleteUser(String id) { userDao.deleteUser(Integer.parseInt(id)); } /** * 修改 * @param id */ @Override public User findUserById(String id) { return userDao.findUserById(Integer.parseInt(id)); } @Override public void updateUser(User user) { userDao.updateUser(user); } /** * 删除选中 * @param ids */ @Override public void delSelecteUser(String[] ids) { if(ids != null && ids.length > 0){ //1.遍历数组 for (String id : ids) { //2.调用dao删除 userDao.deleteUser(Integer.parseInt(id)); } } } }
package cn.gtt.web.servlet; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; 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 java.io.IOException; @WebServlet("/delSelectedServlet") public class DelSelectedServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取所有的id String[] uids = req.getParameterValues("uid"); // 调用service删除 UserService userService=new UserServiceImpl(); userService.delSelecteUser(uids); resp.sendRedirect(req.getContextPath()+"/userListServlet"); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>首页</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <script type="text/javascript"> </script> </head> <body> <div >${user.name},欢迎您</div> <div align="center"> <a href="${pageContext.request.contextPath}/findUserByPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息 </a> </div> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> <script> function deleteUser(id){ // 用户安全显示 if(confirm("您确定要删除么?")){ // 访问路径 location.href=" ${pageContext.request.contextPath}/delUserServlet?id="+id; } } window.onload=function (){ // 给删除选中按钮添加单击事件 document.getElementById("delSelected").onclick=function (){ if(confirm("您确定要删除选中条目吗?")){ var flag = false; //判断是否有选中条目 var cbs = document.getElementsByName("uid"); for (var i = 0; i < cbs.length; i++) { if(cbs[i].checked){ //有一个条目选中了 flag = true; break; } } if(flag){//有条目被选中 //表单提交 document.getElementById("form").submit(); } } } //1.获取第一个cb document.getElementById("firstCb").onclick = function(){ //2.获取下边列表中所有的cb var cbs = document.getElementsByName("uid"); //3.遍历 for (var i = 0; i < cbs.length; i++) { //4.设置这些cbs[i]的checked状态 = firstCb.checked cbs[i].checked = this.checked; } } } </script> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float:left;" > <form class="form-inline"> <div class="form-group"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2"> </div> <div class="form-group"> <label for="exampleInputEmail3">籍贯</label> <input type="email" class="form-control" id="exampleInputEmail3" > </div> <div class="form-group"> <label for="exampleInputEmail4">E-mail</label> <input type="email" class="form-control" id="exampleInputEmail4" > </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right;margin: 5px;"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">删除选中</a> </div> <form action="${pageContext.request.contextPath}/delSelectedServlet" method="post" id="form"> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox" id="firstCb"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach items="${pb.list}" var="user" varStatus="s" > <tr> <td><input type="checkbox" name="uid" value="${user.id}"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td> <a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td> </tr> </c:forEach> </table> </form> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <c:if test="${pb.currentPage==1}"> <li class="disabled"> </c:if> <c:if test="${pb.currentPage!=1}"> <li > </c:if> <li> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage-1}&rows=5" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <c:forEach begin="1" end="${pb.totalPage}" var="i"> <c:if test="${pb.currentPage==i}"> <li class="active"> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5">${i}</a> </li> </c:if> <c:if test="${pb.currentPage!=i}"> <li> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5">${i}</a> </li> </c:if> </c:forEach> <li> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage+1}&rows=5" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px;margin-left: 20px">共${pb.totalCount}条记录,共${pb.totalPage}页</span> </ul> </nav> </div> </div> </body> </html>
package cn.gtt.dao; import cn.gtt.pojo.User; import java.util.List; /** * 用户操作的dao */ public interface UserDao { /** * 查询所有用户信息 */ public List<User> findAll(); /** * 登录 * @param username * @param password * @return */ User findUserByUsernamePassword(String username,String password); /** * 添加 * @param user */ public void addUser(User user); /** * 删除 * @param id */ void deleteUser(int id); /** * 修改 */ User findUserById(int id); public void updateUser(User user); /** * 分页 */ /** * 查询总记录数 * @return */ int findTotalCount(); /** * 分页查询每页记录 * @param start * @param rows * @return */ List<User> findByPage(int start,int rows); }
package cn.gtt.dao.Impl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.util.JDBCUtils; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; public class UserDaoImpl implements UserDao { private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource()); /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 使用JDBC操作数据库 String sql="select * from user"; List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } /** * 登录 * @param username * @param password * @return */ @Override public User findUserByUsernamePassword(String username, String password) { try { String sql="select * from user where username=? and password=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password); return user; }catch (Exception e){ e.printStackTrace(); return null; } } /** * 添加 * @param user */ @Override public void addUser(User user) { String sql="insert into user values(null,?,?,?,?,?,?,null,null)"; jdbcTemplate.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail()); } /** * 删除 */ @Override public void deleteUser(int id) { String sql="delete from user where id=?"; jdbcTemplate.update(sql,id); } /** * 修改 * @param id */ @Override public User findUserById(int id) { String sql="select * from user where id=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id); return user; } @Override public void updateUser(User user) { String sql="update user set name=?,gender=?,age=?,address=?,qq=?,email=? where id=?"; jdbcTemplate.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId()); } /** * 分页 */ /** * 查询总记录数 * @return */ @Override public int findTotalCount() { String sql="select count(*) from user"; return jdbcTemplate.queryForObject(sql,Integer.class); } /** * 分页查询每页记录 * @param start * @param rows * @return */ @Override public List<User> findByPage(int start, int rows) { String sql="select * from user limit ?,?"; return jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class),start,rows); } }
package cn.gtt.service; import cn.gtt.pojo.Page; import cn.gtt.pojo.User; import java.util.List; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 登录 * @param user * @return */ User login(User user); /** * 添加 * @param user */ void addUser(User user); /** * 删除 */ void deleteUser(String id); /** * 修改 */ User findUserById(String id); public void updateUser(User user); /** * 删除选中 */ void delSelecteUser(String[] ids); /** * 分页查询 */ Page<User> findUserByPage(String currentPage, String rows); }
package cn.gtt.service.Impl; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.Page; import cn.gtt.pojo.User; import cn.gtt.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl() ; /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 调用userDao完成 return userDao.findAll(); } /** * 登录 * @param user * @return */ @Override public User login(User user) { return userDao.findUserByUsernamePassword(user.getUsername(),user.getPassword()); } /** * 添加 * @param user */ @Override public void addUser(User user) { userDao.addUser(user); } /** * 删除 * @param id */ @Override public void deleteUser(String id) { userDao.deleteUser(Integer.parseInt(id)); } /** * 修改 * @param id */ @Override public User findUserById(String id) { return userDao.findUserById(Integer.parseInt(id)); } @Override public void updateUser(User user) { userDao.updateUser(user); } /** * 删除选中 * @param ids */ @Override public void delSelecteUser(String[] ids) { if(ids != null && ids.length > 0){ //1.遍历数组 for (String id : ids) { //2.调用dao删除 userDao.deleteUser(Integer.parseInt(id)); } } } /** * 分页查询 * @return */ @Override public Page<User> findUserByPage(String _currentPage, String _rows) { int currentPage=Integer.parseInt(_currentPage); int rows=Integer.parseInt(_rows); if (currentPage<=0){ currentPage=1; } // 创建空的page对象 Page<User> pb = new Page<User>(); // 设置参数 pb.setCurrentPage(currentPage); pb.setRows(rows); // 调用dao查询总记录数 int totalCount=userDao.findTotalCount(); pb.setTotalCount(totalCount); // 调用dao查询list集合 // 计算开始的记录 int start=(currentPage-1)*rows; List<User> list=userDao.findByPage(start,rows); pb.setList(list); // 计算总页码 int totalPage=totalCount%rows==0?totalCount/rows:(totalCount/rows+1); pb.setTotalPage(totalPage); // http://localhost:8080/findUserByPageServlet?currentPage=1&rows=5 System.out.println(pb); return pb; } }
package cn.gtt.web.servlet; import cn.gtt.pojo.Page; import cn.gtt.pojo.User; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; 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 java.io.IOException; @WebServlet("/findUserByPageServlet") public class FindUserByPageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取参数 // 当前页码 String currentPage = req.getParameter("currentPage"); // 每页显示的记录数 String rows = req.getParameter("rows"); if(currentPage==null||"".equals(currentPage)){ currentPage="1"; } if(rows==null||"".equals(rows)){ rows="5"; } // 调用service查询 UserService userService=new UserServiceImpl(); Page<User> pb=userService.findUserByPage(currentPage,rows); // 将Page存入request req.setAttribute("pb",pb); // 转发到list.jsp req.getRequestDispatcher("/list.jsp").forward(req,resp); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> <script> function deleteUser(id){ // 用户安全显示 if(confirm("您确定要删除么?")){ // 访问路径 location.href=" ${pageContext.request.contextPath}/delUserServlet?id="+id; } } window.onload=function (){ // 给删除选中按钮添加单击事件 document.getElementById("delSelected").onclick=function (){ if(confirm("您确定要删除选中条目吗?")){ var flag = false; //判断是否有选中条目 var cbs = document.getElementsByName("uid"); for (var i = 0; i < cbs.length; i++) { if(cbs[i].checked){ //有一个条目选中了 flag = true; break; } } if(flag){//有条目被选中 //表单提交 document.getElementById("form").submit(); } } } //1.获取第一个cb document.getElementById("firstCb").onclick = function(){ //2.获取下边列表中所有的cb var cbs = document.getElementsByName("uid"); //3.遍历 for (var i = 0; i < cbs.length; i++) { //4.设置这些cbs[i]的checked状态 = firstCb.checked cbs[i].checked = this.checked; } } } </script> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float:left;" > <form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post"> <div class="form-group"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2" name="name" value="${condition.name[0]}"> </div> <div class="form-group"> <label for="exampleInputEmail3">籍贯</label> <input type="text" class="form-control" id="exampleInputEmail3" name="address" value="${condition.address[0]}"> </div> <div class="form-group"> <label for="exampleInputEmail4">E-mail</label> <input type="text" class="form-control" id="exampleInputEmail4" name="email" value="${condition.email[0]}"> </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right;margin: 5px;"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">删除选中</a> </div> <form action="${pageContext.request.contextPath}/delSelectedServlet" method="post" id="form"> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox" id="firstCb"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach items="${pb.list}" var="user" varStatus="s" > <tr> <td><input type="checkbox" name="uid" value="${user.id}"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td> <a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td> </tr> </c:forEach> </table> </form> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <c:if test="${pb.currentPage==1}"> <li class="disabled"> </c:if> <c:if test="${pb.currentPage!=1}"> <li > </c:if> <li> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage-1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <c:forEach begin="1" end="${pb.totalPage}" var="i"> <c:if test="${pb.currentPage==i}"> <li class="active"> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a> </li> </c:if> <c:if test="${pb.currentPage!=i}"> <li> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a> </li> </c:if> </c:forEach> <li> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage+1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px;margin-left: 20px">共${pb.totalCount}条记录,共${pb.totalPage}页</span> </ul> </nav> </div> </div> </body> </html>
package cn.gtt.dao; import cn.gtt.pojo.User; import java.util.List; import java.util.Map; /** * 用户操作的dao */ public interface UserDao { /** * 查询所有用户信息 */ public List<User> findAll(); /** * 登录 * @param username * @param password * @return */ User findUserByUsernamePassword(String username,String password); /** * 添加 * @param user */ public void addUser(User user); /** * 删除 * @param id */ void deleteUser(int id); /** * 修改 */ User findUserById(int id); public void updateUser(User user); /** * 分页 */ /** * 查询总记录数 * @return * @param condition */ int findTotalCount(Map<String, String[]> condition); /** * 分页查询每页记录 * @param start * @param rows * @param condition * @return */ List<User> findByPage(int start, int rows, Map<String, String[]> condition); }
package cn.gtt.dao.Impl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.User; import cn.gtt.util.JDBCUtils; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class UserDaoImpl implements UserDao { private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource()); /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 使用JDBC操作数据库 String sql="select * from user"; List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } /** * 登录 * @param username * @param password * @return */ @Override public User findUserByUsernamePassword(String username, String password) { try { String sql="select * from user where username=? and password=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password); return user; }catch (Exception e){ e.printStackTrace(); return null; } } /** * 添加 * @param user */ @Override public void addUser(User user) { String sql="insert into user values(null,?,?,?,?,?,?,null,null)"; jdbcTemplate.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail()); } /** * 删除 */ @Override public void deleteUser(int id) { String sql="delete from user where id=?"; jdbcTemplate.update(sql,id); } /** * 修改 * @param id */ @Override public User findUserById(int id) { String sql="select * from user where id=?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id); return user; } @Override public void updateUser(User user) { String sql="update user set name=?,gender=?,age=?,address=?,qq=?,email=? where id=?"; jdbcTemplate.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId()); } /** * 分页 */ /** * 查询总记录数 * @return * @param condition */ @Override public int findTotalCount(Map<String, String[]> condition) { // 查询总记录数 // String sql="select count(*) from user"; // return jdbcTemplate.queryForObject(sql,Integer.class); // 定义模板初始化sql String sql="select count(*) from user where 1=1"; StringBuffer sb=new StringBuffer(sql); // 遍历map Set<String> keySet = condition.keySet(); // 定义一个参数的集合 List<Object> params = new ArrayList<>(); for(String key:keySet){ // 排除分页条件 if("currentPage".equals(key)||"rows".equals(key)){ continue; } // 根据键获取value String value = condition.get(key)[0]; // 判断value是否有值 if(value!=null&&!"".equals(value)){ // 有值 sb.append(" and "+key+" like ?"); // ?条件的值 params.add("%"+value+"%"); } } System.out.println(sb.toString()); System.out.println(params); return jdbcTemplate.queryForObject(sb.toString(),Integer.class,params.toArray()); } /** * 分页查询每页记录 * @param start * @param rows * @param condition * @return */ @Override public List<User> findByPage(int start, int rows, Map<String, String[]> condition) { String sql="select * from user where 1=1 "; StringBuffer sb=new StringBuffer(sql); // 遍历map Set<String> keySet = condition.keySet(); // 定义一个参数的集合 List<Object> params = new ArrayList<>(); for(String key:keySet){ // 排除分页条件 if("currentPage".equals(key)||"rows".equals(key)){ continue; } // 根据键获取value String value = condition.get(key)[0]; // 判断value是否有值 if(value!=null&&!"".equals(value)){ // 有值 sb.append(" and "+key+" like ?"); // ?条件的值 params.add("%"+value+"%"); } } // 添加分页查询 sb.append("limit ?,?"); params.add(start); params.add(rows); return jdbcTemplate.query(sb.toString(),new BeanPropertyRowMapper<User>(User.class),params.toArray()); } }
package cn.gtt.service; import cn.gtt.pojo.Page; import cn.gtt.pojo.User; import java.util.List; import java.util.Map; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 登录 * @param user * @return */ User login(User user); /** * 添加 * @param user */ void addUser(User user); /** * 删除 */ void deleteUser(String id); /** * 修改 */ User findUserById(String id); public void updateUser(User user); /** * 删除选中 */ void delSelecteUser(String[] ids); /** * 分页条件查询 * * 条件condition */ Page<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition); }
package cn.gtt.service.Impl; import cn.gtt.dao.Impl.UserDaoImpl; import cn.gtt.dao.UserDao; import cn.gtt.pojo.Page; import cn.gtt.pojo.User; import cn.gtt.service.UserService; import java.util.List; import java.util.Map; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl() ; /** * 查询所有用户信息 */ @Override public List<User> findAll() { // 调用userDao完成 return userDao.findAll(); } /** * 登录 * @param user * @return */ @Override public User login(User user) { return userDao.findUserByUsernamePassword(user.getUsername(),user.getPassword()); } /** * 添加 * @param user */ @Override public void addUser(User user) { userDao.addUser(user); } /** * 删除 * @param id */ @Override public void deleteUser(String id) { userDao.deleteUser(Integer.parseInt(id)); } /** * 修改 * @param id */ @Override public User findUserById(String id) { return userDao.findUserById(Integer.parseInt(id)); } @Override public void updateUser(User user) { userDao.updateUser(user); } /** * 删除选中 * @param ids */ @Override public void delSelecteUser(String[] ids) { if(ids != null && ids.length > 0){ //1.遍历数组 for (String id : ids) { //2.调用dao删除 userDao.deleteUser(Integer.parseInt(id)); } } } /** * 分页条件查询 * * 条件condition */ @Override public Page<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) { int currentPage=Integer.parseInt(_currentPage); int rows=Integer.parseInt(_rows); if (currentPage<=0){ currentPage=1; } // 创建空的page对象 Page<User> pb = new Page<User>(); // 设置参数 pb.setCurrentPage(currentPage); pb.setRows(rows); // 调用dao查询总记录数 int totalCount=userDao.findTotalCount(condition); pb.setTotalCount(totalCount); // 调用dao查询list集合 // 计算开始的记录 int start=(currentPage-1)*rows; List<User> list=userDao.findByPage(start,rows,condition); pb.setList(list); // 计算总页码 int totalPage=totalCount%rows==0?totalCount/rows:(totalCount/rows+1); pb.setTotalPage(totalPage); // http://localhost:8080/findUserByPageServlet?currentPage=1&rows=5 System.out.println(pb); return pb; } }
package cn.gtt.web.servlet; import cn.gtt.pojo.Page; import cn.gtt.pojo.User; import cn.gtt.service.Impl.UserServiceImpl; import cn.gtt.service.UserService; 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 java.io.IOException; import java.util.Map; @WebServlet("/findUserByPageServlet") public class FindUserByPageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); // 获取参数 // 当前页码 String currentPage = req.getParameter("currentPage"); // 每页显示的记录数 String rows = req.getParameter("rows"); if(currentPage==null||"".equals(currentPage)){ currentPage="1"; } if(rows==null||"".equals(rows)){ rows="5"; } // 获取条件查询参数 Map<String, String[]> condition = req.getParameterMap(); // 调用service查询 UserService userService=new UserServiceImpl(); Page<User> pb=userService.findUserByPage(currentPage,rows,condition); // 将Page存入request req.setAttribute("pb",pb); // 将查询条件存起来 req.setAttribute("condition",condition); // 转发到list.jsp req.getRequestDispatcher("/list.jsp").forward(req,resp); } }