JSP开发入门基础指南
## 1. Java基本程序设计
### 1.1 变量、常量与数据类型
```java
public class VariableExample {
public static void main(String[] args) {
// 变量声明
int age = 25;
double price = 19.99;
boolean isStudent = true;
char grade = 'A';
// 常量定义
final double PI = 3.14159;
final String COMPANY = "Tech Corp";
// 输出演示
System.out.println("年龄:" + age);
System.out.println("圆周率:" + PI);
System.out.println("是否学生:" + isStudent);
}
}
### 1.2 流程控制语句
```java
public class ControlFlowExample {
public static void main(String[] args) {
// if-else条件判断
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 75) {
System.out.println("良好");
} else {
System.out.println("继续努力");
}
// switch-case分支结构
int day = 3;
switch(day) {
case 1: System.out.println("星期一"); break;
case 2: System.out.println("星期二"); break;
case 3: System.out.println("星期三"); break;
default: System.out.println("周末");
}
// for循环累加
int sum = 0;
for(int i=1; i<=100; i++) {
sum += i;
}
System.out.println("1-100累加和:" + sum);
// while循环输入验证
int input = 0;
java.util.Scanner scanner = new java.util.Scanner(System.in);
while(input < 1 || input > 10) {
System.out.print("请输入1-10之间的数字:");
input = scanner.nextInt();
}
System.out.println("您输入的是:" + input);
// do-while循环
int factorial = 1, n = 5;
int i = 1;
do {
factorial *= i;
i++;
} while(i <= n);
System.out.println(n + "! = " + factorial);
}
}
```
### 1.3 数组
```java
public class ArrayExample {
public static void main(String[] args) {
// 一维数组声明与初始化
int[] scores = {85, 92, 78, 90}; // 静态初始化
String[] names = new String[4]; // 动态初始化
names[0] = "张三";
names[1] = "李四";
// 数组遍历
System.out.println("— 一维数组遍历 —");
for(int i=0; i<scores.length; i++) {
System.out.println(names[i] + "的成绩:" + scores[i]);
}
// 数组拷贝
int[] copyScores = new int[scores.length];
System.arraycopy(scores, 0, copyScores, 0, scores.length);
// 数组排序
java.util.Arrays.sort(scores);
System.out.println("\n排序后的成绩:" + java.util.Arrays.toString(scores));
// 二维数组示例
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("\n— 二维数组遍历 —");
for(int i=0; i<matrix.length; i++) {
for(int j=0; j<matrix[i].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
// 增强for循环遍历
System.out.println("\n使用增强for循环:");
for(int[] row : matrix) {
for(int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
```
### 1.4 面向对象程序设计
```java
// Person基类
public class Person {
private String name;
protected int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("姓名:" + name + " 年龄:" + age);
}
}
// Student子类
class Student extends Person {
private String studentId;
public Student(String name, int age, String id) {
super(name, age);
this.studentId = id;
}
@Override
public void display() {
super.display();
System.out.println("学号:" + studentId);
}
public void study() {
System.out.println("学生" + super.name + "正在学习");
}
}
class Main {
public static void main(String[] args) {
Student s = new Student("张三", 18, "2023001");
s.display();
Person p = new Student("李四", 20, "2023002");
if(p instanceof Student) {
((Student)p).study();
}
}
}
```
### 1.5 集合类的应用
```java
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
// ArrayList示例
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add(1, "Orange");
System.out.println("ArrayList元素:" + fruits);
// LinkedList遍历
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
System.out.print("LinkedList元素:");
numbers.forEach(n -> System.out.print(n + " "));
System.out.println();
// HashMap应用
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Math", 90);
scores.put("English", 85);
System.out.println("HashMap条目:");
for(Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// 集合排序示例
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("王五", 22, "2023003"));
studentList.add(new Student("赵六", 19, "2023004"));
// 使用Comparator按年龄排序
Collections.sort(studentList, Comparator.comparingInt(s -> s.age));
System.out.println("\n按年龄排序结果:" + studentList);
// 线程安全集合示例
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
syncList.add("线程安全元素");
System.out.println("\n线程安全集合:" + syncList);
}
}
class Student {
String name;
int age;
String studentId;
public Student(String name, int age, String id) {
this.name = name;
this.age = age;
this.studentId = id;
}
@Override
public String toString() {
return name + "(" + age + ")";
}
}
```
### 1.6 异常处理语句
```java
public class ExceptionExample {
// 自定义异常类
static class UserAuthException extends Exception {
public UserAuthException(String message) {
super(message);
}
public UserAuthException(String message, Throwable cause) {
super(message, cause);
}
}
public static void main(String[] args) {
// try-catch-finally基本结构
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("空指针异常:" + e.getMessage());
} finally {
System.out.println("清理资源操作");
}
// 多重异常捕获
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException | NumberFormatException e) {
System.out.println("数学计算异常:" + e.getClass().getSimpleName());
}
// 异常转译示例
try {
processUserInput("admin");
} catch (UserAuthException e) {
System.out.println("认证失败:" + e.getMessage());
System.out.println("根本原因:" + e.getCause().getMessage());
}
// try-with-resources语法
try (FileResource res = new FileResource()) {
res.readData();
} catch (IOException e) {
System.out.println("文件操作异常:" + e.getMessage());
}
}
// 抛出带异常链的自定义异常
private static void processUserInput(String input) throws UserAuthException {
try {
if(input.length() < 6) {
throw new IllegalArgumentException("密码长度不足");
}
} catch (IllegalArgumentException e) {
throw new UserAuthException("用户认证失败", e);
}
}
}
// 自动关闭资源实现
class FileResource implements AutoCloseable {
public void readData() throws IOException {
System.out.println("读取文件数据…");
throw new IOException("文件读取错误");
}
@Override
public void close() {
System.out.println("自动关闭文件资源");
}
}
```
## 2. JavaScript脚本语言
### 2.1 JavaScript概述
**基础语法示例:**
```javascript
// 变量声明
let message = 'Hello World';
const PI = 3.14159;
// 函数定义
function calculateArea(radius) {
return PI * radius ** 2;
}
// 事件处理示例
document.getElementById('myBtn').addEventListener('click', () => {
alert('按钮被点击!');
console.log(calculateArea(5));
});
// DOM操作演示
const updateContent = () => {
const container = document.createElement('div');
container.innerHTML = `<p>当前时间:${new Date().toLocaleString()}</p>`;
document.body.appendChild(container);
}
```
**JSP嵌入方式:**
```jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>JSP与JS结合示例</title>
<script>
// 页面加载完成后执行
window.onload = function() {
console.log('DOM准备就绪');
updateContent();
};
</script>
</head>
<body>
<button οnclick="updateContent()">更新内容</button>
<%@ include file="footer.jsp" %>
</body>
</html>
```
### 2.2 在JSP中引入JavaScript
```jsp
<%– 方式1:内联脚本嵌入 –%>
<script>
// 访问JSP变量
let serverTime = '<%= new java.util.Date() %>';
let userRole = '${user.role}';
// 转义特殊字符
let productName = '<%= org.apache.commons.text.StringEscapeUtils.escapeEcmaScript(product.getName()) %>';
</script>
<%– 方式2:外部文件引用 –%>
<script src="${pageContext.request.contextPath}/js/common.js"></script>
<script src="<%= request.getContextPath() %>/js/module.js"></script>
<%– 方式3:JSTL动态生成脚本 –%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script>
<c:choose>
<c:when test="${user.vipLevel gt 3}">
const MAX_ITEMS = 50;
const ALLOW_DOWNLOAD = true;
</c:when>
<c:otherwise>
const MAX_ITEMS = 20;
const ALLOW_DOWNLOAD = false;
</c:otherwise>
</c:choose>
</script>
<%– AJAX数据交互示例 –%>
<script>
fetch('data.jsp?category=${param.category}')
.then(response => response.json())
.then(data => {
document.getElementById("result").innerHTML =
`当前分类:${data.category},记录数:${data.count}`;
});
</script>
<%– 安全防护措施 –%>
<script>
// XSS防护示例
const userInput = `<%= org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(request.getParameter("input")) %>`;
// CSP设置建议
meta.http-equiv="Content-Security-Policy"
content="script-src 'self' https://trusted.cdn.com"
</script>
<%– 性能优化建议 –%>
<!– 推荐放在body底部 –>
<script defer src="lazy-load.js"></script>
<!– 异步加载 –>
<script async src="analytics.js"></script>
```
### 2.3 JavaScript的数据类型与运算符
```javascript
// 基本数据类型
let age = 25; // number类型
let name = "张三"; // string类型
let isVip = true; // boolean类型
let emptyVar = null; // null类型
let undefinedVar; // undefined类型
let sym = Symbol('id'); // symbol类型 (ES6)
let person = {name: '李四', age: 30}; // object类型
console.log(typeof age); // "number"
console.log(typeof undefinedVar); // "undefined"
// 类型转换示例
let strToNum = Number("123"); // 显式转换 → 123
let numToStr = 456 + ''; // 隐式转换 → "456"
console.log(Boolean("")); // false
console.log(!!"hello"); // true
// 特殊值检测
console.log(isNaN(NaN)); // true
console.log(Number.isNaN("abc")); // false (ES6严格检测)
console.log(0.1 + 0.2 === 0.3); // false (浮点精度问题)
// == 与 === 区别
console.log(1 == "1"); // true (值相等)
console.log(1 === "1"); // false (类型不等)
console.log(null == undefined); // true
console.log(null === undefined); // false
// 运算符优先级
let result = 3 + 4 * 5 ** 2; // 3 + (4*(5²)) = 103
console.log(`运算结果:${result}`);
// ES6展开运算符
let arr1 = [1, 2, 3];
let arr2 = […arr1, 4, 5]; // [1,2,3,4,5]
console.log(Math.max(…arr2)); // 5
// 解构赋值
let [a, b] = [10, 20]; // a=10, b=20
let {name: userName} = person; // userName="李四"
// 可选链操作符 (ES2020)
let street = user?.address?.street; // 避免undefined错误
```
### 2.4 JavaScript流程控制语句
```javascript
// 条件判断结构
function checkAge(age) {
if (age < 18) {
return '未成年';
} else if (age >= 18 && age < 60) {
return '成年人';
} else {
return '老年人';
}
}
// switch-case示例
function getDayName(dayNum) {
switch(dayNum) {
case 1: return '周一';
case 2: return '周二';
// … 其他周几
default: throw new Error('无效的星期数字');
}
}
// 循环结构示例
function calculateSum() {
// 传统for循环
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
// while循环
let counter = 5;
while(counter > 0) {
console.log(`倒计时:${counter}`);
counter–;
}
// ES6 for-of循环
const fruits = ['Apple', 'Banana', 'Orange'];
for (const fruit of fruits) {
console.log(fruit);
}
}
// 表单验证实际案例
function validateForm() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (!username || username.length < 6) {
showError('用户名至少6位');
return false;
}
if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(password)) {
showError('密码需包含字母和数字且至少8位');
return false;
}
return true;
}
// DOM元素批量操作
function highlightEvenRows() {
document.querySelectorAll('tr').forEach((row, index) => {
if (index % 2 === 0) {
row.style.backgroundColor = '#f0f0f0';
}
});
}
// 箭头函数中的流程控制
const processData = data => {
return data.map(item => {
if (item.status === 'pending') {
return {…item, badge: '待处理'};
} else if (item.status === 'completed') {
return {…item, badge: '已完成'};
}
return item;
});
};
```
### 2.5 JavaScript应用实例
```javascript
// 增强型表单验证
class FormValidator {
constructor(formId) {
this.form = document.getElementById(formId);
this.errors = new Set();
this.form.addEventListener('submit', (e) => {
if(!this.validate()) {
e.preventDefault();
this.showErrors();
}
});
}
validate() {
this.errors.clear();
// 用户名验证
const username = this.form.username.value.trim();
if(username.length < 6) {
this.errors.add('用户名至少6位');
}
// 密码强度验证
const password = this.form.password.value;
if(!/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/.test(password)) {
this.errors.add('密码需包含大小写字母和数字且至少8位');
}
// 邮箱格式验证
const email = this.form.email.value;
if(!/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/.test(email)) {
this.errors.add('邮箱格式不正确');
}
return this.errors.size === 0;
}
showErrors() {
const errorContainer = document.createElement('div');
errorContainer.className = 'alert';
errorContainer.innerHTML = `<ul>${[…this.errors].map(e => `<li>${e}</li>`).join('')}</ul>`;
this.form.prepend(errorContainer);
}
}
// 自动轮播组件
class AutoCarousel {
constructor(containerId, interval = 5000) {
this.container = document.getElementById(containerId);
this.slides = this.container.querySelectorAll('.slide');
this.currentIndex = 0;
this.interval = interval;
this.init();
}
init() {
this.slides[0].classList.add('active');
setInterval(() => this.nextSlide(), this.interval);
}
nextSlide() {
this.slides[this.currentIndex].classList.remove('active');
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
this.slides[this.currentIndex].classList.add('active');
}
}
// AJAX数据交互示例
const api = {
fetchData: async (url) => {
try {
const response = await fetch(url);
if(!response.ok) throw new Error(`HTTP错误 ${response.status}`);
return await response.json();
} catch(error) {
console.error('请求失败:', error);
return null;
}
},
postData: async (url, data) => {
const response = await fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
});
return await response.json();
}
};
// 本地购物车管理
const cartManager = {
key: 'shopping_cart',
getCart() {
return JSON.parse(localStorage.getItem(this.key)) || [];
},
addItem(item) {
const cart = this.getCart();
const existing = cart.find(i => i.id === item.id);
existing ? existing.quantity++ : cart.push({…item, quantity: 1});
this.saveCart(cart);
},
removeItem(itemId) {
const cart = this.getCart().filter(i => i.id !== itemId);
this.saveCart(cart);
},
saveCart(cart) {
localStorage.setItem(this.key, JSON.stringify(cart));
document.dispatchEvent(new Event('cartUpdated'));
}
};
// 图片懒加载优化
const lazyLoad = () => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if(entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img);
});
};
// XSS防护示例
const sanitizeInput = (input) => {
const div = document.createElement('div');
div.textContent = input;
return div.innerHTML;
};
// 初始化应用
window.addEventListener('DOMContentLoaded', () => {
new FormValidator('mainForm');
new AutoCarousel('productCarousel');
lazyLoad();
// 购物车事件监听
document.addEventListener('cartUpdated', () => {
console.log('购物车更新:', cartManager.getCart());
});
});
```
作者:雪花一片