1. JSP 指令: JSP指令(directive)是为JSP引擎而设计的,
它们并不直接产生任何可见输出, 而只是告诉引擎如何处理JSP页面中的其余部分。
2. 在目前的JSP 2.0中,定义了page、include 和 taglib这三种指令
3. page 指令:
1). page指令用于定义JSP页面的各种属性, 无论page指令出现在JSP页面中的什么地方,
它作用的都是整个JSP页面, 为了保持程序的可读性和遵循良好的编程习惯, page指令最好是放在整个JSP页面的起始位置。
2). page 指令常用的属性:
①. import 属性: 指定当前 JSP 页面对应的 Servlet 需要导入的类.
<%@page import="java.text.DateFormat"%>
②. session 属性: 取值为 true 或 false, 指定当前页面的 session 隐藏变量是否可用, 也可以说访问当前页面时是否一定要生成 HttpSession
对象. <%@ page session="false" %>
③. errorPage 和 isErrorPage:
> errorPage 指定若当前页面出现错误的实际响应页面时什么. 其中 / 表示的是当前 WEB 应用的根目录.
<%@ page errorPage="/error.jsp" %>
> 在响应 error.jsp 时, JSP 引擎使用的请求转发的方式.
> isErrorPage 指定当前页面是否为错误处理页面, 可以说明当前页面是否可以使用 exception 隐藏变量. 需要注意的是: 若指定
isErrorPage="true", 并使用 exception 的方法了, 一般不建议能够直接访问该页面.
> 如何使客户不能直接访问某一个页面呢 ? 对于 Tomcat 服务器而言, WEB-INF 下的文件是不能通过在浏览器中直接输入地址的方式
来访问的. 但通过请求的转发是可以的!
> 还可以在 web.xml 文件中配置错误页面:
<error-page>
<!-- 指定出错的代码: 404 没有指定的资源, 500 内部错误. -->
<error-code>404</error-code>
<!-- 指定响应页面的位置 -->
<location>/WEB-INF/error.jsp</location>
</error-page>
<error-page>
<!-- 指定异常的类型 -->
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/WEB-INF/error.jsp</location>
</error-page>
④. contentType: 指定当前 JSP 页面的响应类型. 实际调用的是 response.setContentType("text/html; charset=UTF-8");
通常情况下, 对于 JSP 页面而言其取值均为 text/html; charset=UTF-8. charset 指定返回的页面的字符编码是什么. 通常取值为 UTF-8
⑤. pageEncoding: 指定当前 JSP 页面的字符编码. 通常情况下该值和 contentType 中的 charset 一致.
⑥. isELIgnored: 指定当前 JSP 页面是否可以使用 EL 表达式. 通常取值为 false.
4. include 指令: <%@ include file="b.jsp" %>
1). include 指令用于通知 JSP 引擎在翻译当前 JSP 页面时将其他文件中的内容合并进当前 JSP 页面转换成的 Servlet 源文件中,
这种在源文件级别进行引入的方式称之为静态引入, 当前JSP页面与静态引入的页面紧密结合为一个Servlet。
2). file属性的设置值必须使用相对路径
3). 如果以 / 开头,表示相对于当前WEB应用程序的根目录(注意不是站点根目录),否则,表示相对于当前文件。
5. jsp:incluce 标签:
1). <jsp:include page="b.jsp"></jsp:include>
2). 动态引入: 并不是像 include 指令生成一个 Servlet 源文件, 而是生成两个 Servlet 源文件, 然后通过一个方法的方式把目标页面包含
进来. org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "b.jsp", out, false);
6. jsp:forward:
1). <jsp:forward page="/include/b.jsp"></jsp:forward>
相当于.
<% request.getRequestDispatcher("/include/b.jsp").forward(request, response); %>
2). 但使用 jsp:forward 可以使用 jsp:param 子标签向 b.jsp 传入一些参数. 同样 jsp:include 也可以使用 jsp:param 子标签.
<jsp:forward page="/include/b.jsp">
<jsp:param value="abcd" name="username"/>
</jsp:forward>
OR
<jsp:include page="/include/b.jsp">
<jsp:param value="abcd" name="username"/>
</jsp:include>
在 b.jsp 页面可以通过 request.getParameter("username") 获取到传入的请求参数.
7. 关于中文乱码:
1). 在 JSP 页面上输入中文, 请求页面后不出现乱码: 保证 contentType="text/html; charset=UTF-8",
pageEncoding="UTF-8" charset 和 pageEncoding 的编码一致, 且都支持中文. 通常建议取值为UTF-8
还需保证浏览器的显示的字符编码也和请求的 JSP 页面的编码一致.
2). 获取中文参数值: 默认参数在传输过程中使用的编码为 ISO-8859-1
①. 对于 POST 请求: 只要在获取请求信息之前(在调用 request.getParameter 或者是 request.getReader 等),
调用 request.setCharacterEncoding("UTF-8") 即可.
②. 对于 GET 请求: 前面的方式对于 GET 无效. 可以通过修改 Tomcat 的 server.xml 文件的方式.
参照 http://localhost:8989/docs/config/index.html 文档的 useBodyEncodingForURI 属性.
为 Connector 节点添加 useBodyEncodingForURI="true" 属性即可.
<Connector connectionTimeout="20000" port="8989" protocol="HTTP/1.1" redirectPort="8443" useBodyEncodingForURI="true"/>
8.代码区
package com.atguigu.javaweb.mvc; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class DeleteStudentServlet */ public class DeleteStudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String flowId = request.getParameter("flowId"); StudentDao studentDao = new StudentDao(); studentDao.deleteByFlowId(Integer.parseInt(flowId)); request.getRequestDispatcher("/success.jsp").forward(request, response); } }
package com.atguigu.javaweb.mvc; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ListAllStudentsServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StudentDao studentDao = new StudentDao(); List<Student> students = studentDao.getAll(); request.setAttribute("students", students); request.getRequestDispatcher("/students.jsp").forward(request, response); } }
package com.atguigu.javaweb.mvc; public class Student { private Integer flowId; private int type; private String idCard; private String examCard; private String studentName; private String location; private int grade; public Integer getFlowId() { return flowId; } public void setFlowId(Integer flowId) { this.flowId = flowId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getExamCard() { return examCard; } public void setExamCard(String examCard) { this.examCard = examCard; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } public Student(Integer flowId, int type, String idCard, String examCard, String studentName, String location, int grade) { super(); this.flowId = flowId; this.type = type; this.idCard = idCard; this.examCard = examCard; this.studentName = studentName; this.location = location; this.grade = grade; } public Student() { // TODO Auto-generated constructor stub } }
package com.atguigu.javaweb.mvc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class StudentDao { public void deleteByFlowId(Integer flowId){ Connection connection = null; PreparedStatement preparedStatement = null; try { String driverClass = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql:///atguigu"; String user = "root"; String password = "1230"; Class.forName(driverClass); connection = DriverManager.getConnection(url, user, password); String sql = "DELETE FROM examstudent WHERE flow_id = ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, flowId); preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ try { if(preparedStatement != null){ preparedStatement.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(connection != null){ connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } public List<Student> getAll(){ List<Student> students = new ArrayList<>(); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String driverClass = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql:///atguigu"; String user = "root"; String password = "1230"; Class.forName(driverClass); connection = DriverManager.getConnection(url, user, password); String sql = "SELECT flow_id, type, id_card, exam_card, student_name, location, grade " + "FROM examstudent"; preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ int flowId = resultSet.getInt(1); int type = resultSet.getInt(2); String idCard = resultSet.getString(3); String examCard = resultSet.getString(4); String studentName = resultSet.getString(5); String location = resultSet.getString(6); int grade = resultSet.getInt(7); Student student = new Student(flowId, type, idCard, examCard, studentName, location, grade); students.add(student); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if(resultSet != null){ resultSet.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(preparedStatement != null){ preparedStatement.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(connection != null){ connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } return students; } }
/* * $Id: TokenProcessor.java 471754 2006-11-06 14:55:09Z husted $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.atguigu.javaweb.mvc; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class TokenProcessor { private long previous; public synchronized String generateToken(String id) { try { long current = System.currentTimeMillis(); if (current == previous) { current++; } previous = current; byte[] now = new Long(current).toString().getBytes(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(id.getBytes()); md.update(now); return toHex(md.digest()); } catch (NoSuchAlgorithmException e) { return null; } } private String toHex(byte[] buffer) { StringBuffer sb = new StringBuffer(buffer.length * 2); for (int i = 0; i < buffer.length; i++) { sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16)); sb.append(Character.forDigit(buffer[i] & 0x0f, 16)); } return sb.toString(); } public static void main(String[] args) { TokenProcessor tokenProcessor = new TokenProcessor(); String id = tokenProcessor.generateToken("尚硅谷"); System.out.println(id); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% //判断用户是否登录, 只有登录的用户才会得到响应. //登录方式有两种: //1. 从 login.jsp 页面提交表单 //2. 从含有登录名的 Cookie 中登录 String name = request.getParameter("name"); if(name == null){ Cookie [] cookies = request.getCookies(); if(cookies != null){ for(Cookie cookie: cookies){ if("loginName".equals(cookie.getName())){ name = cookie.getValue(); } } } } //把 loginName 保存在 Cookie 中, 并回传给浏览器 else{ Cookie cookie = new Cookie("loginName", name); cookie.setMaxAge(45); response.addCookie(cookie); } if(name == null){ response.sendRedirect("login.jsp"); }else{ out.print("Hello: " + name); } %> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="index.jsp" method="post"> name: <input type="text" name="name"/> <input type="submit" value="Submit"/> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h4>Book Detail Page</h4> Book: <%= request.getParameter("book") %> <br><br> <a href="books.jsp">Return</a> <% String book = request.getParameter("book"); Cookie tempCookie = null; //只显示最近浏览过的 3 件商品. //1. 获取所有满足条件的 Cookie List<Cookie> books = new ArrayList<Cookie>(); Cookie [] cookies = request.getCookies(); if(cookies != null && cookies.length > 0){ for(Cookie cookie: cookies){ String cookieName = cookie.getName(); if(cookieName.startsWith("book_")){ books.add(cookie); String cookieVal = cookie.getValue(); if(cookieVal.equals(book)){ tempCookie = cookie; } } } } if(books.size() == 5){ if(tempCookie == null){ tempCookie = books.get(0); } tempCookie.setMaxAge(0); response.addCookie(tempCookie); } //2. 在数组 length == 3 的情况下, 把最早的那个(即数组的第 1 个元素-下标是 0 的那个元素)删除 Cookie cookie = new Cookie("book_" + book, book); response.addCookie(cookie); %> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!-- 利用 Cookie 实现 "您浏览过的图书有: x, y, z", 只显示最近浏览的 3 本图书的信息 且支持 Cookie 的持久化. 其余的 Cookie 被删除: 调用其 setMaxAge() 方法, 传入 0 即可。 --> <h4>Books Page</h4> <a href="book.jsp?book=JavaWeb">Java Web</a><br><br> <a href="book.jsp?book=Java">Java</a><br><br> <a href="book.jsp?book=Oracle">Oracle</a><br><br> <a href="book.jsp?book=Ajax">Ajax</a><br><br> <a href="book.jsp?book=JavaScript">JavaScript</a><br><br> <a href="book.jsp?book=Android">Android</a><br><br> <a href="book.jsp?book=Jbpm">Jbpm</a><br><br> <a href="book.jsp?book=Struts">Struts</a><br><br> <a href="book.jsp?book=Hibernate">Hibernate</a><br><br> <a href="book.jsp?book=Spring">Spring</a><br><br> <br><br> <% StringBuilder books = new StringBuilder(""); Cookie [] cookies = request.getCookies(); if(cookies != null && cookies.length > 0){ for(Cookie cookie: cookies){ String cookieName = cookie.getName(); String cookieVal = cookie.getValue(); if(cookieName.startsWith("book_")){ books.append(cookieVal + " "); } } } if(!books.toString().equals("")){ out.print("您浏览过的商品有: " + books.toString()); } %> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h3>AAA PAGE</h3> <% String str = "abcde"; %> <!-- 在 a.jsp 中包含 b.jsp --> <%-- <%@ include file="b.jsp" %> --%> <jsp:include page="/include/b.jsp"> <jsp:param value="abcd" name="username"/> </jsp:include> <%-- <jsp:forward page="/include/b.jsp"> <jsp:param value="abcd" name="username"/> </jsp:forward> request.getRequestDispatcher("/include/b.jsp").forward(request, response); --%> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>BBB PAGE</h3>
<%= request.getParameter("username") %>
</body>
</html>
<%@page import="java.text.DateFormat"%> <%@ page language="java" contentType="text/html; charset=UTF-8" %> <%@ page pageEncoding="UTF-8" import="java.util.Date" %> <%@ page session="false" isELIgnored="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% Date date = new Date(); DateFormat dateFormat = null; HttpServletRequest req = null; //int i = 10 / 0; %> <form action="hello.jsp" method="get"> username: <input type="text" name="username"/> <input type="submit" value="Submit"/> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="GB2312"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h4>Hello Page</h4> 学习 Java! <br><br> <% request.setCharacterEncoding("UTF-8"); %> username: <%= request.getParameter("username") %> <br><br> <%-- String val = request.getParameter("username"); String username = new String(val.getBytes("UTF-8"), "UTF-8"); out.print(username); --%> </body> </html>
<%@page import="com.atguigu.javaweb.mvc.Student"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% List<Student> stus = (List<Student>)request.getAttribute("students"); %> <table border="1" cellpadding="10" cellspacing="0"> <tr> <th>FlowId</th> <th>Type</th> <th>IdCard</th> <th>ExamCard</th> <th>StudentName</th> <th>Location</th> <th>Grade</th> <th>Delete</th> </tr> <% for(Student student: stus){ %> <tr> <td><%= student.getFlowId() %></td> <td><%= student.getType() %></td> <td><%= student.getIdCard() %></td> <td><%= student.getExamCard() %></td> <td><%= student.getStudentName() %></td> <td><%= student.getLocation() %></td> <td><%= student.getGrade() %></td> <td><a href="deleteStudent?flowId=<%=student.getFlowId() %>">Delete</a></td> </tr> <% } %> </table> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 操作成功! <br><br> <a href="listAllStudents">List All Students</a> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 操作成功! <br><br> <a href="listAllStudents">List All Students</a> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.security.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <%!public static String TRANSACTION_TOKEN_KEY = "TRANSACTION_TOKEN_KEY"; public static String TOKEN_KEY = "TOKEN_KEY"; private long previous; public synchronized void resetToken(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { return; } session.removeAttribute(TRANSACTION_TOKEN_KEY); } public synchronized String saveToken(HttpServletRequest request) { HttpSession session = request.getSession(); String token = generateToken(request); if (token != null) { session.setAttribute(TRANSACTION_TOKEN_KEY, token); } return token; } public synchronized String generateToken(HttpServletRequest request) { HttpSession session = request.getSession(); return generateToken(session.getId()); } public synchronized String generateToken(String id) { try { long current = System.currentTimeMillis(); if (current == previous) { current++; } previous = current; byte[] now = new Long(current).toString().getBytes(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(id.getBytes()); md.update(now); return toHex(md.digest()); } catch (NoSuchAlgorithmException e) { return null; } } private String toHex(byte[] buffer) { StringBuffer sb = new StringBuffer(buffer.length * 2); for (int i = 0; i < buffer.length; i++) { sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16)); sb.append(Character.forDigit(buffer[i] & 0x0f, 16)); } return sb.toString(); }%> <%= generateToken(request) %> </body> </html>