传送门
JSP基本语法
什么是servlet
自定义Servlet,直接使用抽象好的HttpServlet更好
MyCustomServlet
public class MyCustomServlet extends HttpServlet {
@Serial
private static final long serialVersionUID = -599450886992695746L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (LocalTime.now().getSecond()%2==0){
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.println("<html><body bgcolor= #ffccff>");
out.println("<h1>hello servlet,你好 servlet</h1>");
out.println("</body></html>");
}else {
resp.setContentType("application/json;charset=UTF-8");
PrintWriter out = resp.getWriter();
resp.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
out.println("""
{"code":502,"msg":"服务器错误啦"}
""");
}
}
}
web.xml
<servlet>
<servlet-name>MyCustomServlet</servlet-name>
<servlet-class>com.lazyking.MyCustomServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyCustomServlet</servlet-name>
<url-pattern>/customServlet</url-pattern>
</servlet-mapping>
jsp运行原理
<% out.print("welcome") %>
IDEA Jetty启动 out对象不能识别怎么办?(也就是out.print报红)
其实是因为缺少servlet-api,大部分教程是告诉你引入tomcat作为编译依赖的一部分,其实直接pom引入servlet-api和jsp-api就可以了
这里为了方便直接引用了jstl(它包含了api),后续jstl表达式能大大简化开发
同时还需要引入taglibs,为的是让IDEA支持JSTL的代码补全,否则c:set标签等虽然可以使用,但会报红影响开发
需要注意依赖的scope都要改为provided,因为我们只在编写编译代码时需要使用依赖,实际使用时Web容器会提供这些依赖
引入多余的话会出现WARNING:scanned from multiple locations 类似这样的提示
<!-- https://mvnrepository.com/artifact/jakarta.servlet.jsp/jakarta.servlet.jsp-api -->
<dependency>
<groupId>jakarta.servlet.jsp</groupId>
<artifactId>jakarta.servlet.jsp-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet.jsp.jstl/jakarta.servlet.jsp.jstl-api -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>3.0.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
<scope>provided</scope>
</dependency>
第一个JSP页面
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>Hello JSP!</p>
<%
out.print("welcome");
String msg = "这是一个字符串";
List<Integer> list = List.of(1, 2, 3, 4, 5);
%>
<p>Hello GO GO GO!</p>
<%= "msg is " + msg + " list is " + list %>
</body>
</html>
注释
JSP表达式
JSP程序段
JSP声明
可以随处声明,但不常用,有点不符合Java的风格了
<%="value is " + value %>
<%
student.setName("111");
%>
<br>
<%="student is " + student%>
<br>
<%="studentNull is " + studentNull%>
<%!
String value = "像JavaScript那样随处声明";
Student student = new Student(1,"小明");
Student studentNull;
%>
<%
for (int i = 0; i < 5; i++) {
%>
<p> 跨Java区域中间添加HTML代码,但是非常不美观 </p>
<%
}
%>
URL传值
<%
String no = request.getParameter("no");
%>
JSP指令和动作
jsp基本头部标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List,java.util.ArrayList" %>
<%@ page import="com.lazyking.Student" %>
<%@ page errorPage="/error/error.jsp" %>
//error.jsp
<%@ page isErrorPage="true" %>
jsp错误页面示例
<%@ page import="java.util.Date" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Title</title>
<%
request.setAttribute("exceptionC",exception);
request.setAttribute("myDate",new Date());
out.println("页面出问题了!" + exception.getMessage());
%>
<br>
request.setAttribute exceptionC: <c:out value="${exceptionC}"></c:out>
<br>
<c:set var="ss" value="AABB"></c:set>
fn:toLowerCase: <c:out value="${fn:toLowerCase(ss)}"></c:out>
<br>
<fmt:parseDate value="2024-03-06" var="parsedDate" pattern="yyyy-MM-dd" />
<fmt:formatDate value="${myDate}" pattern="yyyy-MM-dd HH:mm:ss" var="formattedDate" />
parsedDate: <c:out value="${parsedDate}"></c:out>
<br>
formattedDate: ${formattedDate} <c:out value="${formattedDate}"></c:out>
<br>
<%-- <sql:query var=""></sql:query>--%>
</head>
<body>
</body>
</html>
详情可以查看jsp的xml规范
jsp包含,常用,include其他jsp文件作为网页头或者网页脚
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<hr>
<p>我是foot.jsp 其他jsp记得在最后include我</p>
<%@ include file="/foot.jsp"%>
<jsp:include page="/foot.jsp" />
<p>@ include 会复制整个jsp的代码嵌入 </p>
<p>jsp:include 只复制jsp的输出页面结果而非jsp代码 建议jsp的文件用这种 避免变量名冲突</p>
jsp转发
<jsp:forward page="go.jsp"></jsp:forward>
课后习题
表单开发
注意一下多选框元素的获取就可以
String no = request.getParameter("no");
String[] checkboxes = request.getParameterValues("checkbox");
认识表单
单一表单元素数据
捆绑表单元素数据
隐藏表单
其他问题
课后习题
JSP访问数据库
好久没有这么原始的调用数据库了
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
Connection connection = DriverManager.getConnection("url","user","pwd");
try {
try (
PreparedStatement ps = connection.prepareStatement("select sql from table where name=?");
PreparedStatement psUpdate = connection.prepareStatement("update table set name=? where no=?");
){
connection.setAutoCommit(false);
//事务
ps.setString(1,"小明");
try (ResultSet resultSet = ps.executeQuery();){
while (resultSet.next()) {
String no = resultSet.getString("no");
}
}
psUpdate.setString(1,"小明");
psUpdate.setString(2,"2");
int update = psUpdate.executeUpdate();
connection.commit();
}
}catch (Exception e){
connection.rollback();
throw new RuntimeException(e);
}finally {
if (connection != null){
connection.close();
}
}
JDBC
建立ODBC数据源
JDBC操作
使用PreparedStatement
事务
使用厂商驱动进行数据库连接
课后习题
JSP内置对象
可以通过查看编译后的Servlet class更直观的了解jsp内置对象
指定一下Jetty的临时目录
<configuration>
<httpConnector>
<port>9999</port>
<host>localhost</host>
</httpConnector>
<webApp>
<contextPath>/</contextPath> <!-- Web 应用的上下文路径 -->
<tempDirectory>D:\jettyTemp</tempDirectory><!--web文件临时目录 -->
</webApp>
<scan>10</scan>
</configuration>
认识JSP内置对象
如源代码所示
内置对象的类可以在serlvet-api的jar包内看到具体内容
out对象
request对象
response对象
//重定向
response.sendRedirect("xxx.jsp");
//与<jsp:forward>的区别是,sendRedirect相当于浏览器重新请求,使用的是新的地址,request的数据不能共享