If it helps you, remember to like and follow me!
Each experiment has 2~3 small questions, the code can be found on Baidu Baike, but they are all VIP documents, and there are some minor problems, such as Chinese garbled codes.
Experiment topic: ①JSP syntax ②JSP built-in objects ③JSP and JavaBean ④Use of database in JSP
Experiment 4 requires Tomcat to connect to the database. Many students failed to connect. There are also problems such as garbled code passing by JSP. So the following report, I will write backwards, first experiment 4, then experiment 3, 2, and 1, the code is very simple and easy to understand.
Project catalog overview
Experiment 4 Using Database in JSP
Step 1: Import JDBC to External Libraries
If you don’t, you can see https://blog.csdn.net/SSY_1992/article/details/88344709
Step 2: Use the Java console to verify whether the JDBC connection is successful
package bean.data;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class test {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/book", "root", "请输入你的密码");
String sql = "UPDATE bookform SET bookISBN = 3333 WHERE bookISBN = 987654";
Statement stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(count);
stmt.close();
conn.close();
}
}
Operation result (database content will be modified and will not be shown here)
Step 3: Let Tomcat connect to the database!
Click "File", select "Project Structure", then select "Artifacts", and click the "plus" on the map.
Select "Web Application:Exploded——"From Modules" and add the untitled1 module. My place here (I don’t know what it is called, let’s call it "Files") by default under "Available Elements", and I need to put all the "under the untitled1 module" "Files" are all double-clicked to move to the <output root> path, which becomes a file under WEB-INF.
JSP saves Chinese data into the database as a solution to the question mark
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/book","root","***");
//在book后面添加?useUnicode=true&characterEncoding=UTF8
The blogger introduced three methods, I only used the first one, and the problem was solved.
Before the solution
After solving
MySQL Workbench (please add tables by yourself, I won’t repeat them here)
PK: primary key
NN: not null
UQ: unique unique index
BIN: binary binary data (larger than text)
UN: unsigned unsigned (non-negative number)
ZF: zero fill fill with 0, for example, the field content is 1 int( 4), the content is displayed as 0001
AI: auto increment
1. The purpose of the experiment
1. Master the use of JDBC to query the records of tables in the database;
2. Master the use of JDBC to update the records of the tables in the database.
2. Experimental content
1. Database query operation
First create a database Book, and create a table bookForm in the library. The table fields refer to the 7 columns in the following renderings. Write a JSP page inputMess.jsp, search for and return information based on keywords.
The effect of inputMess.jsp is as follows:
Source code
inputMess2.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.lang.*" %>
<%@ page import="java.lang.String.*" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
%>
<form action="">
输入查询内容:<input type="text" name="findContent" value=""/>
<select name="condition" size=1>
<option Selected value="bookISBN">ISBN</option>
<option value="bookName">书名</option>
<option value="bookAuthor">作者</option>
<option value="bookPublish">出版社</option>
<option value="bookTime">出版时间</option>
<option value="bookAbstract">内容摘要</option>
</select>
<br>
<input type="radio" name="findMethod" value="start"/>前方一致
<input type="radio" name="findMethod" value="end"/>后方一致
<input type="radio" name="findMethod" value="contains"/>包含
<br>
<input type="submit" value="提交"/>
</form>
<%
String findContent = request.getParameter("findContent");
if (findContent == null)
findContent = "";
String condition = request.getParameter("condition");
if (condition == null)
condition = "";
String findMethod = request.getParameter("findMethod");
if (findMethod == null)
findMethod = "";
if (findContent != null) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=UTF8";
String username = "root";
String password = "请填自己的密码";
Connection con = DriverManager.getConnection(url, username, password);
Statement sql = con.createStatement();
String s = "";
if (findMethod.equals("start")) {
s = "select * from bookform where " + condition + " like'" + findContent + "%'";
} else if (findMethod.equals("end")) {
s = "select * from bookform where " + condition + " like'%" + findContent + "'";
} else if (findMethod.equals("contains")) {
s = "select * from bookform where " + condition + " like'%" + findContent + "%'";
}
ResultSet rs = sql.executeQuery(s);
%>
<font size=4 align=center>查询到的图书</font>
<table border=1>
<tr>
<th>ISBN</th>
<th>图书名称</th>
<th>作者</th>
<th>价格</th>
<th>出版社</th>
<th>出版时间</th>
<th>摘要</th>
</tr>
<%
while(rs.next()){
%>
<tr>
<td><%=rs.getString(1) %></td>
<td><%=rs.getString(2) %></td>
<td><%=rs.getString(3) %></td>
<td><%=rs.getString(4) %></td>
<td><%=rs.getString(5) %></td>
<td><%=rs.getString(6) %></td>
<td><textarea><%=rs.getString(7) %></textarea></td>
</tr>
<%
}
}catch(Exception e){
out.print("没找到驱动");
}
}
%>
</body>
</html>
operation result
Figure 1.1.1 Input data
Figure 1.1.2 The interface after clicking "Submit"
Figure 1.1.3 Compare the database and verify that the output information is correct
2. Database update operation
Still use the database and table in the first experiment. Write a JSP page updateRecord.jsp to change a certain piece of information in the database.
The effect of the updateRecord.jsp page is as follows:
Source code
UpdateRecord.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.lang.*" %>
<%@ page import="java.lang.String.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
%>
<form method="post" action="" name="form1">
输入图书的ISBN号,然后更新该图书的有关信息:
<input type="text" name="bookISBN"/>
<input type="submit" value="提交">
</form>
<br>
<%
String bookISBN = request.getParameter("bookISBN");
String bookName = request.getParameter("bookName");
String bookAuthor = request.getParameter("bookAuthor");
String bookPrice = request.getParameter("bookPrice");
String bookPublish = request.getParameter("bookPublish");
String bookTime = request.getParameter("bookTime");
String bookAbstract = request.getParameter("bookAbstract");
if (bookISBN != null) {
String info = "输入(" + bookISBN + ")的图书信息";
out.println(info);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (ClassNotFoundException e) {
out.print("没有找到驱动");
}
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=UTF8","root","请输入你的密码");
Statement sql = con.createStatement();
String s = "";
s = "select * from bookform where bookISBN=" + bookISBN;
ResultSet rs = sql.executeQuery(s);
%>
<br>
<form method="post" name="form2" action="">
<table border=1>
<%while (rs.next()) { %>
<tr>
<th>图书名称:</th>
<%
String temp=rs.getString(2);
%>
<td><input type="text" value="<%=rs.getString(2)%>" name="bookName"></td>
</tr>
<tr>
<th>图书作者:</th>
<td><input type="text" value="<%=rs.getString(3)%>" name="bookAuthor"></td>
</tr>
<tr>
<th>图书价格:</th>
<td><input type="text" value="<%=rs.getString(4)%>" name="bookPrice"></td>
</tr>
<tr>
<th>出版社:</th>
<td><input type="text" value="<%=rs.getString(5)%>" name="bookPublish"></td>
</tr>
<tr>
<th>出版社时间:</th>
<td><input type="text" value="<%=rs.getString(6)%>" name="bookTime"></td>
</tr>
<tr>
<th>图书摘要:</th>
<td><textarea name="bookAbstract"><%=rs.getString(7)%></textarea></td>
</tr>
<tr>
<td><input type="hidden" name="bookISBN" value="<%=rs.getString(1)%>"></td>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
<%
}
%>
<%
if (bookName != null && bookAuthor != null && bookPrice != null && bookPublish != null && bookTime != null && bookAbstract != null) {
String update1;
Connection con1;
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=UTF8", "root", "请输入你的密码");
update1 = "update bookform set bookName='" + bookName + "'," + "bookAuthor='" + bookAuthor + "'," + "bookPrice="
+ bookPrice + "," + "bookPublish='" + bookPublish + "'," + "bookTime='" + bookTime + "'," + "bookAbstract='" + bookAbstract +
"' where bookISBN=" + bookISBN;
Statement sql1 = con1.createStatement();
int r1 = sql1.executeUpdate(update1);
if (r1 >= 0) {
out.println("修改成功!");
response.setHeader("refresh", "4");
}
}
}
%>
</body>
</html>
operation result
Figure 1.2.1 Initial interface
Figure 1.2.2 The interface after data input and submission
Experiment three JSP and JavaBean
1. The purpose of the experiment
1. Master the storage information of the bean whose effective scope is request;
2. Master the basic information of the bean display computer whose effective scope is the session;
3. Make a simple message board for the bean whose effective scope is application.
2. Experimental content
1. Beans whose valid scope is request
Write a JSP page inputAndShow.jsp and a Javabean named computer, where the computer is created by the PC.class class.
1) The inputAndShow.jsp page provides a form. The form allows the user to enter the brand, model, and production date of the computer. The form submits the information entered by the user to the current page. The current page calls the bean named computer, and uses the data submitted in the form to set the value of the computer's related properties, and then Display the value of each attribute of the computer.
2) The value of each attribute.
3) The written PC.java should have attributes describing the computer brand, model and production date, and provide the corresponding getXxx and setXxx methods to obtain and modify the values of these attributes. The package statement is used in PC.java, and the package name is bean.data. Save the bytecode file PC.class compiled by PC.java to the WEB-INF\classes\bean\data directory of the corresponding project.
Source code
InputAndShow.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<jsp:useBean id="computer" class="bean.data.PC" scope="request" />
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
%>
<html>
<body bgcolor="yellow">
<form action="" method="post">
电脑品牌:<input type="text" name="pinpai"> <br>
电脑型号:<input type="text" name="xinghao"> <br>
生产日期:<input type="text" name="riqi">
<input type="submit" value="提交">
</form>
<jsp:setProperty name="computer" property="*" />
<table border="1">
<tr>
<th>电脑品牌</th>
<th>电脑型号</th>
<th>生产日期</th>
</tr>
<tr>
<th><jsp:getProperty name="computer" property="pinpai" /></th>
<th><jsp:getProperty name="computer" property="xinghao" /></th>
<th><jsp:getProperty name="computer" property="riqi" /></th>
</tr>
</table>
</body>
</html>
PC.java
package bean.data;
public class PC {
String pinpai, xinghao, riqi;
public PC() {
}
public String getPinpai() {
return pinpai;
}
public void setPinpai(String pinpai) {
this.pinpai = pinpai;
}
public String getXinghao() {
return xinghao;
}
public void setXinghao(String xinghao) {
this.xinghao = xinghao;
}
public String getRiqi() {
return riqi;
}
public void setRiqi(String time) {
this.riqi = time;
}
}
operation result
2. Beans whose valid range is session
The requirements of Experiment 2 are similar to those of Experiment 1. The difference from Experiment 1 is that two JSP pages input.jsp and show.jsp are required to be written. Write a Javabean named computer, where computer is created by the PC.class class.
1) The input.jsp page provides a form. The form allows the user to enter the brand, model, and production date of the computer. The form submits the information entered by the user to the current page. The current page calls the bean named computer and uses the data submitted in the form to set the value of the computer's related properties. It is required to provide a hyperlink in input.jsp so that users can click this hyperlink to visit the show.jsp page.
2) show.jsp calls the bean named computer and displays the value of each attribute of the bean.
3) The written PC.java should have attributes describing the computer brand, model and production date, and provide the corresponding getXxx and setXxx methods to obtain and modify the values of these attributes. The package statement is used in PC.java, and the package name is bean.data. Save the bytecode file PC.class compiled by PC.java to the WEB-INF\classes\bean\data directory of the corresponding project.
Source code
input.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="computer" class="bean.data.PC" scope="session" />
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
%>
<html>
<body bgcolor="#adff2f">
<font size="2">
<form action="" method="post">
电脑品牌:<input type="text" name="pinpai"><br>
电脑型号:<input type="text" name="xinghao"><br>
生产日期:<input type="text" name="riqi">
<input type="submit" value="提交">
</form>
<jsp:setProperty name="computer" property="*" />
<A href="show.jsp">访问show.jsp,查看有关信息。</A>
</font>
</body>
</html>
show.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="computer" class="bean.data.PC" scope="session" />
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
%>
<html>
<body bgcolor="#7fffd4">
<table border="1">
<tr>
<th>电脑品牌</th>
<th>电脑型号</th>
<th>生产日期</th>
</tr>
<tr>
<th><jsp:getProperty name="computer" property="pinpai" /></th>
<th><jsp:getProperty name="computer" property="xinghao" /></th>
<th><jsp:getProperty name="computer" property="riqi" /></th>
</tr>
</table>
</body>
</html>
operation result
3. Beans whose valid range is application
It is required to write two JSP pages inputMess.jsp and show.jsp. Write a Javabean named board, where the board is created by the MessBoard.class class.
1) The inputMess.jsp page provides a form. The form allows the user to enter the name of the person who left the message, the title of the message, and the content of the message. The form submits the information entered by the user to the current page. The current page calls the bean named board, and uses the data submitted by the form to set the value of the board's related attributes . It is required to provide a hyperlink in inputMess.jsp so that users can click this hyperlink to visit the show.jsp page.
2) show.jsp calls the bean named board and displays the value of the allMessage property of the bean.
3) The written MessBoard.java should have attributes that describe the name of the person who left the message, the title of the message and the content of the message, and the attribute allMessage that describes all the message information. Save the compiled bytecode file MessBoard.class of MessBoard.java to the WEB-INF\classes\tom\jiafei directory of the corresponding project.
Source code
inputMess.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="board" class="bean.data.MessBoard" scope="application"/>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<body>
<form action="" method="post" name="form">
输入你的名字:<br><input type="text" name="name"><br>
输入你的留言标题:<br><input type="text" name="title"><br>
输入你的留言:<br><textarea name="content" rows="10" cols="36" wrap="soft"></textarea><br>
<input type="submit" value="提交信息" name="submit">
</form>
<jsp:setProperty name="board" property="*"/>
<a href="showMess.jsp">查看留言板</a>
</body>
</html>
showMess.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="board" class="bean.data.MessBoard" scope="application"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<body bgcolor="#6495ed">
<jsp:getProperty name="board" property="allMessage"/>
<a href="inputMess.jsp">我要留言</a>
</body>
</html>
MessBoard.java
package bean.data;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MessBoard {
String name,title,content;
StringBuffer allMessage;
ArrayList<String> savedName,savedTitle,savedContent,savedTime;
private String t;
public MessBoard() {
savedName = new ArrayList<String>();
savedTitle = new ArrayList<String>();
savedContent = new ArrayList<String>();
savedTime = new ArrayList<String>();
}
public void setName(String s) {
this.name = s;
savedName.add(name);
Date time = new Date();
SimpleDateFormat matter = new SimpleDateFormat("yyyy-mm-dd,HH:mm:ss");
String messTime = matter.format(time);
savedTime.add(messTime);
}
public void setTitle(String t) {
this.title = t;
savedTitle.add(title);
}
public void setContent(String c) {
/*try {
byte b[] = c.getBytes("ISO-8859-1");
c = new String(b);
} catch (Exception e) {}*/
this.content = c;
savedContent.add(content);
}
public StringBuffer getAllMessage() {
allMessage = new StringBuffer();
allMessage.append("<table border=1>");
allMessage.append("<tr>");
allMessage.append("<th>留言者姓名</th>");
allMessage.append("<th>留言标题</th>");
allMessage.append("<th>留言内容</th>");
allMessage.append("<th>留言时间</th>");
allMessage.append("</tr>");
for (int k = 0; k < savedName.size(); k++) {
allMessage.append("<tr>");
allMessage.append("<td>");
allMessage.append(savedName.get(k));
allMessage.append("</td>");
allMessage.append("<td>");
allMessage.append(savedTitle.get(k));
allMessage.append("</td>");
allMessage.append("<td>");
allMessage.append("<textarea>");
allMessage.append(savedContent.get(k));
allMessage.append("</textarea>");
allMessage.append("</td>");
allMessage.append("<td>");
allMessage.append(savedTime.get(k));
allMessage.append("</td>");
allMessage.append("</tr>");
}
allMessage.append("</table>");
return allMessage;
}
}
operation result
Figure 2.3.1 Input data
Figure 2.3.2 Redirect after clicking "Submit Information"
Figure 2.3.3 Click "View Message Board" to jump to
Experiment two JSP built-in objects
1. The purpose of the experiment
1. Through this experiment, students will master the basic grammar of JSP built-in objects, and be able to use the grammar of JSP built-in objects such as request, response, and out for dynamic website programming.
2. Experimental content
1. Registration page
Write a user JSP registration page, which contains name (text), password (password), age (select), gender (radio), hobbies (checkbox), self-introduction (textarea), confirmation (submit), reset (reset) Form tag, and request to another JSP page, receive information in this page, and display the information that the user has filled in.
Source code
register.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="information.jsp" method="post">
姓名:<input type="text" name="username"><br>
密码:<input type="password" name="pwd"><br>
年龄:<select size="1" name="age">
<%for (int i = 1; i <= 100; ++i) {%>
<option value="<%=i%>"><%=i%>
</option>
<%} %>
</select><br>〉
性别:<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女<br>
自我介绍:<textarea rows="8" cols="30" name="introduction">
</textarea><br>
<input type="submit" value="提交">
<input type="reset" value="reset">
</form>
</body>
</html>
information.jsp
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="utf-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String strUsername = request.getParameter("username");
String strpwd = request.getParameter("pwd");
String strage = request.getParameter("age");
String strsex = request.getParameter("sex");
String strIntroduction = request.getParameter("introduction");
%>
用户名是:<%=strUsername%><br>
密码是:<%=strpwd%><br>
你的年龄是:<%=strage%><br>
你的性别是:<%=strsex%><br>
你的简介:<%=strIntroduction%><br>
</body>
</html>
operation result
Figure 2.1.1 Input information
Figure 2.1.2 After pressing the "reset" key
Figure 2.1.3 After pressing the "Submit" button
2. Page refresh
Use the response object to control the page refresh every 3 seconds. (Use the java.util.Date function to display the time).
Source code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>现在的时间是:<br>
<%
out.println(""+new Date());
response.setHeader("Refresh", "3");
%>
</body>
</html>
operation result
Figure 2.2.1 Refresh every 3 seconds
3. Page jump
Use the redirect function of the response object to achieve page jumps. In the experiment question 1, if the name of the form is submitted without filling in or empty, the page will be redirected to the registration page.
Source code
register.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="information.jsp" method="post">
姓名:<input type="text" name="username"><br>
密码:<input type="password" name="pwd"><br>
年龄:<select size="1" name="age">
<%for (int i = 1; i <= 100; ++i) {%>
<option value="<%=i%>"><%=i%>
</option>
<%} %>
</select><br>〉
性别:<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女<br>
自我介绍:<textarea rows="8" cols="30" name="introduction">
</textarea><br>
<input type="submit" value="提交">
<input type="reset" value="reset">
</form>
</body>
</html>
information.jsp
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="utf-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String strUsername = request.getParameter("username");
if (strUsername == "") response.sendRedirect("register.jsp");
String strpwd = request.getParameter("pwd");
String strage = request.getParameter("age");
String strsex = request.getParameter("sex");
String strIntroduction = request.getParameter("introduction");
%>
用户名是:<%=strUsername%><br>
密码是:<%=strpwd%><br>
你的年龄是:<%=strage%><br>
你的性别是:<%=strsex%><br>
你的简介:<%=strIntroduction%><br>
</body>
</html>
operation result
Figure 2.3.1 "Submit" without filling in the name
Figure 2.3.2 Redirect to the registration page
Experiment 1 JSP syntax
1. The purpose of the experiment
1. Master the basic knowledge of how to use Tomcat to lay the foundation for future experiments.
2. Master how to use member variables in JSP pages, how to Java programs, and Java expressions;
3. Master how to use include tags to dynamically load files in JSP pages, and use forward to implement page redirection.
2. Experimental content
1. The basic structure of JSP pages
In this experiment, the words entered by the user are sorted in dictionary order. Need to write two JSP pages, named inputWord.jsp and showDictionary.jsp.
1) Specific requirements of inputWord.jsp
This page has a form through which the user enters several words and submits them to the showDictionary.jsp page.
2) Specific requirements of showDictionary.jsp
This page is responsible for sorting words and displaying all sorted words to customers.
(1) The JSP page has the name dictionary and the type is TreeSet member variable.
(2) The JSP page has a public void addWord(String s) method, which adds the character string specified by the parameter s to the member variable dictionary.
The JSP page operates the dictionary in the program piece, that is, displays all the words.
Source code
importWord.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>inputWord</title>
</head>
<body bgcolor=cyan>
<form action="showDictionary.jsp" method=get name=form> 请输入单词(用空格分隔):
<input type="text" name="word"> <br>
<input type="submit" value="发送" name=submit>
</form>
</body>
</html>
showWord.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*" %>
<html>
<head>
<title>showDictionary</title>
</head>
<body bgcolor="yellow">
<%!
TreeSet<String> dictionary = new TreeSet<String>();
public void addWord(String s) {
String word[] = s.split(" ");
for (int i = 0; i < word.length; i++) {
dictionary.add(word[i]);
}
}
%>
<%
String str = request.getParameter("word");
addWord(str);
Iterator<String> te = dictionary.iterator();
while (te.hasNext()) {
String word = te.next();
out.print(" " + word);
}
%>
</body>
</html>
operation result
2. JSP action tag
Write 3 JSP pages: giveFileName.jsp, readFile.jsp and error.jsp.
1) Specific requirements of giveFileName.jsp
The giveFileName.jsp page is required to use the include action tag to dynamically load the readFile.jsp page, and pass the name of a file such as ok.txt to the loaded readFile.jsp page.
2) The specific requirements of readFile.jsp
The readFile.jsp is required to be responsible for reading the file based on the file name passed by the giveFileName.jsp page. If the file does not exist, use the forward action tag to redirect the user to the error.jsp page.
3) Specific requirements of error.jsp
Responsible for displaying error messages.
Source code
giveFileName.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
读取名字是ok.txt的文件:
<jsp:include page="readFile.jsp">
<jsp:param value="D:/ok.txt" name="file"/>
</jsp:include>
</body>
</html>
readFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>
<font size=2 color=blue>
This is readFile.jsp.
</font>
<font size=4>
<%
String s = request.getParameter("file");
File f = new File(s);
if (f.exists()) {
out.println("<br>文件" + s + "的内容:");
FileReader in = new FileReader(f);
BufferedReader Bin = new BufferedReader(in);
String line;
while ((line = Bin.readLine()) != null) {
out.println("<br>" + line);
}
} else {%>
<jsp:forward page="error.jsp">
<jsp:param name="mess" value="File Not Found"/>
</jsp:forward>
<%
}
%>
</font>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body bgcolor=yellow>
<p>
<font size=5 color=red>
This is error.jsp.
</font>
<%
String s=request.getParameter("mess");
out.println("<br>本页面得到的信息:"+s);
%>
</body>
</html>