<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>This is my first page!</title>
</head>
<body>
Now:<%=new java.util.Date() %>
</body>
</html>
Servlet
JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>脚本的使用</title>
</head>
<body>
<%
//jsp中, 使用小脚本嵌入Java代码
int a = 10;//普通脚本定义的是局部变量
System.out.println(a);//打印内容在控制台
out.println(a);//打印内容在客户端页面
%>
</body>
</html>
<%!
int b = 20;//声明脚本定义的是全局变量
public void test() {//定义一个无返回值的方法
System.out.println("你好");
}
public int test1() {//定义一个有返回值的方法
return 100;
}
%>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>脚本的使用</title>
</head>
<body>
<%=test1()%>
<%="今天天气很好!"%>
<%=666%>
<%=new Date()%>
</body>
</html>
<%-- JSP注释在网页中不会被显示 --%>
<%!-- HTML注释在网页源代码中会显示 --%>
<%@include file="header.jsp"%>
...
...
<%@include file="footer.jsp"%>
<%@ taglib url="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:include page="index.jsp"/>
<jsp:useBean id="user" class="com.dz.entity.User" />
<jsp:useBean id="user" class="com.dz.entity.User" />
<jsp:setProperty name="user" property="name" value="mars">
<jsp:useBean id="user" class="com.dz.entity.User" />
<jsp:setProperty name="user" property="name" value="mars" />
<jsp:getProperty name="user" property="name" />
<jsp:forward page="index.jsp" />
<jsp:forward page="index.jsp">
<!--- http请求参数传递 --->
<jsp:param name="sex" value="man" />
</jsp:forward>
由JSP自动创建的对象, 可以直接使用
对象名 类型 说明
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession 由session="true"开关
**application ** javax.servlet.ServletContext
config javax.servlet.ServletConfig
exception java.lang.Throwable 由isErrorPage="false"开关
out javax.servlet.jsp.JspWriter
**pageContext ** javax.servlet.jsp.PageContext
page java.lang.Object当前对象this 当前servlet实例
<%
pageContext.setAttribute("name",value);//当前页面作用域有效
%>
<%
pageContext.getRequest();//返回request内置对象
pageContext.getResponse();//返回response内置对象
pageContext.getSession();//返回session内置对象
pageContext.getServletContext();//返回application内置对象
pageContext.getOut();//返回out内置对象
pageContext.getException();//返回exception内置对象
pageContext.getPage();//返回page内置对象
pageContext.getServletConfig();//返回config内置对象
%>
<%
/*操作其他作用域存储*/
pageContext.setAttribute("page", "123", PageContext.PAGE_SCOPE);//当前页面作用域
pageContext.setAttribute("req","aaa", PageContext.REQUEST_SCOPE);//request作用域
pageContext.setAttribute("session","bbb", PageContext.SESSION_SCOPE);//session作用域
pageContext.setAttribute("application","ccc", PageContext.APPLICATION_SCOPE);//application作用域
/*操作其他作用域获取*/
String value = (String) pageContext.getAttribute("page");//当前页面作用域
String value1 = (String) request.getAttribute("req");//request作用域
String value2 = (String) session.getAttribute("session");//session作用域
String value3 = (String) application.getAttribute("application");//application作用域
String value4 = (String) pageContext.findAttribute("req");//从pageContext, request, session, application四个作用域中依次查找
%>
<%@ page import="com.dz.emp.entity.Emp" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>查询所有员工页面</title>
</head>
<body>
<form action=‘/EmpProject/manager/safe/showInsertEmp.jsp‘>
<p><input type=‘submit‘ value=‘新增‘></p>
</form>
<table border=‘1‘>
<tr>
<td>编号</td>
<td>姓名</td>
<td>工资</td>
<td>年龄</td>
<td colspan=‘2‘>操作</td>
</tr>
<%
List<Emp> empList = (List<Emp>) request.getAttribute("empList");//从request中拿数据
for (Emp emp : empList) {
%>
<tr>
<td><%=emp.getId()%></td>
<td><%=emp.getName()%></td>
<td><%=emp.getSalary()%></td>
<td><%=emp.getAge()%></td>
<td><a href="<%=request.getContextPath()+"/manager/safe/removeEmpController?id="+emp.getId()%>">删除</a></td>
<td><a href="<%=request.getContextPath()+"/manager/safe/showEmpController?id="+emp.getId()%>">修改</a></td>
</tr>
<%
}
%>
</table>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增员工信息页面</title>
</head>
<body>
<form action=‘/EmpProject/manager/safe/insertEmpController‘ method=‘post‘>
<p>姓名:<input type=‘text‘ name=‘name‘></p>
<p>工资:<input type=‘text‘ name=‘salary‘></p>
<p>年龄:<input type=‘text‘ name=‘age‘></p>
<p><input type=‘submit‘ value=‘提交‘></p>
</form>
</body>
</html>
<%@ page import="com.dz.emp.entity.Emp" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改员工信息页面</title>
</head>
<body>
<%
Emp emp = (Emp) request.getAttribute("emp");
%>
<form action=‘/EmpProject/manager/safe/updateEmpController‘ method=‘post‘>
<p>编号:<input type=‘text‘ name=‘id‘ value=<%=emp.getId()%> readonly></p>
<p>姓名:<input type=‘text‘ name=‘name‘ value=<%=emp.getName()%>></p>
<p>工资:<input type=‘text‘ name=‘salary‘ value=<%=emp.getSalary()%>></p>
<p>年龄:<input type=‘text‘ name=‘age‘ value=<%=emp.getAge()%>></p>
<p><input type=‘submit‘ value=‘修改‘></p>
</form>
</body>
</html>
<body>
<%
request.setAttribute("key1","value1");
session.setAttribute("key2", "value2");
application.setAttribute("key3", "value3");
%>
<%--通过作用域对象获取数据--%>
<h1><%=request.getAttribute("key1")%></h1>
<h1><%=session.getAttribute("key2")%></h1>
<h1><%=application.getAttribute("key3")%></h1>
<hr/>
<%--通过EL表达式获取数据--%>
<h1>${requestScope.key1}</h1>
<h1>${sessionScope.key2}</h1>
<h1>${applicationScope.key3}</h1>
<hr/>
<h1>${key1}</h1>
<h1>${key2}</h1>
<h1>${key3}</h1>
</body>
<%@ page import="com.dz.entity.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>El获取对象</title>
</head>
<body>
<%
User user = new User("mars","123");
request.setAttribute("user",user);
%>
${user}<br>
${user.username}<br>
${user.password}<br>
</body>
</html>
<%
int[] array = new int[]{1,2,3,4,5};
request.setAttribute("array",array);
List<String> nums = new ArrayList<>();
nums.add("A");
nums.add("B");
nums.add("C");
request.setAttribute("nums",nums);
Map<String,String> maps = new HashMap<>();
maps.put("CN","中国");
maps.put("US","美国");
maps.put("UK","英国");
request.setAttribute("maps",maps);
%>
<%--EL访问数据--%>
${array[0]}<br>
${array[1]}<br>
${array[2]}<br>
<hr>
${nums[0]}<br>
${nums[1]}<br>
${nums.get(2)}<br>
<hr>
${maps["CN"]}<br>
${maps["US"]}<br>
${maps.UK}<br>
操作符
<%
request.setAttribute("nums",100);
request.setAttribute("n","");
request.setAttribute("m",null);
%>
<h1>算数运算符</h1>
<h1>${nums + 2}</h1>
<h1>${nums - 2}</h1>
<h1>${nums * 2}</h1>
<h1>${nums div 2}</h1>
<h1>${nums mod 2}</h1>
<hr>
<h1>关系运算符</h1>
<h1>${nums eq 101}</h1><%-- = --%>
<h1>${nums ne 101}</h1><%-- != --%>
<h1>${nums lt 101}</h1><%-- < --%>
<h1>${nums gt 101}</h1><%-- > --%>
<h1>${nums le 101}</h1><%-- <= --%>
<h1>${nums ge 101}</h1><%-- >= --%>
<hr>
<h1>逻辑运算符</h1>
<h1>${nums > 100 and nums < 200}</h1>
<h1>${nums > 100 or nums < 200}</h1>
<h1>${not(nums > 100)}</h1>
<hr>
<h1>empty运算符</h1>
<h1>${empty n}</h1>
<h1>${empty m}</h1>
<%
request.setAttribute("n","");
request.setAttribute("m",null);
%>
<%--empty关键字 只要内容为空 就返回true--%>
<h1>empty运算符</h1>
<h1>${empty n}</h1>
<h1>${empty m}</h1>
<%=request.getContextPath()%>
${pageContext.request.contextPath}
<h1>${cookie.username}</h1><%--获取名为username的cookie对象--%>
<h1>${cookie.password}</h1><%--获取名为password的cookie对象--%>
<h1>${cookie.username.value}</h1><%--获取名为username的cookie对象的value值--%>
<h1>${cookie.password.value}</h1><%--获取名为password的cookie对象的value值--%>
<%
request.setAttribute("username","dz");
%>
${username}
<%-- test属性中是条件, 但是条件需要使用EL表达式来书写 --%>
<c:if test="${username eq ‘dz‘}">
<h1>欢迎您, ${username}</h1>
</c:if>
<c:if test="${username ne ‘dz‘}">
<h1>请您重新登陆!</h1>
</c:if>
语法: < c:choose>
<c:when test="条件1">结果1< /c:when>
<c:when test="条件2">结果2< /c:when>
<c:when test="条件3">结果3< /c:when>
< c:otherwise>结果4< /c:otherwise>
< /c:choose>
<%
request.setAttribute("age",18);
%>
<c:choose>
<c:when test="${age < 18}"><h1>少年</h1></c:when>
<c:when test="${age >= 18 and age < 30}"><h1>中年</h1></c:when>
<c:when test="${age >= 30 and age < 50}"><h1>中年</h1></c:when>
<c:otherwise><h1>老年</h1></c:otherwise>
</c:choose>
语法
<c:forEach var="变量名" items="集合" begin="起始下标" end="结束下标" step="间隔长度" varstatus="遍历状态"> </c:forEach>
<%
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
request.setAttribute("list",list);
%>
<%-- varStatus: 变量状态: 遍历出每一项内容的状态
first: 是否是第一行
last: 是否是最后一行
count: 当前行数
index: 当前元素的下标
--%>
<%-- var: 遍历出的每一项使用变量先存储
items: 集合(使用EL表达式)
--%>
<c:forEach var="v" items="${list}" begin="0" end="4" step="1" varStatus="vs">
<h1>${v} ${vs.first} ${vs.last} ${vs.count} ${vs.index}</h1>
</c:forEach>
<%--重写URL,拼接jsessionid(旧方法)--%>
<%
String newURL = response.encodeRedirectURL(request.getContextPath()+"/jstl/jstl1.jsp");
%>
<%=newURL%>
<a href="<%=response.encodeRedirectURL(request.getContextPath()+"/jstl/jstl1.jsp")%>">跳转</a><br>
<%--重写URL,拼接jsessionid(新方法,使用url标签)--%>
<c:url context=‘${pageContext.request.contextPath}‘ value=‘/jstl/jstl1.jsp‘></c:url>
<a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/jstl/jstl1.jsp‘></c:url>">跳转2</a>
<%--在form表单的action中嵌套动态路径--%>
<form action="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/jstl/jstl1.jsp‘></c:url>">
<input type="submit" value="提交">
</form>
<%@ page import="com.dz.emp.entity.Emp" %>
<%@ 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>查询所有员工页面</title>
</head>
<body>
<form action="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/showInsertEmp.jsp‘></c:url>">
<p><input type=‘submit‘ value=‘新增‘></p>
</form>
<table border=‘1‘>
<tr>
<td>编号</td>
<td>姓名</td>
<td>工资</td>
<td>年龄</td>
<td colspan=‘2‘>操作</td>
</tr>
<c:forEach var="emp" items="${empList}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.age}</td>
<td><a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/removeEmpController?id=${emp.id}‘></c:url>">删除</a></td>
<td><a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/showEmpController?id=${emp.id}‘></c:url>">修改</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
<%@ page import="com.dz.emp.entity.Emp" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>修改员工信息页面</title>
</head>
<body>
<form action="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/updateEmpController‘></c:url>" method=‘post‘>
<p>编号:<input type=‘text‘ name=‘id‘ value=${emp.id} readonly></p>
<p>姓名:<input type=‘text‘ name=‘name‘ value=${emp.name}></p>
<p>工资:<input type=‘text‘ name=‘salary‘ value=${emp.salary}></p>
<p>年龄:<input type=‘text‘ name=‘age‘ value=${emp.age}></p>
<p><input type=‘submit‘ value=‘修改‘></p>
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>新增员工信息页面</title>
</head>
<body>
<form action=‘<c:url context="${pageContext.request.contextPath}" value="/manager/safe/insertEmpController"></c:url>‘ method=‘post‘>
<p>姓名:<input type=‘text‘ name=‘name‘></p>
<p>工资:<input type=‘text‘ name=‘salary‘></p>
<p>年龄:<input type=‘text‘ name=‘age‘></p>
<p><input type=‘submit‘ value=‘提交‘></p>
</form>
</body>
</html>
View层 (表示|界面层)、Service层 (业务逻辑层)、DAO层(数据访问层)
表示层(UI, Main)
业务逻辑层(service)
数据访问层(DAO)
select * from 表名 limit 0,20;//第一页
select * from 表名 limit 20,20;//第二页
select * from 表名 limit 40,20;//第三页
CREATE TABLE emp(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
salary DOUBLE NOT NULL,
age INT NOT NULL
)CHARSET=utf8;
#向数据库中添加100条数据
INSERT INTO emp(NAME,salary,age) VALUES(‘dz1‘,1000,18);
......(此处省略,请自行插入数据)
#<!-- 连接设置 -->
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/emp?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
#<!-- 初始化连接 -->
initialSize=10
#<!-- 最大连接数量 -->
maxActive=50
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 60000毫秒/1000等于60秒 -->
maxWait=5000
package com.dz.emp.entity;
public class Page {
private Integer pageIndex;//页码, 第几页
private Integer pageSize;//页大小, 每页显示多少行数据
private Integer totalCounts;//数据的总行数, 一共有多少条数据
private Integer totalPages;//总页数, 数据一共可以分为多少页
private Integer startRows;//起始行, 用户从第几行开始查数据
//单参构造方法,参数为 页码pageIndex,内部调用两参构造方法,且把 页大小pageSize 的值固定为5
public Page(Integer pageIndex) {
this(pageIndex,5);
}
//两参构造方法,参数为 页码pageIndex, 页大小pageSize,并且设置 起始行startRows 为(pageIndex-1)*pageSize
public Page(Integer pageIndex, Integer pageSize) {
this.pageIndex = pageIndex;
this.pageSize = pageSize;
this.setStartRows((pageIndex-1)*pageSize);
}
public Integer getPageIndex() {
return pageIndex;
}
public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalCounts() {
return totalCounts;
}
//通过数据总行数对页大小取模是否为0, 从而判断总页数为多少
public void setTotalCounts(Integer totalCounts) {
this.totalCounts = totalCounts;
this.setTotalPages(totalCounts % pageSize == 0?totalCounts/pageSize:totalCounts/pageSize + 1 );
}
public Integer getTotalPages() {
return totalPages;
}
public void setTotalPages(Integer totalPages) {
this.totalPages = totalPages;
}
public Integer getStartRows() {
return startRows;
}
public void setStartRows(Integer startRows) {
this.startRows = startRows;
}
}
package com.dz.emp.dao;
import com.dz.emp.entity.Emp;
import com.dz.emp.entity.Page;
import java.util.List;
public interface EmpDao {
int insert(Emp emp);
int delete(int id);
int update(Emp emp);
Emp select(int id);
List<Emp> selectAll();
//分页查询所有
List<Emp> selectAll(Page page);
//查询数据总行数
long selectCounts();
}
public class EmpDaoImpl implements EmpDao {
private QueryRunner queryRunner = new QueryRunner();
//此处省略其他方法
//分页查询所有
@Override
public List<Emp> selectAll(Page page) {
try {
List<Emp> empList = queryRunner.query(DbUtils.getConnection(), "select * from emp limit ?,?", new BeanListHandler<Emp>(Emp.class), page.getStartRows(),page.getPageSize());//两个参数分别为起始行和页大小
return empList;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
//查询数据总行数
@Override
public long selectCounts() {
try {
long counts = queryRunner.query(DbUtils.getConnection(), "select count(*) from emp", new ScalarHandler<>());
return counts;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return 0;
}
}
package com.dz.emp.service;
import com.dz.emp.entity.Emp;
import com.dz.emp.entity.Page;
import java.util.List;
public interface EmpService {
int addEmp(Emp emp);
int removeEmp(int id);
int modify(Emp emp);
Emp showEmp(int id);
List<Emp> showAllEmp();
List<Emp> showAllEmp(Page page);
}
public class EmpServiceImpl implements EmpService {
private EmpDao empDao = new EmpDaoImpl();
//此处省略其他方法
@Override
public List<Emp> showAllEmp(Page page) {
List<Emp> empList = new ArrayList<>();
try {
DbUtils.begin();
long counts = empDao.selectCounts();//查询共有多少条数据
page.setTotalCounts((int)counts);//将long类型的counts转换为int,并赋值给totalCounts
List<Emp> temp = empDao.selectAll(page);
if (temp != null) {
empList = temp;
}
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return empList;
}
}
package com.dz.emp.controller;
import com.dz.emp.entity.Emp;
import com.dz.emp.entity.Page;
import com.dz.emp.service.EmpService;
import com.dz.emp.service.impl.EmpServiceImpl;
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(name = "ShowAllEmpController",value = "/manager/safe/showAllEmpController")
public class ShowAllEmpController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pageIndex = request.getParameter("pageIndex");//获取到页码的值
if (pageIndex == null) {//用户第一次访问页码为空时
pageIndex = "1";//为页码赋值为1
}
Page page = new Page(Integer.valueOf(pageIndex));//将字符串格式的页码转换为Integer类型
EmpService empService = new EmpServiceImpl();
List<Emp> empList = empService.showAllEmp(page);
if (empList != null) {
request.setAttribute("page",page);
request.setAttribute("empList",empList);//存到request作用域中,临时存储
request.getRequestDispatcher("/manager/safe/showAllEmp.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<%@ page import="com.dz.emp.entity.Emp" %>
<%@ 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>查询所有员工页面</title>
</head>
<body>
<form action="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/showInsertEmp.jsp‘></c:url>">
<p><input type=‘submit‘ value=‘新增‘></p>
</form>
<table border=‘1‘>
<tr>
<td>编号</td>
<td>姓名</td>
<td>工资</td>
<td>年龄</td>
<td colspan=‘2‘>操作</td>
</tr>
<c:forEach var="emp" items="${empList}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.age}</td>
<td><a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/removeEmpController?id=${emp.id}‘></c:url>">删除</a></td>
<td><a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/showEmpController?id=${emp.id}‘></c:url>">修改</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="6">
<a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/showAllEmpController?pageIndex=1‘/> ">首页</a>
<c:if test="${page.pageIndex > 1}">
<a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/showAllEmpController?pageIndex=${page.pageIndex-1}‘></c:url> ">上一页</a>
</c:if>
<c:if test="${page.pageIndex == 1}">
<a>上一页</a>
</c:if>
<c:if test="${page.pageIndex < page.totalPages}">
<a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/showAllEmpController?pageIndex=${page.pageIndex+1}‘></c:url> ">下一页</a>
</c:if>
<c:if test="${page.pageIndex == page.totalPages}">
<a>下一页</a>
</c:if>
<a href="<c:url context=‘${pageContext.request.contextPath}‘ value=‘/manager/safe/showAllEmpController?pageIndex=${page.totalPages}‘/> ">尾页</a>
</td>
</tr>
</table>
</body>
</html>
原文:https://www.cnblogs.com/MRASdoubleZ/p/14669013.html