JSP ( Java Server Pages )
1、什么是JSP
-
java服务器端页面。
-
JSP页面可以嵌入java代码,为用户提供动态数据。
2、JSP原理
-
代码层面没有任何问题。
-
服务器内部工作。
-
tomcat中有有一个work目录
-
IDEA使用Tomcat会在IDEA的Tomcat中产生一个work目录。
-
-
JSP本质上就是一个Servlet。
//初始化 public void _jspInit(){} //销毁 public voidd _jspDestroy(){} //JSPServlet public void _jspService(final request, final response) throws ServletException {}-
判断请求
-
内置一些对象
-
输出页面前增加的代码
-
以上的这些对象我们可以在JSP页面中直接使用
-
3、JSP语法和指令
JSP表达式:
<%--jsp表达式 用来将程序的输出,输出到客户端 --%> <%= new java.util.Date()%>
JSP脚本片段
<%--JSP脚本片段--%>
<%
int sum = 0;
for (int i = 0; i <=100 ; i++) {
sum+=i;
}
out.print("<h2>Sum="+sum+"</h2>");
%>
脚本片段的再实现
<%--JSP脚本片段--%>
<%
int sum = 0;
for (int i = 0; i <=100 ; i++) {
sum+=i;
}
out.print("<h2>Sum="+sum+"</h2>");
%>
<hr>
<%
int x = 10;
out.print(x);
%>
<p>这个一个JSP文档</p>
<%
int y = 10;
out.print(y);
%>
<hr>
<%--在java代码里面嵌入html元素--%>
<%
for (int i = 0; i < 5; i++) {
%>
<h3>Hello World! <%= i %> <h3>
<%
}
%>
JSP声明
<%--JSP声明--%>
<%!
static {
System.out.println("你好!!");
}
private String name = "李白";
public void hl(){}
%>
区别
-
JSP声明:会被编译到JSP生产的Java类中。
-
其他的:就会被声生成到_jspService方法里。
4、配置404、500错误页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>500</title> </head> <body> <img src="../img/500.png" alt="500"> </body> </html>
<error-page> <error-code>500</error-code> <location>/error/500.jsp</location> </error-page>
5、提出公共页面(网页头部、脚部)
<%-- @include会将两个页面合二为一 --%> <%@include file="/common/header.jsp"%> <h1>网页主体</h1> <%@include file="/common/footer.jsp"%> <hr> <%-- jsp:include 拼接页面,本质是三个页面 --%> <jsp:include page="/common/header.jsp" /> <h1>网页主体</h1> <jsp:include page="/common/footer.jsp" />
6、九大内置对象
-
PageContext 存东西
-
Request 存东西
-
Response
-
Session 存东西
-
Application 【ServletContext】 存东西
-
config 【ServletConfig】
-
out
-
page
-
exception
<%--内置对象--%>
<%
pageContext.setAttribute("name1","李白1号");//保存的数据只在一个页面中有效
request.setAttribute("name2","李白2号");//只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","李白3号");//只在一个会话中有效(打开浏览器到关闭浏览器)
application.setAttribute("name4","李白4号");//数据在服务器中有效(打开服务器到关闭服务器)
%>
7、JSP标签,JSTL标签,EL表达式
EL表达式:${}
-
获取数据
-
执行运算
-
获取web开发的常用对象
-
需要导包:
<!-- JSTL表达式 依赖 -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库 -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
JSP标签
<jsp:include page=""/>
<jsp:forward page="">
<%-- 相当于:http://localhost:8080/static/jsp/jsptag.jsp?name1=value1$name2=value2 --%>
<jsp:param name="name1" value="value1"/>
<jsp:param name="name2" value="value2"/>
</jsp:forward>
JSTL标签库
JSTL标签库的使用就是为了弥补HTML标签的不足;其自定义了许多标签。
核心标签,需要引入:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Demo:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>if测试</h2>
<hr>
<form action="coreif.jsp" method="get">
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
<%--判断如果提交的用户是管理员则登录成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="管理员${param.username},进入系统!"/>
</c:if>
<c:out value="${isAdmin}"/>
</body>
</html>
8、JavaBean
-
实体类,有特定的写法。
-
必须要有一个无参构造。
-
属性必须私有化。
-
必须有对应的get/set方法。
一般用来和数据库的字段做映射: ORM。
ORM:对象关系映射
-
表--->类
-
字段--->属性
-
行记录--->对象
people表
| id | name | age | address |
|---|---|---|---|
| 1 | 李白1号 | 3 | 唐代 |
| 2 | 李白2号 | 18 | 唐代 |
| 3 | 李白3号 | 100 | 唐代 |
class People{
private int id;
private String name;
private int age;
private String address;
}
class A{
new People(1,"李白1号",3,"唐代");
new People(2,"李白2号",18,"唐代");
new People(3,"李白3号",100,"唐代");
}
-
过滤器
-
文件上传
-
邮件发送
-
jdbc
9、MVC三层架构
什么是MVC : Model、view、Controller 模型、视图、控制器
Model:
-
业务处理:业务逻辑(Service)
-
数据持久层:CRUD(Dao)
view:
-
展现数据
-
提供连接发起Servlet请求
Controller: (Servlet)
-
接收用户的请求:(req:请求参数、Session信息...)
-
提交给业务层处理
-
控制视图跳转
10、过滤器(Filter)
作用:过滤网站的数据。
-
处理中文乱码。
-
处理登录验证码。
Filter开发步骤:
-
导包
-
编写过滤器
-
导包不要错(javax.servlet)
-
-
在web.xml配置filter
public class CharacterEncodingFilter implements Filter {
//初始化:web服务器启动就已经初始化了
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
//filterChain:链
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html;charset='UTF-8");
filterChain.doFilter(servletRequest,servletResponse);//让我们的请求继续走,如果不写程序到这就会拦截
}
//销毁:服务器关闭时销毁
@Override
public void destroy() {
}
}
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.hl.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern><!--过滤/servlet文件夹下的所有请求-->
</filter-mapping>
11、监听器
实现一个监听器的接口;
-
编写一个监听器,实现监听器的接口。
-
在web.xml中注册监听器。
//统计网站在线人数:统计session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer)servletContext.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count++);
}
servletContext.setAttribute("OnlineCount",onlineCount);
}
//销毁session监听
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer)servletContext.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count--);
}
servletContext.setAttribute("OnlineCount",onlineCount);
}
}
<listener>
<listener-class>
com.hl.listener.OnlineCountListener
</listener-class>
</listener>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>当前有:<%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%></h1>
</body>
</html>
12、过滤器、监听器的常见应用
监听器:GUI编程中经常使用;
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame("小练习");//新建一个窗口
Panel panel = new Panel(null);//面板
frame.setLayout(null);//设置窗口布局
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(0,0,225));
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(0,225,0));
frame.add(panel);
frame.setVisible(true);
//监听事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
}
});
}
}
用户登录后才能进入主页,用户注销后就不能进入主页了。
-
用户登录之后,把用户数据放到Session中。
-
进入主页时,判断用户是否已经登录;在过滤器中实现。
HttpServletRequest request1 = (HttpServletRequest) servletRequest;
HttpServletResponse response1 = (HttpServletResponse) servletResponse;
if (request1.getSession().getAttribute(Constan.USER_SESSIION)==null){
response1.sendRedirect("/error.jsp");
}
filterChain.doFilter(servletRequest,servletResponse);
13、JDBC
什么是JDBC:java连接数据库。
需要jar包支持:
-
java.sql
-
javax.sql
-
mysql-conneter-java 连接驱动
-
...
环境搭建:
CREATE TABLE users( id INT PRIMARY KEY, `name` VARCHAR(40), `password` VARCHAR(40), email VARCHAR(60), brithday DATE ); INSERT INTO users(id,`name`,`password`,email,brithday) VALUE(1,'张三','123456','zs.@qq.com','2000-01-01'); INSERT INTO users(id,`name`,`password`,email,brithday) VALUE(2,'李四','123456','ls@qq.com','2000-02-11'); INSERT INTO users(id,`name`,`password`,email,brithday) VALUE(3,'王五','123456','ww@qq.com','2000-11-21');
1.导入数据库依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
2.IDEA中连接数据库
JDBC固定步骤
public class TestJdbc {
public static void main(String[] args) throws Exception {
//配置信息
//useUnicode=true&characterEncoding=utf-8 : 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="root";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送sql的对象Statement
Statement statement = connection.createStatement();
//4.编写sql语句
String sql = "select * from users;";
//5.执行sql,返回一个结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//6.关闭资源
rs.close();
statement.close();
connection.close();
}
}
预编译sql
public class TestJdbc2 {
public static void main(String[] args) throws Exception {
//配置信息
//useUnicode=true&characterEncoding=utf-8 : 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="root";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写sql语句
String sql = "insert into users(id, name, password, email, birthday) VALUES (?,?,?,?,?);";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,4);
preparedStatement.setString(2,"李白");
preparedStatement.setString(3,"123456");
preparedStatement.setString(4,"lb@qq.com");
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
//5.执行sql,返回一个结果集
int i = preparedStatement.executeUpdate();
if (1>0){
System.out.println("插入成功!");
}
//6.关闭资源
preparedStatement.close();
connection.close();
}
}
事务
-
ACID原则:保证数据安全
开启事务
事务提交
事务回滚
关闭事务
转账:
A:1000
B:1000
A(900) ---100---> B(1100)
通过操作数据库方式:
start transaction; #开启事务 update account set money = money - 100 where name = 'A'; update account set money = money + 100 where name = 'B'; rollback ;#回滚 commit ;#提交
通过java方式:
public class TestJdbc3 {
@Test
public void test(){
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="root";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, username, password);
//开启事务.false代表开启
connection.setAutoCommit(false);
String sql = "update account set money = money - 100 where name = 'A';";
connection.prepareStatement(sql).executeQuery();
//制造错误
int i = 1/0;
String sql1 = "update account set money = money + 100 where name = 'B';";
connection.prepareStatement(sql1).executeQuery();
connection.commit();
System.out.println("提交成功!");
}catch (Exception e){
try {
connection.rollback();
} catch (SQLException throwables) {
e.printStackTrace();
}
System.out.println("!!!");
}finally {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
junit单元测试
@Test注解只在方法中有效
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>compile</scope>
</dependency>
@Test
public void test(){
System.out.println("hello");
}
本文详细介绍了JSP的基本概念、工作原理,涵盖了JSP语法、指令、内置对象、JSP标签、EL表达式、JavaBean、MVC架构,以及过滤器、监听器和JDBC的应用实例。深入浅出地展示了如何利用JSP进行动态网页开发和数据交互。
1100

被折叠的 条评论
为什么被折叠?



