jsp入门使用
<%@ page import="java.io.PrintWriter" %>
<%-- Created by IntelliJ IDEA.--%>
<%-- User: 韩顺平--%>
<%-- jsp的模板如何定制,一会再说明--%>
<%-- To change this template use File | Settings | File Templates.--%>
<%--–%>--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>jsp的简单的求和计算器</title>
</head>
<body>
<h1>jsp的简单的求和计算器</h1>
<%//老韩解读//1. 在jsp的 该标签中, 可以写java代码int i = 10;int j = 20;int res = i + j;//2. jsp 中内置对象,可以直接使用, 比如 out// 老韩小技巧:先死后活 ctrl + alt + lout.println(i + " + " + j + " = " + res);//3. 老师说明,如果要看HttpJspBase类的关系, 需要引入一个包, alt+enter//在java片段中,仍然是java的注释String email = "xx@qq.com";/*多行注释*/%>
<%--email: <%=email%>--%>
<!--html注释 -->
</body>
</html>
声明所需的类
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>jsp声明脚本</title>
</head>
<body>
<h1>jsp声明脚本</h1>
<%!//这里我们可以声明该jsp需要使用的属性,方法,静态代码块, 内部类//老师一句话: 也就是给 statement.jsp 对应的 statement_jsp 类定义成员//1. 属性private String name = "jack";private int age;private static String company;//2 方法public String getName() {return name;}//3. 静态代码块static {company = "字节跳动";}
%>
</body>
</html>
表达式脚本使用
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>表达式脚本的使用</title>
</head>
<body>
<h1>个人信息</h1>
<%String name = "老韩";String email = request.getParameter("email");
%>
用户名: <%=name%><br/>
工作是: <%="java工程师"%><br/>
年龄: <%=request.getParameter("age")%><br/>
电邮: <%=email%>
</body>
</html>
jsp内置对象
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>jsp内置对象</title>
</head>
<body>
<h1>jsp内置对象</h1>
<%//老韩梳理jsp的内置对象//out 类型是 JspWriter 父类就是 Writer.out.println("jsp out");//request是HttpServletRequestrequest.getParameter("age");//response就是 HttpServletResponse//response.sendRedirect("http://www.baidu.com");//session 就是 HttpSessionsession.setAttribute("job", "PHP工程师");//application类型就是ServletContextapplication.setAttribute("name", "老韩老师");//pageContext 可以存放数据(属性), 但是该数据只能在本页面使用pageContext.setAttribute("age", 100);//exception 异常对象 使用比较少//page 内置对象,类似 thisout.println("page=" + page);//config 内置对象的类型就是ServletConfigString pwd = config.getInitParameter("pwd");%>
</body>
age: <%=pageContext.getAttribute("age")%>
</html>
jsp的域对象
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>scope文件</title>
</head>
<body>
<%//在不同的域对象中,放入数据//老韩解读//1. 因为四个域对象,是不同的对象,因此name(key) 相同时,并不会冲突pageContext.setAttribute("k1", "pageContext数据(k1)");request.setAttribute("k1", "request数据(k1)");session.setAttribute("k1", "session数据(k1)");application.setAttribute("k1", "application数据(k1)");//做一个请求转发的操作//路径应该怎么写,请不清楚地小伙伴,去看韩老师讲的web路径专题//request.getRequestDispatcher("/scope2.jsp").forward(request, response);//做一个重定向String contextPath = request.getContextPath();//返回的就是 web路径=>/jsp//response.sendRedirect("/jsp/scope2.jsp");response.sendRedirect(contextPath + "/scope2.jsp");
%>
<h1>四个域对象,在本页面获取数据的情况</h1>
pageContext-k1: <%=pageContext.getAttribute("k1")%><br/>
request-k1: <%=request.getAttribute("k1")%><br/>
session-k1: <%=session.getAttribute("k1")%><br/>
application-k1: <%=application.getAttribute("k1")%><br/>
</body>
</html>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>scope2.js</title>
</head>
<body>
<h1>在scope2页面获取数据的情况</h1>
pageContext-k1: <%=pageContext.getAttribute("k1")%><br/>
request-k1: <%=request.getAttribute("k1")%><br/>
session-k1: <%=session.getAttribute("k1")%><br/>
application-k1: <%=application.getAttribute("k1")%><br/>
</body>
</html>
jsp对象的使用
package com.hspedu.entity;public class Monster {private Integer id;private String name;private String skill;public Monster(Integer id, String name, String skill) {this.id = id;this.name = name;this.skill = skill;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSkill() {return skill;}public void setSkill(String skill) {this.skill = skill;}
}
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.hspedu.entity.Monster" %>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>演示代码脚本</title>
</head>
<body>
<h1>演示代码脚本</h1>
<%//创建ArrayList ,放入两个monster对象ArrayList<Monster> monsterList = new ArrayList<>();monsterList.add(new Monster(1, "牛魔王", "芭蕉扇"));monsterList.add(new Monster(2, "蜘蛛精", "吐口水"));
%>
<table bgcolor="#f0f8ff" border="1px" width="300px"><tr><th>id</th><th>名字</th><th>技能</th></tr><%for (int i = 0; i < monsterList.size(); i++) {//先取出monster对象Monster monster = monsterList.get(i);%><tr><td><%=monster.getId()%></td><td><%=monster.getName()%></td><td><%=monster.getSkill()%></td></tr><%}%></table>
</body>
</html>
jsp作业
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>JSP计算器</title><!--使用js+正则表达式完成数据校验--><script type="text/javascript">function check() {//得到 num1 和 num2值var num1 = document.getElementById("num1").value;var num2 = document.getElementById("num2").value;//验证 正则表达式, 整数 => 在java基础讲过 => 学习技术一定要经常回顾//我们学习的所有java技术=> 其实都是基础组合[oop,io,反射,注解,集合,线程,网络]var reg = /^[-]?([1-9]\d*|0)$/;if (!reg.test(num1)) {//如果不满足验证条件alert("num1 不是一个整数");return false;//放弃提交}if (!reg.test(num2)) {//如果不满足验证条件alert("num2 不是一个整数");return false;//放弃提交}return true;//提交到action指定的位置}</script>
</head>
<body>
<h1>JSP计算器</h1>
<form action="<%=request.getContextPath()%>/calServlet"method="post" onsubmit="return check()">num1: <input type="text" id="num1" name="num1"> num1错误:xx <br/>num2: <input type="text" id="num2" name="num2"> num2错误:xx<br/>运算符号:<select name="oper"><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option></select><br/><input type="submit" value="提交计算">
</form>
</body>
</html>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>计算结果</title>
</head>
<body>
<h1>计算结果</h1>
<%=request.getAttribute("res")%><br/>
<%--<a href="/jsp/cal/calUI.jsp">返回重新来玩一把</a>--%>
<a href="<%=request.getContextPath()%>/cal/calUI.jsp">返回重新来玩一把~</a>
</body>
</html>
package com.hspedu.servlet;import com.hspedu.utils.WebUtils;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class CalServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("CalServlet 被调用...");//思路 ==> 代码//1. 是Servlet//2. 接收数据//String num1 = request.getParameter("num1");//String num2 = request.getParameter("num2");//进行转换->intdouble num1 = WebUtils.parseDouble(request.getParameter("num1"), 0);double num2 = WebUtils.parseDouble(request.getParameter("num2"), 0);String oper = request.getParameter("oper");double res = 0; //使用变量来接收运算结果//3. 完成计算if ("+".equals(oper)) {res = num1 + num2;} else if ("-".equals(oper)) {res = num1 - num2;} else if ("*".equals(oper)) {res = num1 * num2;} else if ("/".equals(oper)) {res = num1 / num2;} else {System.out.println(oper + " 不正确...");}//4. 把结果保存到域对象[request, session, servletContext]// 老韩解读:因为一次请求对应一次计算, 所以我建议将结果保存到request// 老韩的思路: 把结果组织到一个字符串中., 方便我们在下一个页面显示// java基础: String.format ,可以格式化字符串String formatRes = String.format("%s %s %s = %s", num1, oper, num2, res);request.setAttribute("res", formatRes);//System.out.println("formatRes= " + formatRes);//5. 转发到显示页面 calRes.jsprequest.getRequestDispatcher("/cal/calRes.jsp").forward(request, response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}
package com.hspedu.utils;public class WebUtils {//把一个string->intpublic static int parseInt(String strNum, int defaultVal) {try {return Integer.parseInt(strNum);} catch (NumberFormatException e) {System.out.println(strNum + " 不能转成整数...");}return defaultVal;}//把一个string->intpublic static double parseDouble(String strNum, double defaultVal) {try {return Double.parseDouble(strNum);} catch (NumberFormatException e) {System.out.println(strNum + " 不能转成double...");}return defaultVal;}
}
jstl快速入门
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>jstl的快速入门</title>
</head>
<body>
<h1>jstl的快速入门</h1>
<%--老韩解读1. c:if ... 类似2. if(10>2){out.println("<h1>10 > 2 成立~</h1>")}
--%>
<c:if test="${10 < 2}"><h1>10 > 2 成立~</h1>
</c:if>
</body>
</html>
标签if的应用
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>c:if标签使用</title>
</head>
<body>
<c:set scope="request" var="num1" value="20"></c:set>
<c:set scope="request" var="num2" value="10"></c:set>
<c:if test="${num1 > num2}"><h1>${num1} > ${num2}</h1>
</c:if>
</body>
</html>
标签set的应用
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>c:set标签的使用</title>
</head>
<body>
<h1>c:set标签的使用</h1>
<%--<%--%>
<%-- //Java代码--%>
<%-- request.setAttribute("email", "hsp@sohu.com");--%>
<%--%>--%>
<%--老韩解读<c:set /> set 标签可以往域中保存数据1. 等价 域对象.setAttribute(key,value);2. scope 属性设置保存到哪个域page 表示 PageContext 域(默认值)request 表示 Request 域session 表示 Session 域application 表示 ServletContext 域3. var 属性设置 key 是什么4. value 属性设置值
--%>
<c:set scope="request" var="name" value="韩顺平教育~"></c:set>
c:set-name的值${requestScope.name}
</body>
</html>
foreach标签的使用
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="com.hspedu.entity.Monster" %>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0Filename: jstl_foreach
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>c:forEach 标签</title>
</head>
<body>
<h1>c:forEach 标签</h1>
<hr/>
<h1>第1种遍历方式从i到j</h1>
<ul><%--1.遍历 1 到 5,2. 输出 begin 属性设置开始的索引 end 属性设置结束的索引3. var 属性表示循环的变量(也是当前正在遍历到的数据)4. 等价 for (int i = 1; i <= 5; i++) {}5. 在默认情况下, i 每次会递增1--%><c:forEach begin="1" end="5" var="i"><li>排名=${i}</li></c:forEach>
</ul>
<hr/>
<h1>第2种遍历方式:遍历数组</h1>
<%request.setAttribute("sports", new String[]{"打篮球", "乒乓球"});
%>
<%--<c:forEach items="${ requestScope.sports }" var="item"/>1. items 遍历的集合/数组2. var 遍历到的数据3. 等价 for (Object item: arr) {}
--%>
<c:forEach items="${requestScope.sports}" var="sport">运动名称= ${sport}<br/>
</c:forEach>
<hr/>
<h1>第3种遍历方式:遍历Map</h1>
<%Map<String, Object> map = new HashMap<>();map.put("key1", "北京");map.put("key2", "上海");map.put("key3", "天津");request.setAttribute("cities", map);
%>
<%--1. items 遍历的map集合2. var 遍历到的数据3. entry.key 取出key4. entry.value 取出值
--%>
<c:forEach items="${requestScope.cities}" var="city">城市信息: ${city.key}--${city.value}<br/>
</c:forEach>
<hr/>
<h1>第4种遍历方式:遍历List</h1>
<%List<Monster> monsters = new ArrayList<>();monsters.add(new Monster(100, "小妖怪", "巡山的"));monsters.add(new Monster(200, "大妖怪", "做饭的"));monsters.add(new Monster(300, "老妖怪", "打扫位置的"));request.setAttribute("monsters", monsters);
%>
<%--items 表示遍历的集合var 表示遍历到的数据begin 表示遍历的开始索引值 ,从0开始计算end 表示结束的索引值step 属性表示遍历的步长值varStatus 属性表示当前遍历到的数据的状态,可以得到step,begin,end等属性值//老师提示, 对于jstl标签,能看懂,会使用即可
--%>
<c:forEach items="${requestScope.monsters}" var="monster">妖怪的信息: ${monster.id}-${monster.name}-${monster.skill}<br/>
</c:forEach>
</body>
</html>
choose标签的应用
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>c:choose标签的使用</title>
</head>
<body>
<h1>c:choose标签的使用</h1>
<%request.setAttribute("score", 50);request.setAttribute("k1", "request-k1的值");//session.setAttribute("k1", "session-k1的值");//application.setAttribute("k1", "application-k1的值");//pageContext.setAttribute("k1", "pageContext-k1的值~");
%>
<%--老师多说一句
1. 如果${requestScope.score} 那么就明确的指定从request域对象取出数据
2. 如果${score}, 这是就按照从小到大的域范围去获取 pageContext->request->session->application
3. 一会老韩给小伙伴验证一把.
--%>
k1=${k1}
<c:choose><c:when test="${requestScope.score > 80}"><h1>${score}-成绩优秀</h1></c:when><c:when test="${requestScope.score >= 60}"><h1>${score}-成绩一般, 及格了</h1></c:when><c:otherwise><h1>${score}-没有及格,下次努力~</h1></c:otherwise>
</c:choose>
</body>
</html>
jstl作业
package com.hspedu.servlet;import com.hspedu.entity.Monster;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;public class QueryServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1. 准备要显示的数据--> 从DBArrayList<Monster> list = new ArrayList<>();list.add(new Monster(100, "牛魔王", "芭蕉扇"));list.add(new Monster(200, "狐狸精", "美人计"));list.add(new Monster(300, "白骨精", "吃人骨头"));//2. 把list放入到request域, 供jsp页面使用request.setAttribute("monsters", list);//3. 请求转发 list.jsprequest.getRequestDispatcher("/jstl/list.jsp").forward(request,response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>显示所有的妖怪</title>
</head>
<body>
<h1>显示所有的妖怪</h1>
<table border="1px" width="400px"><tr><td>id</td><td>name</td><td>skill</td></tr>
<%-- 使用c:foreach循环显示即可 显示id > 200--%><c:forEach items="${monsters}" var="monster"><c:if test="${monster.id >= 200}"><tr><td>${monster.id}</td><td>${monster.name}</td><td>${monster.skill}</td></tr></c:if></c:forEach></table>
</body>
</html>
<%--Created by IntelliJ IDEA.User: 韩顺平Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>查询妖怪</title>
</head>
<body>
<h1>查询妖怪</h1>
<a href="<%=request.getContextPath()%>/queryServlet">点击查询所有的妖怪</a>
</body>
</html>