实验一 JSP内置对象的应用
package com.count.stoptime;
import java.util.*;
public class StopTime {
private int h=0;
private int m=0;
private int s=0;
public StopTime(){}
public void counttime(Date start){
Date end=new Date();
long howmuch=end.getTime()-start.getTime();
h=(int)(howmuch/1000/60/60);
howmuch=howmuch-h*60*60*1000;
m=(int)(howmuch/1000/60);
howmuch=howmuch-m*60*1000;
s=(int)(howmuch/1000);
}
public int getH(){
return this.h;
}
public int getM(){
return this.m;
}
public int getS(){
return this.s;
}
}
Index.jsp
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="java.util.*" %>
<jsp:useBean id="mycounttime" class="com.count.stoptime.StopTime" scope="page"/>
<%
session.setMaxInactiveInterval(11);
Date now=new Date();
if(session.isNew()){
session.setAttribute("start",now);
}
else{
mycounttime.counttime((Date)session.getAttribute("start"));
}
%>
<html>
<head>
<title>统计用户在某一页停留的时间</title>
<meta http-equiv="refresh" content="10">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<center>
<table width="250" height="100" border=1 bordercolor="black" bordercolorlight="black" bordercolordark="white" cellspacing=0" style="margin-top:200">
<tr bgcolor="lightgrey" height="25">
<td align="center">统计用户在某一页停留的时间</td>
</tr>
<tr>
<td align="center">
您登录的时间为:<%=((Date)session.getAttribute("start")).toLocaleString()%>
</td>
</tr>
<tr>
<td align="center">
您在本页的停留时间为:<%=mycounttime.getH()%>小时<%=mycounttime.getM()%>分<%=mycounttime.getS()%>秒
</td>
</tr>
</table>
</center>
</body>
</html>
实验二
应用session对象实现用户登录
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%>
<%@ page import="java.util.*" %>
<%
String[][] userList={{"mr","mrsoft"},{"wgh","111"},{"sk","111"}};
boolean flag=false;
request.setCharacterEncoding("GB18030");
String username=request.getParameter("username");
String pwd=request.getParameter("pwd");
for(int i=0;i<userList.length;i++){
if(userList[i][0].equals(username)){
if(userList[i][1].equals(pwd)){
flag=true;
break;
}
}
}
if(flag){
session.setAttribute("username",username);
response.sendRedirect("main.jsp");
}else{
response.sendRedirect("index.jsp");
}
%>
实验三 javabean使用
打开指定大小的窗口
package com.lh.bean;
public class ShowWindow {
private String url;
private String openWindowStr="";
private int width;
private int height;
private String functionName;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOpenWindowStr() {
StringBuffer sb = new StringBuffer(openWindowStr);
sb.append("<script language='javascript'>");
sb.append("\r\n\t");
sb.append("function "+this.functionName+"(){");
sb.append("\r\n\t\t");
sb.append("var returnObj = window.open('"+this.url+"','window','width="+this.width+"px,height="+this.height+"px');");
sb.append("\r\n\t\t");
sb.append("var x=(screen.width-"+width+")/2;");
sb.append("\r\n\t\t");
sb.append("var y=(screen.height-"+height+")/2;");
sb.append("\r\n\t\t");
sb.append("returnObj.moveTo(x,y);");
sb.append("\r\n\t}");
sb.append("\r\n");
sb.append("</script>");
return sb.toString();
}
public void setOpenWindowStr(String openWindowStr) {
this.openWindowStr = openWindowStr;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getFunctionName() {
return functionName;
}
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
public static void main(String [] args){
ShowWindow s = new ShowWindow();
s.setFunctionName("openWindow");
s.setUrl("index.jsp");
s.setWidth(500);
s.setHeight(500);
System.out.println(s.getOpenWindowStr());
}
}
实验4用servlet生成动态验证码
package com.lh.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidateCodeServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public ValidateCodeServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public Color getRandomColor(int fc,int bc){
Random random = new Random();
Color randomColor = null;
if(fc>255) fc=255;
if(bc>255) bc=255;
//设置个0-255之间的随机颜色值
int r=fc+random.nextInt(bc-fc);
int g=fc+random.nextInt(bc-fc);
int b=fc+random.nextInt(bc-fc);
randomColor = new Color(r,g,b);
return randomColor;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandomColor(200,250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
g.setColor(getRandomColor(160,200));
for(int i=0;i<130;i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x,y,x+xl,y+yl);
}
String strCode="";
for (int i=0;i<4;i++){
String strNumber=String.valueOf(random.nextInt(10));
strCode=strCode+strNumber;
g.setColor(new Color(15+random.nextInt(120),15+random.nextInt(120),15+random.nextInt(120)));
g.drawString(strNumber,13*i+6,16);
}
request.getSession().setAttribute("Code",strCode);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
实验5 字符编码过滤器
package com.mr.encoding;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter {
private String Encoding; //在醒置web.xml编码
private boolean enabled; //是否启用Filter
public void init(FilterConfig config) throws ServletException {
Encoding = config.getInitParameter("Encoding");//编码方式
enabled = "true".equalsIgnoreCase(Encoding.trim()) //启用此FIlter
|| "1".equalsIgnoreCase(Encoding.trim());
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (enabled || Encoding != null) {//如果启用了此Filter
request.setCharacterEncoding(Encoding);//request的编码
response.setCharacterEncoding(Encoding);//response的编码
}
chain.doFilter(request, response);//继续执行下一个Filter
}
public void destroy() {
Encoding = null;
}
}
实验六
package com.lh.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
String name = request.getParameter("name");
//name = new String(name.getBytes("ISO-8859-1"),"GBK");
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
String email = request.getParameter("email");
request.getRequestDispatcher("logininfo.jsp").forward(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
实验七 利用JSTL实现网站计数器
刷新后:
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jstl实现网站计数器功能</title>
</head>
<body>
<table align="center" cellpadding="0" cellspacing="0" bgcolor="lightblue">
<c:set var="allCount" value="${ allCount + 1 }" scope="application"></c:set>
<c:set var="count" value="${ count + 1 }" scope="session"></c:set>
<Tr><td>
今天访问本网站总人数为:${ allCount } <br/>
今天您访问了此网站次数为:${ count } <br/>
</td></Tr>
<c:set var="test" value="by property"></c:set>
<c:set var="test">by body</c:set>
</table>
<br/>
<br/>
<%
request.setAttribute("user", new com.mr.bean.User());
request.setAttribute("map", new java.util.HashMap());
%>
<c:set target="${ user }" property="name" value="${ param.name }"></c:set>
${ user.name }
<c:set target="${ map }" property="name" value="${ param.name }" />
${ map.name }
</body>
</html>
实验八 小写金额转成大些金额
package com.lh.bean;
public class StringUtil {
private String money;
private String submoneyCN[]={"","拾","佰","仟"}; //表示数字位数的数组
private String numberCNN[]={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
private String je="零壹贰叁肆伍陆柒捌玖";
private String cdw="万仟佰拾亿仟佰拾万仟佰拾元角分";
public StringUtil(){}
public void setMoney(String money){
this.money=money;
}
public String getMoney(){
return convert(this.money);
}
public String convert(String money){
String formatCN="";
int point=money.indexOf(".");
if(point!=-1){
String money1=money.substring(0,point);
String money1_1=(new StringBuffer(money1).reverse()).toString();
String money2=money.substring(point+1);
if(money2.length()<2){
if(money2.length()==0)
money2="00";
else
money2+="0";
}
else
money2=money.substring(point+1,point+3);
int len = money1_1.length();
int pos=len-1;
String sigle="";
boolean allhavenum=false;
boolean havenum=false;
boolean mark=false;
while(pos>=0){
sigle=money1_1.substring(pos,pos+1);
if(pos>=8&&pos<12){
if(!sigle.equals("0")){
if(!mark){
formatCN+=numberCNN[Integer.parseInt(sigle)]+submoneyCN[pos%4];
}
else{
if(allhavenum){
formatCN+="零";
}
formatCN+=numberCNN[Integer.parseInt(sigle)]+submoneyCN[pos%4];
mark=false;
}
havenum=true;
allhavenum=true; }
else{
mark=true;
}
if(pos%4==0&&havenum){
formatCN+="亿";
havenum=false;
}
}
if(pos>=4&&pos<8){
if(!sigle.equals("0")){
if(!mark)
formatCN+=numberCNN[Integer.parseInt(sigle)]+submoneyCN[pos%4];
else{
if(allhavenum){
formatCN+="零";
}
formatCN+=numberCNN[Integer.parseInt(sigle)]+submoneyCN[pos%4];
mark=false;
}
havenum=true;
allhavenum=true;
}
else{
mark=true;
}
if(pos%4==0&&havenum){
formatCN+="万";
havenum=false;
}
}
if(pos>=0&&pos<4){
if(!sigle.equals("0")){
if(!mark)
formatCN+=numberCNN[Integer.parseInt(sigle)]+submoneyCN[pos%4];
else{
if(allhavenum){
formatCN+="零";
}
formatCN+=numberCNN[Integer.parseInt(sigle)]+submoneyCN[pos%4];
mark=false;
}
havenum=true;
allhavenum=true;
}
else{
mark=true;
}
}
pos--;
}
if(allhavenum) formatCN+="元";
else
formatCN="零元";
if(money2.equals("00"))
formatCN+="整";
else{
if(money2.startsWith("0")||(allhavenum&&money1.endsWith("0"))){
formatCN+="零";
}
if(!money2.startsWith("0")){
formatCN+=numberCNN[Integer.parseInt(money2.substring(0,1))]+"角";
}
formatCN+=numberCNN[Integer.parseInt(money2.substring(1))]+"分";
}
}
else{
formatCN="输入的格式不正确!格式:888.00";
}
return formatCN;
}
}