JSP的基础使用及应用案例
引言:
本文主要分享了有关JSP的相关知识,包括:JSP页面的格式、九个隐式对象、JSP三个页面的交互、JSP注释、输出语法、编译指令(导包、include)、JSP中调用类对象、遍历集合、使用JSP实现从数据库中拿到数据然后输出;
@[toc]
1. JSP开发_引入
- 文件后缀.jsp
- 文件首行编译指令
- <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
- jsp: java server page 服务器端页面
2. JSP的九个隐式对象
JSP中编译执行时默认会产生9个隐式对象:
2.1 Request :请求对象
javax.servlet.http.HttpServletRequest 类的实例,获取客户端请求信息,主要用于接受http协议传送到服务器的数据,当页面请求到web容器时,JSP引擎对请求数据信息封装成request
常用方法:
- request.getParameter("表单属性名称"):获取表单参数,返回值String;
- request.setAttribute("key","value"):设定请求转发对象;
- Object obj = request.getAttribute("key"):获取请求转发对象;
- request.getRequestDispatcher("去往页面").forward(request,response):页面请求转发;
2.2 Response:响应对象
javax.servlet.http.HttpServletResponse类的实例,代表客户端的响应,当服务器创建request对象时会同时创建用于响应这个客户端的response对象,主要用于将jsp容器处理过的对象传送到客户端;
服务器响应客户端时对外发出的信息统一封装成reponse对象,随request同时创建;
2.3 out对象
响应输出为输出对象,可以把字符型打印到浏览器,打印流(PrintWriter),用来在response对象中写入内容;
2.4 session对象
javax.servlet.http.HttpSession 类的实例,代表浏览器的一次回话,用来跟踪在各个客户端请求间的会话;
有多次请求组成,有生命周期在tomcat的server.xml中设定默认25‘或30’
- 同一设备同一浏览器发出多次请求,属于同一session;
- 同一设备,不同浏览器发出多次请求,为不同session;
- 不同设备发出请求属于不同session
- session超时就终止
- 服务关闭,session清空
2.5 application对象
application对象直接包装了servlet的ServletContext类的对象,是javax.servlet.ServletContext 类的实例,代表当前的web应用类似于一个全局变量;
全局作用域,随服务器启动创建,随服务器关闭消亡;
2.6 config对象
javax.servlet.ServletConfig 类的实例,包装了servlet的ServletConfig类的对象,可以获取服务器的配置信息;
2.7 pageContext对象
javax.servlet.jsp.PageContext 类的实例,页面的上下文对象,可以从中获取到当前页面的其他信息,可以从中获取到其他8个隐含对象;
2.8 Page对象
指的是当前jsp对应的servlet对象的引用
2.9 exception对象
用来处理jsp文件在执行时所产生的错误和异常
3. GET和POST传输方式
get请求地址或链接请求 参数会坠在请求url中 ,有大小限制2k大小;
post:邮寄 无大小限制 ;
4. JSP案例(输入界面--->JSP处理--->展示界面)
4.1 输入界面
<%@ 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>提交页面</title>
<style type="text/css">
html{
heigth: 100%;
}
body{
heigth:100%;
margin:0px;
background-image : url("img/back.jpg");
background-size : cover;
}
#center{
width: 100%;
padding-top: 40px;
display: flex;
align-items: center;
justify-content: center;
color: red;
}
#center input{
margin-top: 5px;
width: 300px;
height: 35px;
border: 1px solid gray;
border-radius: 3px;
}
#submit input{
align-items: center;
justify-content: center;
margin-top: 5px;
width: 150px;
height: 35px;
margin-left:900px;
}
</style>
</head>
<body>
<div>
<form action="dispose.jsp" method = "POST">
<font size="7" color="black" face="华文行楷" ><h1><center>提交信息</center></h1></font>
<div id = "center">
<table >
<tr>
<td >成员姓名</td>
<td>
<input type = "text" name = "stuname" placeholder="输入姓名!!!"/>
</td>
</tr>
<tr>
<td>年 龄</td>
<td>
<input type = "text" name = "age" placeholder="输入年龄!!!"/>
</td>
</tr>
<tr>
<td>毕业院校</td>
<td>
<input type = "text" name = "school" placeholder="输入院校!!!"/>
</td>
</tr>
<tr>
<td>所学专业</td>
<td>
<input type = "text" name = "specialty" placeholder="输入专业!!!"/>
</td>
</tr>
<tr>
<td>目前住址</td>
<td>
<input type = "text" name = "address" placeholder="输入地址!!!"/>
</td>
</tr>
<tr>
<td>联系电话</td>
<td>
<input type = "text" name = "phone" placeholder="输入电话!!!"/>
</td>
</tr>
</table>
</div>
<div id = "submit">
<table >
<tr>
<td colspan="2">
<input type = "submit" value = "提交"/>
</td>
</tr>
</table>
</div>
</form>
</div>
</body>
</html>
4.2 JSP处理操作
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//请求转化
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
//接收表单请求参数
String stuname = request.getParameter("stuname");
int age = Integer.parseInt(request.getParameter("age"));
String school = request.getParameter("school");
String specialty = request.getParameter("specialty");
String address = request.getParameter("address");
String phone = request.getParameter("phone");
//业务处理
System.out.println("stuname:" + stuname +"age:" + age + "school:" + school + "specialty:" + specialty + "address:" + address + "phone:" + phone);
//显示成功页面
RequestDispatcher rd = request.getRequestDispatcher("show.jsp");
//请求转发
rd.forward(request, response);
%>
4.3 展示界面
<%@ 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>展示页面</title>
<style type="text/css">
html{
heigth: 100%;
}
body{
heigth:100%;
margin:0px;
background-image : url("img/1.jpg");
background-size : cover;
}
#center{
width: 100%;
padding-top: 40px;
display: flex;
align-items: center;
justify-content: center;
color: black;
font-fimaly:"楷体";
font-size: 50px;
font-style: oblique;
font-weight: bolder;
}
</style>
</head>
<body>
<div>
<font size="7" color="black" face="华文行楷" ><h1><center>展示页面</center></h1></font>
<div id = "center">
<table >
<tr>
<td>
<%
out.write("学员姓名:"+request.getParameter("stuname") + "</br>");
out.write("学员年龄:"+request.getParameter("age") + "</br>");
out.write("毕业院校:"+request.getParameter("school") + "</br>");
out.write("所学专业:"+request.getParameter("specialty") + "</br>");
out.write("现住地址:"+request.getParameter("address") + "</br>");
out.write("电话号码:"+request.getParameter("phone") + "</br>");
%>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
4.4 运行结果
5. JSP相关语法及知识
5.1 JSP注释
HTML注释:
< !-- xxxx-- > :可以发送到浏览器中;
JSP注释:
<%--xxxxxx--%>:只能存在于jsp中,不会随网页发往浏览器;
<!-- HTML注释,浏览器可见 -->
<%--Java注释,浏览器不可见 --%>
5.2 JSP中的输出语法
- 输出到java控制台 System.out.XXX() 原生的java语法
out输出:输出到响应流中
- <% out.print("xxxx")%>
表达式输出
- <%=java表达式%>
5.2.1 home.html页面传入数据
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Person info...</title>
<style>
body{
text-align: center;
}
</style>
</head>
<script>
function fasong(){
alert("fasong....");
var form1 = window.document.getElementById("form1");
form1.submit();
}
</script>
<body>
<h2>欢迎你!!!</h2>
<form action="dealPerson.jsp" method="GET" id = "form1">
<table align = "center">
<tr><td align = "right">personName:</td><td><input type = "text" name = "name"/></td></tr>
<tr><td align = "right">age:</td><td><input type = "text" name = "age"/></td></tr>
<tr><td align = "right">sex:</td>
<td>
<input type = "radio" name = "sex" value = "man"/>男
<input type = "radio" name = "sex" value = "woman"/>女
</td></tr>
<tr><td colspan = "2"><input type = "button" value = "发送" onclick = "fasong()"/></td></tr>
</table>
</form>
</body>
</html>
5.2.2 Java输出以及Out输出
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//获取表单提交的内容
String name = request.getParameter("name");
String ageStr = request.getParameter("age");
String sex = request.getParameter("sex");
int age = Integer.parseInt(ageStr);
//Java输出
System.out.println(name + "\t" + age +"\t" +sex);
out.print("<html><head><title>使用Java书写HTML</title></head>");
out.print("<body>");
out.print("<h2>");
out.print(name+" "+age+" "+sex);
out.print("</h2>");
out.print("</body></html>");
%>
5.2.3 表达式输出
<%@ 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>使用Java书写HTML</title>
</head>
<body>
<h2>
<%
//获取表单提交的属性数据
String name = request.getParameter("name");
String ageStr = request.getParameter("age");
String sex = request.getParameter("sex");
int age = Integer.parseInt(ageStr);
%>
<%--JSP表达式:必须等号开始,不能带有分号 --%>
name:<%=request.getParameter("name") %><br/>
age:<%=request.getParameter("age") %><br/>
sex:<%=request.getParameter("sex") %><br/>
</h2>
</body>
</html>
5.3 JSP常见的编译指令
5.3.1 page
import属性(导包):
- 方法1: <%@ page language="java" contentType="text/html; charset=UTF-8"
import="java.util.,java.text." pageEncoding="UTF-8"%> - 方法2:<%@page import ="java.text.*" %>
<!-- 打印当前系统时间-->
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@page import = "java.text.*" %>
<!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();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(date);
%>
<%=dateStr %>
</body>
</html>
5.3.2 include
语法:<%@include file="xxx.jsp"%>
- 作用:将页面通用部分单独作为一个页,可以重复利用便于修改;
5.3.2.1 页头
<%@ 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>
<h2>页头</h2>
<span align = "right"></span>
</body>
</html>
5.3.2.2页脚
<%@ 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>
<h2>页脚</h2>
</body>
</html>
5.3.2.3 main.jsp_添加页头页脚
<%@ 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>
<%@include file = "header.jsp" %>
<h2>main content......</h2>
<%@include file = "footer.jsp" %>
</body>
</html>
5.3.2.4 list.jsp_复用页头页脚
<%@ 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>
<%@include file="header.jsp" %>
<h2>我是商品列表清单</h2>
<%@include file="footer.jsp" %>
</body>
</html>
5.4 JSP中调用Java类对象
步骤:
- 导包
- 创建对象
- 调用方法
5.4.1 编写Person类
package com.kaka.entity;
public class Person {
private int pid;
private String pname;
private int age;
private String address;
public Person() {
super();
}
public Person(int pid, String pname, int age, String address) {
super();
this.pid = pid;
this.pname = pname;
this.age = age;
this.address = address;
}
@Override
public String toString() {
return "Person [pid=" + pid + ", pname=" + pname + ", age=" + age + ", address=" + address + "]";
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
5.4.2 编写entityUse,jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="com.kaka.entity.Person"%>
<%
//jsp中使用java对象-实体应用
Person person = new Person();
person.setPid(1001);
person.setPname("kaka");
person.setAge(23);
person.setAddress("陕西省西安市");
//将person对象放入request作用域中
request.setAttribute("person", person);
request.getRequestDispatcher("success.jsp").forward(request, response);
%>
5.4.3 编写success,jsp
<%@ page language="java" import="com.kaka.entity.Person" 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>
<%
if( request.getAttribute("person")!=null){
Person per = (Person) request.getAttribute("person");
out.write(per.toString());
}
%>
</body>
</html>
5.4.4 运行结果
5.5 JSP中如何遍历Java集合对象
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import = "com.kaka.entity.Person,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>
<%
//jsp中遍历对象对象应用
List<Person> li = new ArrayList<Person>();
li.add(new Person(1001,"kaka",23,"西安"));
li.add(new Person(1002,"zhangsan",23,"武汉"));
li.add(new Person(1003,"lisi",23,"北京"));
li.add(new Person(1004,"wangwu",23,"西安"));
%>
<table>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>address</th>
</tr>
<%for(int i=0;i<li.size();i++) {
Person p = (Person) li.get(i);
%>
<tr>
<td><%=p.getPid() %></td>
<td><%=p.getPname() %></td>
<td><%=p.getAge() %></td>
<td><%=p.getAddress() %></td>
</tr>
<%} %>
</table>
</body>
</html>
遍历结果
5.6 JSP实现数据库查找功能
利用JDBC从数据库中拿到数据,在通过JSP页面显示出来
5.6.1 编写Dept.java类
package com.kaka.entity;
public class Dept {
private int id;
private String name;
private String sex;
private String age;
public Dept() {
super();
}
public Dept(int id, String name, String sex, String age) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
@Override
public String toString() {
return "Dept [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
5.6.2 编写BaseDao.javaJDBC工具类
package com.kaka.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
//定义常量
final static String driver = "com.mysql.jdbc.Driver";
final static String url = "jdbc:mysql://localhost:3306/db0711?useUnicode=true&characterEncoding=utf8";
final static String username = "root";
final static String password = "root";
//声明常用的对象
protected Connection conn = null;
protected PreparedStatement pstmt = null;
protected ResultSet rs = null;
//静态块
static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接
public void getConnection(){
try {
conn = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭资源
public void closeAll(){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstmt != null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
5.6.3 编写接口类DeptDao.java
package com.kaka.dao;
import java.util.List;
import com.kaka.entity.Dept;
public interface DeptDao {
public List<Dept> findAll();
}
5.6.4 编写接口实现类DeptDaoImpl.java
package com.kaka.dao.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.kaka.dao.DeptDao;
import com.kaka.entity.Dept;
import com.kaka.util.BaseDao;
public class DeptDaoImpl extends BaseDao implements DeptDao{
@Override
public List<Dept> findAll() {
String sql = "select * from student";
List<Dept> li = new ArrayList<Dept>();
try {
super.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
Dept d = new Dept();
d.setId(rs.getInt("id"));
d.setName(rs.getString("name"));
d.setSex(rs.getString("sex"));
d.setAge(rs.getString("age"));
li.add(d);
}
return li;
} catch (SQLException e) {
e.printStackTrace();
}finally{
super.closeAll();
}
return null;
}
}
5.6.5 编写showDept.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*,com.kaka.entity.*,com.kaka.dao.*,com.kaka.dao.impl.*"%>
<!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>
<table>
<tr>
<td>ID</td><td>NAME</td><td>SEX</td><td>AGE</td>
</tr>
<%
DeptDao deptDao = new DeptDaoImpl();
List<Dept> depts = deptDao.findAll();
for(int i = 0; i < depts.size(); i++){
Dept d = depts.get(i);
%>
<tr>
<td><%=d.getId() %></td>
<td><%=d.getName() %></td>
<td><%=d.getAge() %></td>
<td><%=d.getSex() %></td>
<td><a href = "#">编辑</a><a href = "#">删除</a></td>
</tr>
<%}%>
</table>
</body>
</html>