admin管理员组文章数量:1568431
2024年7月3日发(作者:)
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" %>
程序8.7
package er;
import .*;
public class User implements HttpSessionBindingListener{
public String username = "";
public String password = "";
public User(){}
public User(String username,String password){
me = username;
rd = password;
}
public void valueBound(HttpSessionBindingEvent e){
HttpSession session = sion();
vletContext().log("用户名:"+username
+", 口令:"+password+" 登录系统.");
}
public void valueUnbound(HttpSessionBindingEvent e){
HttpSession session = sion();
vletContext().log("用户名:"+username
+"口令:"+password+" 退出系统.");
}
}
程序8.8
package ;
import t.*;
import .*;
import .*;
import .*;
import ;
import vlet;
@WebServlet("/")
public class LoginServlet extends HttpServlet{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
String username = ameter("username");
String password = ameter("password");
DataSource dataSource =
(DataSource)getServletContext().getAttribute("dataSource");
try{
Connection conn = nection();
String sql = "SELECT * FROM users WHERE username=? AND password=?";
PreparedStatement pstmt = eStatement(sql);
ing(1,username);
ing(2,password);
ResultSet rst = eQuery();
boolean valid = ();
if(valid){
User validuser = new User(username,password);
sion().setAttribute("user", validuser);
n("欢迎您,"+username);
}else{
direct("");
}
}catch(Exception e){
log("产生异常:" + sage());
}
}
}
程序8.9
package ;
import ption;
import t.*;
import ter;
import rvletRequest;
@WebFilter(filterName = "logFilter", urlPatterns = { "/*" })
public class LogFilter implements Filter {
private FilterConfig config;
// 实现初始化方法
public void init(FilterConfig fConfig) throws ServletException {
= fConfig;
}
// 实现过滤方法
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 获得应用上下文对象
ServletContext context = vletContext();
// 返回请求对象
HttpServletRequest hrequest = (HttpServletRequest)request;
// 记录开始过滤时间
long start = tTimeMillis();
n("用户地址:"+oteAddr());
n("请求的资源:"+uestURI());
("请求的资源:"+uestURI());
("用户地址:"+oteAddr());
// 请求转到下一资源或下一过滤器
er(request, response);
// 记录返回到过滤器时间
long end = tTimeMillis();
n("请求的总时间:"+(end - start)+"毫秒");
("请求的总时间:"+(end - start)+"毫秒");
}
// 实现销毁方法
public void destroy() {
= null;
}
}
程序8.10
package ;
import ption;
import t.*;
import ter;
import tParam;
import .*;
@WebFilter(
filterName = "authorityFilter",
urlPatterns = { "/*" },
initParams = {
@WebInitParam(name = "encoding", value = "UTF-8"),
@WebInitParam(name = "loginPage", value = ""),
@WebInitParam(name = "proLogin", value = "")
})
public class AuthorityFilter implements Filter {
private FilterConfig config;
// 实现初始化方法
public void init(FilterConfig fConfig) throws ServletException {
config = fConfig;
}
// 实现过滤方法
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 获取该过滤器的配置参数
String encoding = tParameter("encoding");
String loginPage = tParameter("loginPage");
String proLogin = tParameter("proLogin");
// 设置请求request的编码字符集
racterEncoding(encoding);
HttpServletRequest hrequest = (HttpServletRequest)request;
HttpSession session = sion(true);
// 获得客户请求的页面
String requestPath = vletPath();
// 如果session作用域的user为null,表明没有登录
// 即用户请求的既不是登录页面,也不是处理登录的页面
if(ribute("user")==null
&&!th(loginPage)
&&!th(proLogin)){
//转发到登录页面
ribute("message","您还没有登录!");
uestDispatcher(loginPage)
.forward(request, response);
}else{
er(request, response);
}
}
// 实现销毁方法
public void destroy() {
config = null;
}
}
程序8.11
package ;
import t.*;
import .*;
import .*;
import tion.*;
@WebServlet(
name = "calculatorServlet",
urlPatterns = { "/" },
initParams = {
@WebInitParam(name = "sleepTime", value = "2000")
})
public class CalculatorServlet extends HttpServlet{
private int result;
private int sleepTime;
public void init(){
String sleep_time = getInitParameter("sleepTime");
sleepTime = getNumber(sleep_time);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException {
racterEncoding("UTF-8");
String value1 = ameter("value1");
int v1 = getNumber(value1);
String value2 = ameter("value2");
int v2 = getNumber(value2);
String op = ameter("submit");
if(("相加")){
result = v1 + v2;
}else{
result = v1 - v2;
}
try{
(sleepTime); // 当前线程睡眠指定时间
}catch(InterruptedException e){
log("Exception during sleeping.");
}
try{
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
");n(v1 +"与"+ v2 + op +"结果是"+result);
n("");
}catch(Exception e){
log("Error writing output.");
}
}
private int getNumber(String s){
int result = 0;
try{
result = nt(s);
}catch(NumberFormatException e){
log("Error Parseing "+s);
}
return result;
}
}
程序8.12
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
程序8.13
package ;
import ption;
import riter;
import ontext;
import tException;
import vlet;
import rvlet;
import rvletRequest;
import rvletResponse;
@WebServlet(urlPatterns="/asyncDemo",asyncSupported=true)
public class AsyncDemoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
n("
");n("进入Servlet的时间:"+new ()+".
");
();
AsyncContext actx = sync();
eout(30*1000); // 设置异步调用的超时时长30秒
// 启动异步调用的线程
(new Executor(actx));
n("结束Servlet的时间:"+new ()+".");
();
}
}
程序8.14
package ;
import t.*;
import .*;
import ;
public class Executor implements Runnable{
private AsyncContext actx=null;
public Executor(AsyncContext actx){
=actx;
}
// 实现线程体的run()
public void run(){
try{
// 等待10秒钟,以模拟业务方法的执行
(10000);
PrintWriter out=ponse().getWriter();
n("业务处理完毕的时间:"+new Date()+".");
();
te(); // 结束异步线程
}catch(Exception e){
tackTrace();
}
}
}
程序8.15
package er;
import istener;
import vent;
import tion.*;
import ption;
public class MyAsyncListener implements AsyncListener{
@Override
public void onStartAsync(AsyncEvent event)throws IOException{
n("异步调用开始。");
}
public void onComplete(AsyncEvent event)throws IOException {
n("异步调用完成。");
}
public void onError(AsyncEvent event)throws IOException {
n("异步调用出错。");
}
public void onTimeout(AsyncEvent event)throws IOException {
n("异步调用超时。");
}
}
程序8.16
package ;
import ption;
import ontext;
import tException;
import vlet;
import rvlet;
import rvletRequest;
import rvletResponse;
import cListener;
@WebServlet(name="AsyncListenerServlet",
urlPatterns={"/asyncListener"},
asyncSupported=true)
public class AsyncListenerServlet extends HttpServlet {
private static final long serialVersionUID = 222L;
@Override
protected void doGet(final HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
final AsyncContext asyncContext = sync();
eout(5000);
// 注册监听器
tener(new MyAsyncListener());
n("主线程输出...");
n("主线程名:"+tThread().getName());
(new Runnable(){
@Override
public void run(){
try{
(3000); // 睡眠3秒钟
}catch(InterruptedException e){ }
String greeting = "Hi from worker thread";
n("异步线程输出...");
n("异步线程名:"
+tThread().getName());
ribute("greeting", greeting);
ch("/");
}
});
}
}
程序9.1
程序9.2
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet("/")
public class AccountServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
");n("
n("");
n("
");String name = oteUser();
n("欢迎您, "+name+"!");
n("
能够访问该页面,说明你是管理员(manager)。");
n("");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
n("
");n("
n("");
n("
");n("欢迎你!
");
n("HTTP POST请求对所有用户开放!");
n("");
}
}
程序9.3
<%@ page contentType="text/html;charset=UTF-8" %>
请您输入用户名和口令
程序9.4
<%@ page contentType="text/html;charset=UTF-8" %>
对不起,用户名或口令不正确!
请返回重新登录:返回
程序9.5
package ;
import .*;
import t.*;
import .*;
import 64Encoder;
import 64Decoder;
public class AuthorizationServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException {
String authorization = der("Authorization");
if (authorization == null){
askForPassword(response);
} else {
// 从Authorization请求头中解析出用户名和口令
String userInfo = ing(6).trim();
BASE64Decoder decoder = new BASE64Decoder();
String nameAndPassword = new String(Buffer(userInfo));
int index = f(":");
String username = ing(0, index);
String password = ing(index+1);
if (InRole("director")) {
showDirectorPage(request, response);
}else if (InRole("employee")){
showEmployeePage(request, response);
}
}
}
private void askForPassword(HttpServletResponse response)
throws IOException {
// 向客户发送401响应
der("WWW-Authenticate",
"BASIC realm="Programatic Test"");
ror(_UNAUTHORIZED);
}
private void showDirectorPage(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
String username = oteUser();
n("
");n("
n("
");n("Welcome, "+username+"!");
n("
这是为主管(director)产生的页面.");
n("
Authorization:"+
der("Authorization")+"");
n("");
}
private void showEmployeePage(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
tentType("text/html;charset=UTF-8");
PrintWriter out = ter();
String username = oteUser();
n("
");n("
n("
");n("Welcome, "+username+"!");
n("
这是为职员(employee)产生的页面.");
n("
Authorization:"+
der("Authorization")+"");
n("");
}
}
程序9.6
xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_3_" version="3.0" metadata-complete="true">
程序10.1
程序10.2
程序10.3
程序10.4
学号 | 姓名 | 性别 | 年龄 |
20120101 | Li Ming | 男 | 19 |
20120102 | Wang Xiaoming | 女 | 20 |
20120103 | Liu Hao | 男 | 18 |
程序10.5
XML 文档解析
程序10.6
查看图书或杂志
程序10.7
Ajax数据验证示例
用户名:
程序10.8
package ;
import .*;
import t.*;
import .*;
import vlet;
@WebServlet(name = "validationServlet", urlPatterns = { "/" })
public class ValidationServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
tentType("text/xml;charset=UTF-8");
der("Cache-Control","no-cache");
String username = ameter("username");
String message = "用户名可以使用!";
PrintWriter out = ter();
//这里的验证非常简单,实际应用可与数据库中用户名比较
if(("hacker")){
message = "用户名已被占用!";
}
n("
n("
n("");
}
}
程序10.9
请选择入学年份和班级
程序10.10
package ;
import .*;
import ist;
import ;
import t.*;
import .*;
import vlet;
@WebServlet(name ="refreshServlet", urlPatterns={"/" })
public class RefreshNameServlet extends HttpServlet {
private List
new ArrayList
public void init() throws ServletException {
(new Student(2012, "class1", "李小明"));
(new Student(2012, "class1", "张冬玫"));
(new Student(2012, "class2", "赵亮"));
(new Student(2012, "class2", "王强"));
(new Student(2012, "class2", "孙文"));
(new Student(2013, "class1", "Micheal Jordon"));
(new Student(2013, "class1", "Henry Smith"));
(new Student(2013, "class2", "Joeory Bush"));
(new Student(2013, "class2", "Karta"));
(new Student(2013, "class2", "Luews"));
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int syear = nt(ameter("syear"));
String sclass = ameter("sclass");
StringBuffer results = new StringBuffer("
for(Student stud:students) {
if(syear == && (sclass)){
("
();
("");
}
}
("");
tentType("text/xml;charset=UTF-8");
ter().println(ng());
}
private class Student{ // 定义内部类
private int syear; // 入学年份
private String sclass; // 班级
private String sname; // 姓名
public Student(int syear, String sclass, String sname) {
= syear;
= sclass;
= sname;
}
}
}
程序10.11
Ajax工具提示示例
onmouseout="clearData();"> | onmouseout="clearData();"> | onmouseout="clearData();"> |
程序10.12
package ;
import .*;
import p;
import ;
import t.*;
import .*;
import vlet;
@WebServlet(name ="tooltipServlet", urlPatterns={"/" })
public class ToolTipServlet extends HttpServlet {
private Map
public void init(ServletConfig config) throws ServletException {
("dog1", "It is a dog!");
("dog2", "It is a lovely dog!");
("dog3", "It is a very lovely dog!");
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String key = ameter("key");
String data = (key);
PrintWriter out = ter();
tentType("text/xml;charset=UTF-8");
der("Cache-Control", "no-cache");
n("
n("
n("");
();
}
}
程序10.13
请输入客户信息
客户信息如下:
程序10.14
package ;
import .*;
import ;
import t.*;
import .*;
import vlet;
@WebServlet(name ="customerList", urlPatterns={"/" })
public class CustomerListServlet extends HttpServlet {
protected void addCustomer(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// 可将对象存储到数据库中
String uniqueID = storeCustomer();
// 创建响应XML
StringBuffer xml = new StringBuffer("
(uniqueID);
("");
("
("");
// 向浏览器发送响应
sendResponse(response, ng());
}
protected void deleteCustomer(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
String id = ameter("id");
// 可将客户从数据库中删除
// 创建响应XML
StringBuffer xml = new StringBuffer("
("
("");
// 向浏览器发送响应
sendResponse(response, ng());
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String action = ameter("action");
if(("add")) {
addCustomer(request, response);
}
else if(("delete")) {
deleteCustomer(request, response);
}
}
private String storeCustomer() {
// 这里可将客户对象保存到数据库中
String uniqueID = "";
Random randomizer = new Random(tTimeMillis());
for(int i = 0; i < 8; i++) {
uniqueID += t(9);
}
return uniqueID;
}
private void sendResponse(HttpServletResponse response,
String responseText)
throws IOException {
tentType("text/xml");
ter().println(responseText);
}
}
程序11.1
package ate;
public class Student {
private Long id;
private long studentNo;
private String studentName;
private int sage;
private String major;
public Student() { }
public Student(long studentNo, String studentName, int sage,
String major){
tNo = studentNo;
tName = studentName;
= sage;
= major;
}
public Long getId(){
return id;
}
public void setId(Long id){
= id;
}
public long getStudentNo(){
return studentNo;
}
public void setStudentNo(long studentNo){
tNo = studentNo;
}
public String getStudentName(){
return studentName;
}
public void setStudentName(String studentName){
tName = studentName;
}
public int getSage(){
return sage;
}
public void setSage(int sage){
= sage;
}
public String getMajor(){
return major;
}
public void setMajor(String major){
= major;
}
}
程序11.2
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"/">
程序11.3
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"/dtd/">
jdbc:postgresql://localhost:5432/postgres
eSQLDialect
eProvider
程序11.4
import uration;
import eRegistry;
import eRegistryBuilder;
import nFactory;
import n;
import ction;
import t;
public class Main {
public static void main(String[] args) {
// 加载配置文件
Configuration configuration = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(perties())
.buildServiceRegistry();
// 创建会话工厂对象
SessionFactory factory =
essionFactory(serviceRegistry);
// 创建会话对象
Session session = ssion();
// 创建一个事务对象
Transaction tx = ransaction();
Student student = new Student();
dentNo(20120108);
dentName("王小明");
e(20);
or("计算机科学");
(student); // 将student对象持久化到数据表中
n("插入学生成功!");
// 从数据库中读取一个对象
Student stud = (Student)(, new Long(1));
n(dentName() + " " + e());
(); // 提交事务
();
();
}
}
程序11.5
package ;
import ateException;
import n;
import nFactory;
import uration;
import eRegistry;
import eRegistryBuilder;
public class HibernateUtil {
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;
static{
try{
Configuration configuration = new Configuration().configure();
serviceRegistry = new ServiceRegistryBuilder()
.applySettings(perties())
.buildServiceRegistry();
factory = essionFactory(serviceRegistry);
}catch(HibernateException e){
tackTrace();
}
}
// 返回会话工厂对象
public static SessionFactory getSessionFactory() {
return factory;
}
// 返回一个会话对象
public static Session getSession() {
Session session = null;
if(factory !=null)
session = ssion();
return session;
}
// 关闭指定的会话对象
public static void closeSession(Session session){
if(session !=null){
if(())
();
}
}
}
程序11.6
package ;
import n;
import ction;
import t;
import ateUtil;
public class StudentDemo{
public static void main(String[] args) {
try{
Session session = sion();
Transaction tx = ransaction();
Student student = (Student)(, new Long(1));
dentName("王晓明");
(student); // 更新修改后的记录
(); // 提交事务
();
}catch(HibernateException he){
tackTrace();
}
}
}
程序12.1
package ;
import Support;
public class HelloUserAction extends ActionSupport {
private String message; // 动作属性
public String getMessage() {
return message;
}
public void setMessage(String message) {
e = message;
}
@Override
public String execute() throws Exception {
setMessage("Hello Struts User");
return SUCCESS;
}
}
程序12.2
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
Welcome To Struts 2!
程序12.3
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
程序12.4
package ;
public class User{
private Long id;
private String username;
private String password;
private int age;
private String email;
// 这里省略了属性的getter方法和setter方法
@Override
public String toString(){
return "用户名: " + getUsername() +"口令: " + getPassword()
+ "年龄: " + getAge() +" Email:" + getEmail();
}
}
程序12.5
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"/">
程序12.6
package ;
import ;
import ateUtil;
import Support;
import n;
import ction;
import ;
import ;
public class RegisterAction extends ActionSupport {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
= user;
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
public String register() throws Exception {
try{
Session session = sion();
Transaction tx = ransaction();
(user); // 将user对象持久化到数据表中
();
return SUCCESS;
}catch(Exception e){
tackTrace();
sion().close();
return ERROR;
}
}
public String login() throws Exception {
try{
Session session = sion();
Transaction tx = ransaction();
Query query = Query(
"from User where username=:uname");
ameter("uname", rname());
List list = ();
();
if(()==1){
return SUCCESS;
}else
return ERROR;
}catch(Exception e){
tackTrace();
sion().close();
return ERROR;
}
}
}
程序12.7
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
注册一个新用户
程序12.8
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
请输入用户名和密码:
tooltip="输入用户名" labelposition="left" /> tooltip="输入密码" labelposition="left" /> 程序12.9 <%@ taglib prefix="s" uri="/struts-tags" %> <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
注册成功!
程序12.10
<%@ page contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
欢迎登录本系统
程序12.11
package ;
import ;
public class SampleAction {
private String message;
private User user = new User();
{
rname("王小明"); // 初始化块
}
public String execute() {
setMessage("世界,你好!");
return "success";
}
public String getMessage(){
return message;
}
public void setMessage(String message){
e = message;
}
public User getUser() {
return user;
}
public void setUser(User user) {
= user;
}
}
程序12.12
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
OGNL 示例!
[0].me:
me:
message:
getMessage():
程序12.13
package ;
public class ConverterBean{
private double celcius;
private double fahrenheit;
public double getCelcius(){
return (fahrenheit - 32) * 5 / 9;
}
public void setCelcius(double celcius){
s = celcius;
}
public double getFahrenheit(){
return celcius * 9 / 5 + 32;
}
public void setFahrenheit(double fahrenheit){
heit = fahrenheit;
}
}
程序12.14
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
Bean Tag Example
37°C=
程序12.15
package ;
import Support;
import .*;
public class IteratorAction extends ActionSupport{
private List
private Map
public String execute()throws Exception{
fruit = new ArrayList
("苹果");
("橘子");
("香蕉");
("草莓");
country = new HashMap
("China", "北京");
("USA", "纽约");
("England", "伦敦");
("Russia", "莫斯科");
return SUCCESS;
}
public List
return fruit;
}
public Map
return country;
}
}
程序12.16
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
Iterator Tag Example!
国家名 | 首都 |
---|---|
程序12.17
package ;
import Support;
import .*;
public class SortTagAction extends ActionSupport{
private List
private Comparator
public String execute()throws Exception{
students = new ArrayList
(new Student(333,"张大海"));
(new Student(111,"李小雨"));
(new Student(888,"王天琼"));
return SUCCESS;
}
public Comparator
// 一个匿名内部类,实现Comparator接口
return new Comparator
// 实现Comparator接口必须实现compare()
public int compare(Student o1,Student o2){
return - ;
}
};
}
public List
return students;
}
public void setStudents(List
ts = students;
}
class Student{ // 内部类定义
private int id;
private String name;
Student(int id,String name){
= id;
= name;
}
public String toString(){
return id + " " + name;
}
}
}
程序12.18
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
comparator="myComparator" >
程序12.19
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"/xwork/">
true
true
6
14
16
60
程序12.20
<%@ taglib uri="/tags-tiles" prefix="tiles"%>
"/TR/html4/">
程序12.21
#header {
border:1px solid blue;
background-position:50% 0;
background-repeat:repeat no-repeat;
height:100px;
padding: 10px;
margin:15px;
width:780px;
}
#mainContent {
background-color:white;
margin:0px;
overflow-x:hidden;
overflow-y:hidden;
padding-left:10px;
padding-right:10px;
position:relative;
width:780px;
}
#sidebar {
border:1px solid blue;
display:inline;
float:left;
line-height:1.5em;
margin:15px;
padding:5px;
width:200px;
height:150px;
min-height: 500px;
}
#content {
border:1px solid blue;
display:inline;
float:left;
font-size:100%;
line-height:1.5em;
margin:15px;
padding:5px;
text-align:left;
width:480px;
min-height: 500px;
}
#footer {
border:1px solid blue;
background-position:50% 100%;
background-repeat:repeat no-repeat;
clear:both;
height:30px;
margin:15px;
padding: 10px;
text-align:center;
width:780px;
}
程序12.22
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"/dtds/tiles-config_2_">
程序12.23
package ;
import Support;
import ;
public class LoginAction extends ActionSupport{
private User user;
public String authenticate() { // 登录验证方法
if (rname().equals("admin")
&& sword().equals("admin123")){
return "success";
} else {
addActionError(getText(""));
return "error";
}
}
public String logout() { // 退出登录方法
return "logout";
}
public User getUser() {
return user;
}
public void setUser(User user) {
= user;
}
}
程序12.24
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"/dtds/">
value="false" /> value="ApplicationResources" /> class="esult" /> method="authenticate"> method="logout" >
版权声明:本文标题:JavaWeb编程技术第2版源代码 内容由热心网友自发贡献,该文观点仅代表作者本人,
转载请联系作者并注明出处:https://www.elefans.com/dianzi/1719976136a813787.html,
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论