admin 管理员组文章数量: 887032
2023年12月18日发(作者:怎么做app详细步骤)
Java Web编程技术(第2版)
程序1.1
程序1.2
三星 S5830领取手机节优惠券,立减100元!再送:200元移动手机卡! 派派价:2068元 |
联想(Lenovo)G460AL-ITH 14.0英寸笔记本电脑(i3-370M 2G 500G 512 独显 DVD刻录 摄像头 Win7)特价:3199元! |
程序1.3
body {
font-family:Verdana; font-size:14px; margin:10;}
#container {
margin:0 auto; width:100%;
}
#header {
height:50px; background:#9c6; margin-bottom:5px;
}
#topmenu {
height:30px; background:#c0c0c0; margin-bottom:5px;
}
#middle {
margin-bottom:5px;
}
#leftmenu {
float:left; width:180px; background:#cf9;
}
#content {
float:left; background:#ffa;
}
#footer {
height:60px; background:#9c6;
clear:both;
}
程序1.4
程序1.5
package ;
import ption;
import tException;
import vlet;
import rvlet;
import rvletRequest;
import rvletResponse;
import .*;
@WebServlet(name = "helloServlet", urlPatterns = { "/" })
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("");
n("
n("
Hello,World!
");n("现在的时间是:"+new ());
n("");
n("");
}
}
程序1.6
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Hello,World!
现在的时间是:<%=new () %>
程序2.1
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
程序2.2
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet(name="LoginServlet",urlPatterns={"/"})
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String username = ameter("username");
String password = ameter("password");
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
");if("admin".equals(username)&& "admin".equals(password)){
n("登录成功!欢迎您, "+username);
}else{
n("对不起!您的用户名或密码不正确.");
}
n("");
}
}
程序2.3
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/ClientInfoServlet")
public class ClientInfoServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
");n("
n("
");n("
客户端信息:
");n("
客户主机名 | ");" + oteHost() + " |
客户IP地址 | ");" + oteAddr() + " |
端口 | ");" + otePort() + " |
请求方法 | ");" + hod() + " |
请求协议 | ");" + tocol() + " |
请求URI | ");" + uestURI() + " |
n("");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
程序2.4
package ;
import .*;
import t.*;
import .*;
import ation;
import vlet;
@WebServlet("/ShowHeaders")
public class ShowHeadersServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
");n("
n("服务器收到的请求头信息
");
n(hod()+" "
+uestURI()+" "
+ryString()+" "
+tocol()+"
");
Enumeration
while(eElements()){
String header = (String) ement();
String value = der(header);
n(header+" = "+value+"
");
}
n("");
}
}
程序2.5
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet(name="LoginServlet",urlPatterns={"/"})
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String username = ameter("username");
String password = ameter("password");
// 用户名和口令均为admin,认为登录成功
if(("admin")&&("admin")){
ribute("username", username);
RequestDispatcher rd =
uestDispatcher("/");
d(request, response);
}else{
RequestDispatcher rd =
uestDispatcher("/");
d(request, response);
}
}
}
程序2.6
Your are welcome!
${username}
程序2.7
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
请回答下面的问题:
程序2.8
package ;
import ption;
import riter;
import tException;
import vlet;
import rvlet;
import rvletRequest;
import rvletResponse;
@WebServlet(name="SimpleTestServlet",urlPatterns={"/"})
public class SimpleTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
String quest1 = ameter("quest1");
String quest2 = ameter("quest2");
String[] quest3 = ameterValues("quest3");
String quest4 = ameter("quest4").trim();
int score = 0;
if(quest1!=null && ("1")){
score = score+25; // 答对一道题加25分
}
if(quest2!=null&& ("3")){
score = score+25;
}
if(quest3!=null&&==2&&quest3[0].equals("1")&&
quest3[1].equals("3")){
score = score+25;
}
if(quest4!=null&& (("HttpServlet")||
("rvlet"))){
score = score+25;
}
n("
");n("
n("
");n("你的成绩是:"+score+"分");
n("");
}
}
程序2.9
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
${message}
程序2.10
package ;
import .*;
import t.*;
import .*;
import tion.*;
@WebServlet(name="FileUploadServlet",urlPatterns={"/"})
@MultipartConfig(location="D:",fileSizeThreshold=1024)
public class FileUploadServlet extends HttpServlet{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
// 返回Web应用程序文档根目录
String path = vletContext().getRealPath("/");
String mnumber = ameter("mnumber");
Part p = t("fileName");
String message="";
if(e() >1024*1024){ // 上传的文件不能超过1MB大小
();
message = "文件太大,不能上传!";
}else{
path = path + "member" +mnumber;
File f = new File(path);
if( !()){ // 若目录不存在,则创建目录
();
}
String h = der("content-disposition");
// 得到文件名
String fname = ing(dexOf("")+1, ()-1);
(path + ""+ fname);
message = "文件上传成功!";
}
ribute("message", message);
RequestDispatcher rd = uestDispatcher("/");
d(request, response);
}
}
程序2.11
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet(name="ExcelServlet",urlPatterns={"/"})
public class ExcelServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
//指定页面在传输过程中使用的编码方式
der("Content-Encoding","gb2312");
// 设置响应的内容类型
tentType("application/-excel;charset=gb2312");
PrintWriter out = ter();
n("学号t姓名t性别t年龄t所在系");
n("95001t李勇t男t20t信息");
n("95002t刘晨t女t19t数学");
}
}
程序2.12
package ;
import .*;
import .*;
import DateFormat;
import t.*;
import .*;
import vlet;
@WebServlet("/ShowTimeServlet")
public class ShowTimeServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
tentType("text/html;charset=UTF-8");
der("Refresh","5");
PrintWriter out = ter();
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a HH:mm:ss");
String s = (date); // 对日期对象格式化
n("");
n("
");n("
每5秒钟刷新一次页面
");
n("
现在的时间是:"+s+"
");
n("");
n("");
}
}
程序2.13
package ;
import .*;
import t.*;
import .*;
import tion.*;
@WebServlet(name="SendRedirect",urlPatterns={"/"})
public class RedirectServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException{
String userAgent = der("User-Agent");
// 在请求对象上存储一个属性
ribute("param1", "请求作用域属性");
// 在会话对象上存储一个属性
sion().setAttribute("param2", "会话作用域属性");
if((userAgent!=null)&&(f("MSIE")!=-1)){
direct("");
}else{
direct("localhost:8080/");
}
}
}
程序2.14
package ;
import ption;
import tException;
import vlet;
import .*;
import riter;
@WebServlet("/StatusServlet")
public class StatusServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
String qq = ameter("q");
if(qq==null){
n("没有提供请求参数。");
}else if(("0")){
n(tus()+"
");
n("Hello,Guys!");
}else if(("1")){
tus(_FORBIDDEN);
}else if(("2")){
tus(_UNAUTHORIZED);
}else{
ror(404,"resource cannot founddd!");
}
}
}
程序2.15
xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_3_" version="3.0" metadata-complete="true"> Welcome to Helloweb …
程序2.16
package ;
import .*;
import t.*;
import tion.*;
import .*;
@WebServlet(name="ConfigDemoServlet",
urlPatterns = {"/"},
initParams = {
@WebInitParam(name="email",value="**************"), @WebInitParam(name = "telephone", value = "8899123")
})
public class ConfigDemoServlet extends HttpServlet{
String servletName = null;
ServletConfig config = null;
String email = null;
String telephone = null;
public void init(ServletConfig config) {
= config;
servletName = vletName();
email = tParameter("email");
telephone = tParameter("telephone");
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
");n("
n("Servlet名称:"+servletName+"
");
n("Email地址:"+email+"
");
n("电话:"+telephone);
n("");
}
}
程序3.1
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/")
public class FileDownloadServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// 设置文件的内容类型
tentType("image/gif");
// 设置Content-Disposition响应头,指定文件名
der("Content-Disposition",
"attachment;filename=");
// 获得输出流对象
OutputStream os = putStream();
ServletContext context = getServletContext();
// 返回输入流对象
InputStream is =
ourceAsStream("/files/");
byte[] bytearray = new byte[1024];
int bytesread = 0;
// 从输入流中读取1K字节,然后写到输出流中
while((bytesread = (bytearray)) != -1 ){
// 将数据发送到客户端
(bytearray, 0, bytesread);
}
();
();
}
}
程序3.2
package ;
import .*;
import t.*;
import .*;
import ;
import vlet;
@WebServlet("/ShowSessionServlet")
public class ShowSessionServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
tentType("text/html;charset=utf-8");
// 创建或返回用户会话对象
HttpSession session = sion(true);
String heading = null;
// 从会话对象中检索accessCount属性
Integer accessCount = (Integer)ribute("accessCount");
if(accessCount==null){
accessCount = new Integer(1);
heading = "欢迎您,首次登录该页面!";
}else{
heading = "欢迎您,再次访问该页面!";
accessCount = accessCount+1;
}
// 将accessCount作为属性存储到会话对象中
ribute("accessCount",accessCount);
PrintWriter out = ter();
n("
");n("
n("
n("
"+heading
+"再次访问"+"");
n("
信息 | 值 | n");
会话状态: | "+state+"n"); n(" |
会话ID: | "+()+"n"); n(" |
创建时间: | "); n(""+new Date(ationTime())+"n"); n(" |
最近访问时间: | "); n(""+new Date(tAccessedTime())+"n"); n(" |
最大不活动时间: | "+ InactiveInterval()+"n"); n(" |
Cookie: | "+der("Cookie")+"n"); n(" |
已被访问次数: | "+accessCount+"n"); n(" |
n("
}
}
程序3.3
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/GuessNumberServlet")
public class GuessNumberServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int magic = (int)(()*101);
HttpSession session = sion();
ribute("num",new Integer(magic));
tentType("text/html;charset=utf-8");
PrintWriter out = ter();
n("
");n("我想出一个0到100之间的数,请你猜!");
n("
");n("");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int guess = nt(ameter("guess"));
HttpSession session = sion();
int magic = (Integer)ribute("num");
tentType("text/html;charset=utf-8");
PrintWriter out = ter();
n("
");if(guess==magic){
date(); // 销毁会话对象
n("祝贺你,答对了!");
再猜一次.");
}else if(guess>magic){
n("太大了! 请重猜!");
}else{
n("太小了! 请重猜!");
}
n("
");n("");
}
}
程序3.4
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/SendCookie")
public class SendCookieServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException{
Cookie userCookie = new Cookie("username", "hacker");
Age(60*60*24*7);
kie(userCookie);
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
n("
已向浏览器发送一个Cookie。
");n("");
}
}
程序3.5
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/ReadCookie")
public class ReadCookieServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException{
String cookieName = "username";
String cookieValue = null;
Cookie[] cookies = kies();
if (cookies!=null){
for(int i = 0;i<;i++){
Cookie cookie = cookies[i];
if(e().equals(cookieName))
cookieValue = ue();
}
}
tentType("text/html;charset=utf-8");
PrintWriter out=ter();
n("
n("
从浏览器读回一个Cookie
");n("Cookie名:"+cookieName+"
");
n("Cookie值:"+cookieValue+"
");
n("");
}
}
程序3.6
<%@ page contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
${e}
程序3.7
package ;
import ption;
import t.*;
import .*;
import vlet;
@WebServlet("/CheckUserServlet")
public class CheckUserServlet extends HttpServlet {
String message = null;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
tentType("text/html;charset=utf-8");
String value1 = "",value2="";
Cookie cookie = null;
Cookie[] cookies = kies();
if (cookies!=null){
for(int i = 0;i<;i++){
cookie = cookies[i];
if(e().equals("username"))
value1 = ue();
if(e().equals("password"))
value2 = ue();
}
if(("admin")&&("admin")){
message = "欢迎您!"+value1+"再次登录该页面!";
sion().setAttribute("message", message);
direct("");
}else{
direct("");
}
}else{
direct("");
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
tentType("text/html;charset=utf-8");
String username = ameter("username").trim();
String password = ameter("password").trim();
if(!("admin") || !("admin")){
message = "用户名或口令不正确,请重试!";
sion().setAttribute("message",message);
direct("");
}else{
// 如果用户选中了“自动登录”复选框,向浏览器发送2个Cookie
if((ameter("check")!=null) &&
(ameter("check").equals("check"))){
Cookie nameCookie = new Cookie("username", username);
Cookie pswdCookie = new Cookie("password", password);
Age(60*60);
Age(60*60);
kie(nameCookie);
kie(pswdCookie);
}
message = "你已成功登录!";
sion().setAttribute("message",message);
direct("");
}
}
}
程序4.1
<%@ page contentType="text/html;charset = UTF-8" %>
<%! int count = 0; %>
<%
count++;
%>
该页面已被访问<%=count %> 次。
程序4.2
<%!
int anInt = 3;
boolean aBool = true;
Integer anIntObj = new Integer(3);
Float aFloatObj = new Float(8.6);
%>
<%= 500+380 %>
<%= anInt*3.5/100-500 %>
<%= aBool %>
<%= () %>
<%= aFloatObj %>
程序4.3
<%@page import="" %>
<%@page import="rmat"%>
<%@page contentType="text/html;charset=UTF-8" %>
<%
DateFormat dateFormat = eInstance();
String s = (new Date());
%>
今天的日期是:<%=s%>
程序4.4
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%!
int count = 0;
public void jspInit(){ // 覆盖jspInit()
n("");
}
public void jspDestroy(){ // 覆盖jspDestroy()
n("");
}
%>
<%count++;%>
覆盖jspInit()和jspDestroy()!
该页面被访问<%=count%>次。
程序4.5
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page errorPage="" %>
<%
if (ameter("name")==null){
throw new RuntimeException("没有指定name 请求参数。");
}
%>
Hello, <%=ameter("name")%>
程序4.6
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page isErrorPage="true" %>
页面发生了下面错误:<%=sage()%>
请重试!
程序4.7
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String s = ameter("radius");
if(s==null)
s = "0";
r = ouble(s);
%>
半径为<%= r %>的圆的面积为:<%=area(r)%>
<%!
double r = 0; // 声明一个变量r
double area(double r) { // 声明求圆面积的方法
return r * r * ;
}
%>
程序4.8
<%@ page contentType="text/html;charset=utf-8"%>
<%
for(int n = 2;n < 100;n++){
int i;
for(i = 2;i < n;i++){
if(n % i==0)
break;
}
if(i==n){
%>
<%=n%>
<%
}
}
%>
程序4.9 todayDate_
…
public void _jspService( HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException {
// 其他代码
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
// 创建有关对象的代码
pageContext = _eContext(this, request, response,
null, true, 8192, true);
session = sion();
application = vletContext();
config = vletConfig();
out = ();
// 其他代码
}
程序4.10
<%@ page isErrorPage='true' %>
<%@ page contentType="text/html;charset=utf-8"%>
页面发生了下面错误:<%=ng()%>
程序4.11
<%@ page contentType="text/html;charset=utf-8" %>
My name is Duke. What is yours?
<%! String userName="Duke"; %>
<%@include file="" %>
程序4.12
<%@ page contentType="text/html;charset=utf-8" %>
<% userName=ameter("username");%>
Hello, <%=userName%>!
程序4.13
<%@ page contentType="text/html;charset=UTF-8"%>
My name is Duke. What is yours?
<% String userName = ameter("username");
ribute("username",userName);
%>
程序4.14
<%@ page contentType="text/html;charset = UTF-8" %>
<% String userName = (String)ribute("username");%>
Hello, <%=userName%>!
程序4.15
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
程序4.16
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
程序4.17
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
商品分类
程序4.18
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
圣诞惊喜!买酷派w706,赢取ipad2! | |
三星 S5830领取手机节优惠券,立减100元!再送:200元移动手机卡! 派派价:2068元
|
联想(Lenovo)G460AL-ITH 14.0英寸笔记本电脑(i3-370M 2G 500G 512 独显 DVD刻录 摄像头 Win7)特价:3199元! |
程序4.19
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
关于我们|联系我们|人才招聘|友情链接
Copyright © 2012 派派电子商城有限责任公司,8899123.
程序4.20
package ;
public class Customer{
// 属性声明
private String custName;
private String email;
private String phone;
// 构造方法的定义
public Customer(){}
public Customer(String custName, String email, String phone){
me = custName;
= email;
= phone;
}
// getter方法
public String getCustName(){ return me; }
public String getEmail(){ return ; }
public String getPhone(){ return ; }
// setter方法
public void setCustName(String custName){ me = custName; }
public void setEmail(String email){ = email; }
public void setPhone(String phone){ = phone; }
}
程序4.21
<%@ page contentType="text/html; charset=UTF-8" %>
输入客户信息
程序4.22
package ;
import t.*;
import .*;
import vlet;
@WebServlet("/CustomerServlet")
public class CustomerServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ption,ServletException {
String name = ameter("custName");
String email = ameter("email");
String phone = ameter("phone");
Customer customer = new Customer(name,email,phone);
HttpSession session = sion();
synchronized(session) {
ribute("customer", customer);
}
RequestDispatcher rd =
uestDispatcher("/");
d(request,response);
}
}
程序4.23
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
客户信息如下
客户名: | |
Email地址: | |
电话: |
程序5.1
JSP Expression Language Example
Expression | Value |
${2+5} | ${2+5} |
${4/5} | ${4/5} |
${5 div 6} | ${5 div 6} |
${5 mod 7} | ${5 mod 7} |
${2<3} | ${2 < 3} |
${2gt3} | ${2 gt 3} |
${3.1 le 3.2} | ${3.1 le 3.2} |
${(5>3)?5:3} | ${(5>3)?5:3} |
${empty null} | ${empty null} |
${empty param} | ${empty param} |
程序5.2
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/VariableServlet")
public class VariableServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
ribute("attrib1", new Integer(100));
HttpSession session = sion();
ribute("attrib2", "Java World!");
ServletContext application = getServletContext();
ribute("attrib3",new ());
ribute("attrib4", "请求作用域");
ribute("attrib4", "会话作用域");
ribute("attrib4", "应用作用域");
// 请求转发到JSP页面
RequestDispatcher rd =
uestDispatcher("/");
d(request, response);
}
}
程序5.3
<%@ page contentType="text/html;charset=UTF-8" %>
访问作用域变量
- 属性1: ${attrib1}
- 属性2: ${attrib2}
- 属性3: ${attrib3}
- 属性4: ${attrib4}
程序5.4
package ;
public class Address implements izable {
private String city;
private String street;
private String zipCode;
public Address() { }
public Address(String city,String street,String zipCode) {
=city;
=street;
e=zipCode;
}
// 这里省略了属性的getter方法和setter方法
}
程序5.5
package ;
public class Employee implements izable{
private String empName;
private String email;
private String phone;
private Address address;
public Employee(){}
public Employee(String empName,String email,
String phone,Address address ){
e=empName;
=email;
=phone;
s=address;
}
public void setEmpName(String empName){ e = empName; }
public void setEmail(String email) { = email; }
public void setPhone(String phone) { = phone; }
public void setAddress(Address address){ s=address;}
public String getEmpName(){ return e; }
public String getEmail() { return ; }
public String getPhone() { return ; }
public Address getAddress(){ return address; }
}
程序5.6
package ;
import .*;
import t.*;
import .*;
import s;
import ee;
import vlet;
@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
Address address = new Address("上海市",
"科技路25号","201600");
Employee employee = new Employee("automan",
"**************","8899123",address); ribute("employee", employee);
RequestDispatcher rd =
uestDispatcher("/");
d(request, response);
}
}
程序5.7
<%@ page contentType="text/html;charset = UTF-8" %>
使用EL访问JavaBeans的属性
- 员工名:${e}
- Email地址:${}
- 电话:${}
- 客户地址:
- 城市:${}
- 街道:${}
- 邮编:${e}
- 城市:${}
程序5.8
package ;
import .*;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/CollectServlet")
public class CollectServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
tentType("text/html;charset=UTF-8");
ArrayList
("China");
("England");
("Russia");
HashMap
("China","北京");
("England","伦敦");
("Russia","莫斯科");
ribute("country",country);
ribute("capital",capital);
RequestDispatcher rd =
uestDispatcher("/");
d(request,response);
}
}
程序5.9
<%@ page contentType="text/html;charset=UTF-8" %>
Accessing Collections
- Capital of ${country[0]} is ${capital["China"]}
- Capital of ${country[1]} is ${capital["England"]}
- Capital of ${country[2]} is ${}
程序5.10
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import=".*" %>
<%
Address address = new Address("上海",
"科技路25号","201600");
Employee employee = new Employee("automan",
"**************","8899123",address); ribute("employee", employee);
Cookie cookie = new Cookie("userName","Hacker");
kie(cookie);
%>
EL隐含变量的使用
EL表达式 | 值 |
${} | ${} |
${me} | ${me} |
${} | ${} |
${} | ${} |
${} | ${} |
${} | ${} |
程序6.1
package ;
import .*;
import .*;
import .*;
public class HelloTag implements SimpleTag{
JspContext jspContext = null;
JspTag parent = null;
public void setJspContext(JspContext jspContext){
text = jspContext;
}
public void setParent(JspTag parent){
= parent;
}
public void setJspBody(JspFragment jspBody){
}
public JspTag getParent(){
return parent;
}
public void doTag() throws JspException, IOException{
JspWriter out = ();
("Hello, A simple tag.
");
("现在时间是:"+ new ());
}
}
程序6.2
xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/j2ee /xml/ns/j2ee/web-jsptaglibrary_2_" version="2.1">
程序6.3
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="demo" uri="/sample" %>
Hello Tag Example
程序6.4
package ;
import .*;
import .*;
import .*;
public class RedStarTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException{
JspWriter out = getJspContext().getOut();
("*");
}
}
程序6.5
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/sample" prefix="demo" %>
请输入客户信息,带
程序6.6
package ;
import .*;
import .*;
import .*;
public class WelcomeTag extends SimpleTagSupport {
private String user;
public void setUser(String user) {
= user;
}
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
try{
if (user==null){
("Welcome, Guest!
");
}else{
("Welcome, "+user+"!
");
}
} catch(Exception e){
throw new JspException("Error in ()");}
}
}
程序6.7
<%@ taglib prefix="demo" uri="/sample" %>
程序6.8
package ;
import .*;
import .*;
import .*;
public class BodyTagDemo extends SimpleTagSupport{
public void doTag() throws JspException, IOException{
JspWriter out = getJspContext().getOut();
("输出标签体前
");
// 获得标签体内容并发送到JSP显示
getJspBody().invoke(null);
("
输出标签体后
");
}
}
程序6.9
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="demo" uri="/sample" %>
Tag with body
这是标签体内容.
程序6.10
package ;
import .*;
import .*;
import .*;
public class MarkerTag extends SimpleTagSupport {
private String search = null; // search属性
public void setSearch(String search){
= search;
}
public void doTag() throws JspException, IOException{
JspWriter out = getJspContext().getOut();
StringWriter sw = new StringWriter();
getJspBody().invoke(sw);
String text = ng();
int len = ();
int oldIndex=0, newIndex=0;
while((newIndex = f(search,oldIndex))>=0){
if (newIndex break; } (ing(oldIndex,newIndex)); (""+search+""); oldIndex = newIndex + len; } (ing(oldIndex)); } } 程序6.11 <%@ page contentType="text/html;charset=UTF-8" %> <%@ taglib prefix="demo" uri="/sample" %>
she sells sea shells on the sea shore!
程序6.12
package ;
import .*;
import .*;
import .*;
public class LoopTag extends SimpleTagSupport{
private int count = 0;
public void setCount(int count){
= count;
}
public void doTag() throws JspException,IOException{
JspWriter out = getJspContext().getOut();
StringWriter sw = new StringWriter();
getJspBody().invoke(sw);
String text = ng();
for(int i = 1;i<=count;i++){
("
}
}
}
程序6.13
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="demo" uri="/sample" %>
这是标签体内容!
程序6.14
package ;
// 这里省略了若干导入语句
@WebServlet("/ProductServlet")
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection dbconn = null;
public void init() {
String driver = "";
String dburl = "jdbc:postgresql://127.0.0.1:5432/postgres";
String username = "postgres";
String password = "postgres";
try{
e(driver); // 加载驱动程序
// 创建连接对象
dbconn = nection(
dburl,username,password);
}catch(ClassNotFoundException e1){
}catch(SQLException e2){}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
ArrayList
prodList = new ArrayList
try{
String sql="SELECT * FROM products WHERE prod_id < 'P4'";
PreparedStatement pstmt = eStatement(sql);
ResultSet result = eQuery();
while(()){
Product product = new Product();
d_id(ing("prod_id"));
me(ing("pname"));
ce(ble("price"));
ck(("stock"));
(product);
}
if(!y()){
sion().setAttribute("prodList",prodList);
direct("/helloweb/");
}else{
direct("/helloweb/");
}
}catch(SQLException e){
tackTrace();
}
}
}
程序6.15
package ;
import .*;
import .*;
import .*;
import .*;
import t;
public class ProductTag extends SimpleTagSupport{
private ArrayList
public void setProductList(ArrayList
tList = productList;
}
public void doTag() throws JspException, IOException{
for(Product product:productList){
getJspContext().setAttribute("product", product);
getJspBody().invoke(null);
}
}
}
程序6.16
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="demo" uri="/sample" %>
商品号 | 商品名 | 价格 | 库存量 |
${_id} | ${} | ${} | ${} |
程序6.17
package ;
import .*;
import .*;
import .*;
public class MathTag extends SimpleTagSupport
implements DynamicAttributes{
double num = 0;
String output = "";
public void setNum(double num){
= num;
}
public void setDynamicAttribute(String uri, String localName,
Object value ) throws JspException{
double val = ouble((String)value);
if (localName == "min"){
output = output + "
"
} else if (localName == "max"){
output = output + "
"
} else if (localName == "pow"){
output = output + "
" 次方"+"
}
}
public void doTag() throws JspException, IOException{
getJspContext().getOut().print(output);
}
}
程序6.18
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="demo" uri="/sample" %>
动态属性的使用
程序6.19
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="demo" uri="/sample" %>
Hello!
Good Bye!!
I am Dumb
程序6.20
package ;
import .*;
import .*;
import .*;
public class SwitchTag extends SimpleTagSupport{
private String conditionValue;
private boolean caseFound = false;
public void setConditionValue(String value) {
ionValue =value;
}
public String getConditionValue() {
return conditionValue;
}
public void setCaseFound(boolean caseFound){
und = caseFound;
}
public boolean getCaseFound(){
return caseFound;
}
public void doTag() throws JspException,IOException{
if (("")){
getJspContext().getOut().print
("You did not provide 'action' parameter.");
}else{
getJspBody().invoke(null);
}
}
}
程序6.21
package ;
import .*;
import .*;
import .*;
public class CaseTag extends SimpleTagSupport{
private String caseValue;
public void setCaseValue(String caseValue){
lue = caseValue;
}
public void doTag() throws JspException,IOException{
SwitchTag parent =(SwitchTag) getParent(); // 返回父标签引用
String conditionValue = ditionValue();
if ((caseValue)){
eFound(true);
getJspBody().invoke(null);
}else{
return; // 不执行标签体
}
}
}
程序6.22
package ;
import .*;
import .*;
import .*;
public class DefaultTag extends SimpleTagSupport {
public void doTag() throws JspException,IOException{
SwitchTag parent =(SwitchTag) getParent();
if(eFound()){
return;
}else{
getJspBody().invoke(null);
}
}
}
程序6.23
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="/jsp/jstl/core" %>
OLYMPUS数码相机
程序6.24
<%@ taglib uri="/jsp/jstl/core" prefix="c" %>
${y}*${x}=${x*y}
程序6.25 foreach_
<%@ taglib uri="/jsp/jstl/core" prefix="c" %>
Example of forEach | |||||
---|---|---|---|---|---|
value of x | t | ||||
${x} | ${} | ${t} | ${} | ${} | ${} |
程序6.26
package ;
import ption;
import tDispatcher;
import tException;
import vlet;
import rvlet;
import rvletRequest;
import rvletResponse;
import ;
import ist;
import ;
@WebServlet("/BooksServlet")
public class BooksServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
List
Book book1 = new Book("978-7-302-23059-5","Java语言程序设计",45.00);
Book book2 = new Book("978-7-302-21540-0","Java Web编程技术",39.00);
Book book3 = new Book("978-7-302-24130-0","C #入门经典",99.80);
(book1);
(book2);
(book3);
ribute("books", books);
RequestDispatcher rd = uestDispatcher("/");
d(request, response);
}
}
程序6.27
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import=".*," %>
<%@ taglib uri="/jsp/jstl/core" prefix="c" %>
书号 | 书名 | 价格 |
${} | ${} | ${} |
程序6.28
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/jsp/jstl/core" prefix="c" %>
value="白日依山尽,黄河入海流,欲穷千里目,更上一层楼" />
登鹳雀楼 王之涣
${line}
程序6.29
<%@ taglib uri="/jsp/jstl/core" prefix="c" %>
<%@ page contentType="text/html;charset=UTF-8" %>
You are welcome to my home page!
程序6.30
<%@ page contentType="text/html; charset=UTF-8"%>
关于我们|联系我们|人才招聘|友情链接
Copyright © 2012 派派电子商城有限责任公司,8899123.
E-mail Address:${}
程序7.1
package ;
import izable;
public class Product implements Serializable {
private String prod_id;
private String pname;
private double price;
private int stock;
public Product() { }
public Product(String prod_id, String pname,
double price, int stock) {
_id = prod_id;
= pname;
= price;
= stock;
}
public String getProd_id() {
return prod_id;
}
public void setProd_id(String prod_id) {
_id = prod_id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
= pname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
= price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
= stock;
}
}
程序7.2
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
程序7.3
package ;
import .*;
import .*;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/")
public class QueryProductServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
Connection dbconn = null;
public void init() {
String driver = "";
String dburl = "jdbc:postgresql://127.0.0.1:5432/postgres";
String username = "postgres";
String password = "postgres";
try{
e(driver); // 加载驱动程序
// 创建连接对象
dbconn = nection(
dburl,username,password);
}catch(ClassNotFoundException e1){
n(e1);
}catch(SQLException e2){}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
String productid = ameter("productid");
try{
String sql="SELECT * FROM products WHERE prod_id = ?";
PreparedStatement pstmt = eStatement(sql);
ing(1,productid);
ResultSet rst = eQuery();
if(()){
Product product = new Product();
d_id(ing("prod_id"));
me(ing("pname"));
ce(ble("price"));
ck(("stock"));
sion().setAttribute("product", product);
direct("/helloweb/");
}else{
direct("/helloweb/");
}
}catch(SQLException e){
tackTrace();
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
ArrayList
productList = new ArrayList
try{
String sql="SELECT * FROM products";
PreparedStatement pstmt = eStatement(sql);
ResultSet result = eQuery();
while(()){
Product product = new Product();
d_id(ing("prod_id"));
me(ing("pname"));
ce(ble("price"));
ck(("stock"));
(product);
}
if(!y()){
sion().setAttribute("productList",productList);
direct("/helloweb/");
}else{
direct("/helloweb/");
}
}catch(SQLException e){
tackTrace();
}
}
public void destroy(){
try {
();
}catch(Exception e){
tackTrace();
}
}
}
程序7.4
<%@ page contentType="text/html; charset=utf-8" %>
scope="session">
商品号: | |
商品名: | |
价格: | |
库存量: |
程序7.5
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import=".*,t" %>
商品号 | 商品名 | 价格 | 数量 |
<%=d_id() %> | <%=me() %> | <%=ce() %> | <%=ck() %> |
程序7.6
<%@ page contentType="text/html; charset=UTF-8" %>
该商品不存在。返回
程序7.7
name="jdbc/sampleDS" type="urce" maxActive="4" maxIdle="2" username="paipaistore" maxWait="5000" driverClassName="" password="paipaistore" url="jdbc:postgresql://localhost:5432/paipaistore"/> 程序7.8 package ; import .*; import .*; import urce; import t.*; import vlet; import .*; import t; import .*; import .*; @WebServlet("/") public class ProductQueryServlet extends HttpServlet { private static final long serialVersionUID = 1L; DataSource dataSource; public void init() { try { Context context = new InitialContext(); dataSource = (DataSource)("java:comp/env/jdbc/sampleDS"); }catch(NamingException ne){ n("Exception:"+ne); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection dbconn = nection(); // 代码同程序7.3的doPost() } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection dbconn = nection(); // 代码同程序7.3的doGet() } } 程序7.9 global = "jdbc/paipaistore" name = "jdbc/sampleDS" type = "urce"/> 程序7.10 package ; import izable; public class Customer implements Serializable{ private String cust_id; private String cname; private String email; private double balance; public String getCust_id() { return cust_id; } public void setCust_id(String cust_id) { _id = cust_id; } public String getCname() { return cname; } public void setCname(String cname) { = cname; } public String getEmail() { return email; } public void setEmail(String email) { = email; } public double getBalance() { return balance; } public void setBalance(double balance) { e = balance; } } 程序7.11 package ; import .*; import urce; import .*; public class BaseDao { DataSource dataSource; // 在构造方法中返回数据源对象 public BaseDao () { try { Context context = new InitialContext(); dataSource = (DataSource)("java:comp/env/jdbc/sampleDS"); }catch(NamingException ne){ n("Exception:"+ne); } } // 返回一个连接对象 public Connection getConnection()throws Exception{ return nection(); } } 程序7.12 package ; import .*; import ist; import er; public class CustomerDao extends BaseDao{ // 插入一条客户记录 public boolean addCustomer(Customer customer){ String sql = "INSERT INTO customers" + "(cust_id,cname,email,balance)VALUES(?,?,?,?)"; try( Connection conn = nection(); PreparedStatement pstmt = eStatement(sql)) { ing(1,t_id()); ing(2,me()); ing(3,il()); ble(4,ance()); eUpdate(); return true; }catch(SQLException se){ tackTrace(); return false; } } // 按姓名检索客户记录 public Customer findByName(String cname){ String sql = "SELECT cust_id,cname,email,balance" + " FROM customers WHERE cname=?"; Customer customer = new Customer(); try( Connection conn = nection(); PreparedStatement pstmt = eStatement(sql)){ ing(1,cname); try(ResultSet rst = eQuery()){ if(()){ t_id(ing("cust_id")); me(ing("cname")); il(ing("email")); ance(ble("balance")); } } }catch(SQLException se){ return null; } return customer; } // 查询所有客户信息 public ArrayList Customer customer = new Customer(); ArrayList String sql = "SELECT * FROM customers"; try( Connection conn = nection(); PreparedStatement pstmt = eStatement(sql); ResultSet rst = eQuery()){ while(()){ t_id(ing("cust_id")); me(ing("cname")); il(ing("email")); ance(ble("balance")); (customer); } return custList; }catch(SQLException e){ tackTrace(); return null; } } } 程序7.13 <%@ page contentType="text/html; charset=UTF-8" %>
${result}
请输入一条客户记录
程序7.14
package ;
import .*;
import t.*;
import .*;
import er;
import erDao;
import vlet;
@WebServlet("/")
public class AddCustomerServlet extends HttpServlet{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
CustomerDao dao = new CustomerDao();
Customer customer = new Customer();
String message = null;
try{
t_id(ameter("cust_id"));
// 将传递来的字符串重新使用utf-8编码,以免产生乱码
me(new String(ameter("cname")
.getBytes("iso-8859-1"),"UTF-8"));
il(new String(ameter("email")
.getBytes("iso-8859-1"),"UTF-8"));
ance(
ouble(ameter("balance")));
boolean success = tomer(customer);
if(success){
message = "
}else{
message = "
}
}catch(Exception e){
message = "
}
ribute("result", message);
RequestDispatcher rd =
getServletContext().getRequestDispatcher("/");
d (request,response);
}
}
程序8.1
package er;
import .*;
import ;
import t.*;
import .*;
import tener;
@WebListener // 使用注解注册监听器
public class MyContextListener implements ServletContextListener,
ServletContextAttributeListener{
private ServletContext context = null;
public void contextInitialized(ServletContextEvent sce){
Context ctx = null;
DataSource dataSource = null;
context = vletContext();
try{
if(ctx == null){
ctx = new InitialContext();
}
dataSource = (DataSource)("java:comp/env/jdbc/sampleDS");
}catch(NamingException ne){
("Exception:"+ne);
}
ribute("dataSource",dataSource); // 添加属性
("应用程序已启动:"+new Date());
}
public void contextDestroyed(ServletContextEvent sce){
context = vletContext();
Attribute("dataSource");
("应用程序已关闭:"+new Date());
}
public void attributeAdded(ServletContextAttributeEvent sce){
context = vletContext();
("添加一个属性:"+e()+":"+ue());
}
public void attributeRemoved(ServletContextAttributeEvent sce){
context = vletContext();
("删除一个属性:"+e()+":"+ue());
}
public void attributeReplaced(ServletContextAttributeEvent sce){
context = vletContext();
("替换一个属性:"+e()+":"+ue());
}
}
程序8.2
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import=".*,.*" %>
<%
DataSource dataSource =
(DataSource)ribute("dataSource");
Connection conn = nection();
Statement stmt = Statement();
ResultSet rst = eQuery(
"SELECT * FROM products WHERE prod_id>'P2'");
%>
商品表中信息
商品号 | 商品名 | 价格 | 库存 |
<%= ing(1) %> | <%= ing(2) %> | <%= ble(3) %> | <%= (4) %> |
程序8.3
package er;
import rvletRequest;
import tRequestEvent;
import tRequestListener;
import tener;
@WebListener
public class MyRequestListener
implements ServletRequestListener{
private int count = 0;
public void requestInitialized(ServletRequestEvent re){
HttpServletRequest request=
(HttpServletRequest)vletRequest();
if(uestURI().endsWith("")){
count++;
vletContext().setAttribute("count",new Integer(count));
}
}
public void requestDestroyed(ServletRequestEvent re){
}
}
程序8.4
<%@ page contentType="text/html;charset=UTF-8" %>
欢迎您,您的IP地址是${Addr}
自应用程序启动以来,该页面被访问了
${}
次
程序8.5
package er;
import t.*;
import .*;
import ist;
import tener;
@WebListener
public class MySessionListener implements HttpSessionListener{
private ServletContext context = null;
public void sessionCreated(HttpSessionEvent se){
HttpSession session = sion();
context = vletContext();
ArrayList
ribute("sessionList");
if(sessionList==null){
sessionList = new ArrayList
ribute("sessionList",sessionList);
}else{
(session);
}
("创建一个会话:"+());
}
public void sessionDestroyed(HttpSessionEvent se){
HttpSession session = sion();
context = vletContext();
ArrayList
ribute("sessionList");
(session);
("销毁一个会话:"+());
}
}
程序8.6
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import=".* " %>
<%@ taglib prefix="c" uri="/jsp/jstl/core" %>
发表评论