JSP 的学习。
核心功能模块
1.
源代码层 ( src
)
HelloWorld
:主程序入口- 领域模型 :
domain
包含User.java和ceshi.java - 控制器 :
servlet
包含登录验证和验证码相关Servlet
-
Web表现层 (
web
)- JSP页面:包含首页(index.jsp)、登录页(login.jsp)等
- 技术组件 :
- EL表达式:
el
目录下4个示例页面 - JSTL标签库:
jstl
目录下4个示例页面
- EL表达式:
- 依赖库:
lib
包含Servlet和JSTL相关jar包
-
构建输出 (
out
)- 编译产物:production目录下为编译后的class文件
- 部署包:artifacts目录包含Web应用的 exploded 部署版本
- 后端 :Java + Servlet
- 前端 :JSP + EL + JSTL
- 构建工具 :IntelliJ IDEA内置构建工具
- 服务器 :Java Web容器 Tomcat
项目包含:
- 用户登录验证功能(LoginServlet)
- 验证码生成功能(CheckCodeServlet)
- 基础的页面跳转和数据展示功能
- EL与JSTL标签库的学习示例页面
├── .idea\
│ ├── .gitignore
│ ├── libraries\
│ │ └── lib.xml
│ ├── misc.xml
│ ├── modules.xml
│ └── workspace.xml
├── day22.iml
├── src\
│ └── com\
│ └── demo\
│ ├── HelloWorld.java
│ ├── domain\
│ │ ├── User.java
│ │ └── ceshi.java
│ └── servlet\
│ ├── CheckCodeServlet.java
│ └── LoginServlet.java
└── web\
├── 500.jsp
├── WEB-INF\
│ └── lib\
│ ├── javax.servlet.jsp.jstl.jar
│ └── jstl-impl.jar.
│ └── javax.servlet.jar
├── el\
│ ├── el1.jsp
│ ├── el2.jsp
│ ├── el3.jsp
│ └── el4.jsp
├── home.jsp
├── index.jsp
├── jstl\
│ ├── jstl1.jsp
│ ├── jstl2.jsp
│ ├── jstl3.jsp
│ └── jstl4.jsp
├── login.jsp
├── success.jsp
└── top.jsp
登录html
<!-- 登录页 login.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
<style>
span{
color: #62c6ff;
}
</style>
<script>
window.onload = function(){
document.getElementById("img").onclick = function(){
this.src = "/checkCodeServlet?" + new Date().getTime();
}
}
</script>
</head>
<body>
<form action="/loginServlet">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/><span><%=request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error")%></span></td>
</tr>
<tr>
<td>密 码:</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>验证码:</td>
<td><input type="text" name="checkCode"/><span><%=request.getAttribute("cc_error") == null ? "" : request.getAttribute("cc_error")%></span></td>
</tr>
<tr>
<td colspan="2"><img id="img" src="/checkCodeServlet"><a href="">看不清,换一张</a></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"/></td>
</tr>
</table>
</form>
</body>
</html>
<!-- 登录成功后跳转的页面 -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
<h1><%=request.getSession().getAttribute("user")%>,欢迎您!</h1>
</body>
</html>
<!-- jsp组件概念 top.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>首页logo的位置</h1>
<!-- jsp组件概念 home.jsp 使用 top.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ include file="top.jsp" %>
<html>
<head>
<title>首页</title>
<style>
span {
color: red;
}
</style>
</head>
<body><h3> 这是home.jsp</h3>
<span><%=pageContext.getAttribute("msg")%></span></body>
<%
out.println("hello QQ!");
%>
<!-- jsp组件概念 index.jsp 使用 home.jsp -->
<%@ page import="java.util.*" %>
<%--<%@ page contentType="text/html;charset=UTF-8" errorPage="500.jsp" language="java" buffer="16kb" %>--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" buffer="16kb" %>
<html>
<head>
<title>$Title$</title>
<style>
span{
color: red;
}
</style>
</head>
<body>
<%
List list = new ArrayList();
// int a = 3 / 0;
%>
<%
pageContext.setAttribute("msg","hello jsp!");
%>
<span><%=pageContext.getAttribute("msg")%></span>
<%
request.getRequestDispatcher("/home.jsp").forward(request,response);
%>
$END$111
</body>
</html>
</html>
<!-- 异常页面 500.jsp -->
<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>服务器正忙... ...</h1>
<%
String message = exception.getMessage();
out.println(message);
%>
</body>
</html>
后端实现
import java.text.SimpleDateFormat;
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;
}
/**
* 逻辑视图
* @return
*/
public String getStrDate(){
if(birthday != null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
return sdf.format(birthday);
}else{
return "";
}
}
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;
}
}
import javax.imageio.ImageIO;
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.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1、创建一个对象,用来生成验证码图片
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//2、美化
//2.1填充背景颜色
Graphics graphics = bufferedImage.getGraphics();//画图对象
graphics.setColor(Color.PINK);
graphics.fillRect(0,0,width,height);
//2.2画边框
graphics.setColor(Color.BLUE);
graphics.drawRect(0,0,width-1,height-1);
//2.3实现验证码随机生成
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//随机生成角标
Random random = new Random();
//存储生成的验证码
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1; i <=4 ; i++) {
int index = random.nextInt(str.length());
char c = str.charAt(index);
stringBuilder.append(c);
graphics.drawString(c+"",width/5 * i,height/2);
}
String checkCode_session = stringBuilder.toString();
//存储验证码到session中
HttpSession session = request.getSession();
session.setAttribute("checkCode_session",checkCode_session);
//2.4画干扰线
graphics.setColor(Color.GREEN);
for (int i = 0; i < 10 ; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
//3、输出验证码到浏览器
ImageIO.write(bufferedImage,"jpg", response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
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;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、设置request的编码方式
request.setCharacterEncoding("utf-8");
//2、获取参数
String username = request.getParameter("username");
String password = request.getParameter("pwd");
//用户输入的验证码
String checkCode = request.getParameter("checkCode");
//3、获取验证码
HttpSession session = request.getSession();
String checkCode_session = (String)session.getAttribute("checkCode_session");
//移除验证码
session.removeAttribute("checkCode_session");
//4、判断用户输入的验证码和生成的验证码是否一致
//判断输入的验证码不能为空
if(checkCode != null && checkCode.equalsIgnoreCase(checkCode_session)){
//验证码正确
//判断用户名和密码发是否正确
if("zhangsan".equals(username) && "123".equals(password)) { //应该使用UserDao访问数据库得到的
//用户名和密码正确
//存储数据
session.setAttribute("user",username);
//跳转页面 success.jsp 重定向
response.sendRedirect(request.getContextPath() + "/success.jsp");
}else{
//返回提示信息
request.setAttribute("login_error","用户名或密码错误!");
//跳转页面 转发
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}else{
//验证码错误,给用户返回提示信息
request.setAttribute("cc_error","验证码错误!");
//跳转页面(转发)
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
jsp 练习
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>el表达式</title>
</head>
<body>
<%
boolean a = 3 > 4;
out.println(a);
String str = "123";
request.setAttribute("str",str);
request.setAttribute("a",null);
%>
<hr>
\${ 3 > 4}
<h3>运算符</h3>
${ 3 + 4}<br>
${ 3 - 4}<br>
${ 3 * 4}<br>
${ 3 / 4}<br>
${ 3 div 4}<br>
${ 3 % 4}<br>
${ 3 mod 4}<br>
<h3>比较运算符</h3>
${ 3 == 3 }
<h3>逻辑运算符</h3>
${ 4 > 3 and 5 > 4 ? "ok" : "no"}
${ 4 > 3 && 5 > 4 ? "ok" : "no"}
<h3>空运算符</h3>
${ str }
${ empty str }
${ a }
${ not empty a }
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>el获取值</title>
</head>
<body>
<%
request.setAttribute("name","张三");
session.setAttribute("ok","别瞌睡!");
session.setAttribute("name","李四");
%>
<h1>${ requestScope.name }</h1>
<h1>${ sessionScope.ok }</h1>
<h1>${ sessionScope.name }</h1>
<h1>${ name }</h1>
</body>
</html>
<%@ page import="com.demo.domain.User" %>
<%@ page import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>el获取对象、List集合、Map集合的值</title>
</head>
<body>
<%
User user = new User();
user.setName("乔丹");
user.setAge(57);
user.setBirthday(new Date());
request.setAttribute("user", user);
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add(user);
request.setAttribute("list",list);
Map map = new HashMap();
map.put("a","aaa");
map.put("b","bbb");
map.put("u",user);
request.setAttribute("map",map);
%>
<h3>el获取对象的值</h3>
<%--
获取对象的值的规则是:
1)通过setter或getter方法,然后去掉set或者get,然后首字母小写
2)getName -- > Name -- > name
--%>
${ requestScope.user }
${ requestScope.user.name }
${ requestScope.user.age }
${ requestScope.user.strDate }
<hr>
<h3>el获取List的值</h3>
${ requestScope.list }
${ requestScope.list[0] }
${ requestScope.list[1] }
${ requestScope.list[2].name }
<hr>
<h3>el获取Map的值</h3>
${ requestScope.map }
${ requestScope.map.a }
${ requestScope.map["b"] }
${ requestScope.map.u.name }
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>el的隐式对象</title>
</head>
<body>
${ pageContext.request.contextPath }
</body>
</html>
JSTL练习
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>c:if的学习</title>
</head>
<body>
<%--
常用的JSTL标签
1. if:相当于java代码的if语句
1. 属性:
* test 必须属性,接受boolean表达式
* 如果表达式为true,则显示if标签体内容,如果为false,则不显示标签体内容
* 一般情况下,test属性值会结合el表达式一起使用
2. 注意:
* c:if标签没有else情况,想要else情况,则可以在定义一个c:if标签--%>
<%
//获取request域中的list集合,并判断是否为null,如果不为null则输出“遍历集合”
List list = new ArrayList();
list.add("a");
request.setAttribute("list",list);
request.setAttribute("number", 4);
%>
<c:if test="${ not empty list }">
遍历集合... ...
</c:if>
<c:if test="${number % 2 == 0}">
${number}是偶数
</c:if>
<c:if test="${number % 2 != 0}">
${number}是奇数
</c:if>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>c:choose的学习</title>
</head>
<body>
<%
//根据一个数字来显示对应的星期几
/**
* 1、存储一个数字;
* 2. 使用choose标签声明 相当于switch声明
* 3. 使用when标签做判断 相当于case
* 4. 使用otherwise标签做其他情况的声明 相当于default
*/
request.setAttribute("number",50);
%>
<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>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<html>
<head>
<title>c:forEach的学习</title>
</head>
<body>
<%
// 1. 完成重复的操作
// for(int i = 0; i < 10; i ++){
//
// }
// * 属性:
// begin:开始值
// end:结束值
// var:临时变量
// step:步长
// varStatus:循环状态对象
// index:容器中元素的索引,从0开始
// count:循环次数,从1开始
// 2. 遍历容器
// List<User> list;
// for(User user : list){
//
// }
//
// * 属性:
// items:容器对象
// var:容器中元素的临时变量
// varStatus:循环状态对象
// index:容器中元素的索引,从0开始
// count:循环次数,从1开始
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
request.setAttribute("list",list);
%>
<c:forEach begin="1" end="10" var="i" step="2" varStatus="s">
${i} <h3>${ s.index }</h3> ${ s.count } <hr>
</c:forEach>
<hr>
<%--遍历集合--%>
<c:forEach items="${ list }" var="ltt" varStatus="str">
${ str.index } <h3>${ str.count }</h3> ${ ltt }<br>
</c:forEach>
</body>
</html>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="com.demo.domain.User" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>c标签练习</title>
</head>
<body>
<%
//需求:在request域中有一个存有User对象的List集合。
// 需要使用jstl+el将list集合数据展示到jsp页面的表格table中,并且偶数行显示红色,奇数行显示绿色
List list = new ArrayList();
list.add(new User("张三", 20, new Date()));
list.add(new User("李四", 20, new Date()));
list.add(new User("王五", 20, new Date()));
//将list集合存储在request域中
request.setAttribute("list", list);
%>
<table border="1" width="500" align="center">
<tr>
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>生日</td>
</tr>
<c:if test="${ not empty list }">
<c:forEach items="${ list }" var="haha" varStatus="s">
<c:if test="${ s.count % 2 != 0 }">
<tr style="background: red;">
<td>${ s.count }</td>
<td>${ haha.name }</td>
<td>${ haha.age }</td>
<td>${ haha.strDate }</td>
</tr>
</c:if>
<c:if test="${ s.count % 2 == 0 }">
<tr style="background: green;">
<td>${ s.count }</td>
<td>${ haha.name }</td>
<td>${ haha.age }</td>
<td>${ haha.strDate }</td>
</tr>
</c:if>
</c:forEach>
</c:if>
<c:if test="${ empty list }">
<%--<%--%>
<%--if(list == null || list.size() == 0){--%>
<%--%>--%>
<tr>
<td>无数据</td>
<td>无数据</td>
<td>无数据</td>
<td>无数据</td>
</tr>
<%--<%--%>
<%--}--%>
<%--%>--%>
</c:if>
</table>
</body>
</html>
使用到的jar
javax.servlet.jar
javax.servlet.jsp.jstl.jar
jstl-impl.jar
访问:
http://localhost:8081/login.jsp
http://localhost:8081/index.jsp
http://localhost:8081/el/el1.jsp
http://localhost:8081/el/el2.jsp
http://localhost:8081/el/el3.jsp
http://localhost:8081/el/el4.jsp
http://localhost:8081/jstl/jstl1.jsp
http://localhost:8081/jstl/jstl2.jsp
http://localhost:8081/jstl/jstl3.jsp
http://localhost:8081/jstl/jstl4.jsp