javaee学习之路(十四)JSP编程实例

javaee学习之路(十四)JSP编程实例_第1张图片
例1、输出当前时间值。
1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp入门案例(输出时间)</title>   
  </head>
  <body>
  当前时间值是:
   <% Date date=new Date(); out.write(date.toLocaleString()); %>
  </body>
</html>

找到tomcat服务器当中对应的Servlet文件C:\tomcat\work\Catalina\localhost\day08\org\apache\jsp\ _1_jsp.java
……

out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write(" <head>\r\n");
      out.write(" <title>jsp入门案例(输出时间)</title> \r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("当前时间值是:\r\n");
      out.write(" ");
      Date date=new Date();
      out.write(date.toLocaleString());
      out.write("\r\n");
      out.write(" </body>\r\n");
      out.write("</html>\r\n");

<% %>之间的内容被原封不动地嵌套在了servlet当中
例2、Page指令之errorPage,怎样处理JSP当中的异常—实际开发当中案例1。
Step1、1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp入门案例(输出时间)</title>   
  </head>
  <body>

   <% int x=1/0; out.print(x); %>
  </body>
</html>

Step2、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <error-page>
    <exception-type>java.lang.ArithmeticException</exception-type>
    <location>/errors/error.jsp</location>
  </error-page>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Step3、error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'error.jsp' starting page</title>   
  </head>
  <body>
    对不起,出错了!!! <br>
  </body>
</html>

例3、Page指令之errorPage,怎样处理JSP当中的异常—实际开发当中案例1
Step1、

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <error-page>
    <exception-type>java.lang.ArithmeticException</exception-type>
    <location>/errors/error.jsp</location>
  </error-page>
  <error-page>
    <error-code>404</error-code>
    <location>/errors/404.jsp</location>
  </error-page>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Step2、404.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '404.jsp' starting page</title>   
  </head>
  <body>
      对不起,您访问的资源不存在!!! <br>
  </body>
</html>

Step3、在IE中键入htpp://localhost:8080/day08/fandong
例3、JSP乱码问题。
javaee学习之路(十四)JSP编程实例_第2张图片
在Eclipse当中只需要这只PageEncoding就行了
例4、include指令实例代码
Step1、在WebRoot目录之下建立目录public,在其中放入head.jsp和foot.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>head.jsp</title>   
  </head>
  <body>
    这是页头!!! <br>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>foot.jsp</title>   
  </head>
  <body>
    这是页脚!!! <br>
  </body>
</html>

Step2、在WebRoot目录下创建页面2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>include指令(静态包涵)</title>   
  </head>
  <body>
  <%@include file="/public/head.jsp"%>
    aaaa<br>
  <%@include file="/public/foot.jsp"%>
  </body>
</html>

Step3、在ie中键入: http://localhost:8080/day08/2.jsp可得

这是页头!!! 
aaaa
这是页脚!!!

1、 在实际开发当中通常将head.jsp和foot.jsp等被包涵的文件写为一下格式:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    这是页头!!!<br> 

(即只留下声明和与当中的内容即可)
2、include指令(静态包涵,编译时包含,被包涵的JSP文件与包涵的Jsp文件一起编译成一个servlet)
3、动态包涵:3.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>动态包涵(这种情况是运行时包含)</title>   
  </head>
  <body>
   <% request.getRequestDispatcher("/public/head.jsp").include(request,response); %>
   <% response.getWriter().write("aaaaaaaaaaa <br>"); %>
    <% request.getRequestDispatcher("/public/foot.jsp").include(request,response); %>
  </body>
</html>

在实际开发当中尽量用静态包含!!!!!
例5、out隐式对象
问题演示:4.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '4.jsp' starting page</title>   
  </head>
  <body>
      Aaaaaaa//编译之后用out输出
    <% out.write("hahahahahha"); response.getWriter().write("wuuwuwuwuuwu"); %>
  </body>
</html>

在IE中键入:http://localhost:8080/day08/4.jsp可以看到:
wuuwuwuwuuwu aaaaaaaa hahahahahha
问题在于并没有出想ha在前wu在后的情况,原因:out有缓存
例6、PageContext对象访问其他域对象(4.jsp)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>pageContext对象访问其他域</title>   
  </head>
  <body>
    <% request.setAttribute("data","fandong"); String data=(String)pageContext.getAttribute("data",PageContext.REQUEST_SCOPE); out.write(data); %>
  </body>
</html>

在IE中可以得到:fandong
例7、pageContext域对象之findAttribute方法之应用。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>pageContext对象访问其他域</title>   
  </head>
  <body>
    <% request.setAttribute("data","fandong"); String data=(String)pageContext.getAttribute("data",PageContext.REQUEST_SCOPE); out.write(data+"<br/>"); String data2=(String)pageContext.findAttribute("data"); out.write(data2); %>
  </body>
</html>

在IE中可以得到:fandong
fandong
例8、标签的作用
Step1、5.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>JSP常用标签</title>   
  </head>
  <body>
  <% String x="12"; %>
    <jsp:forward page="/servlet/ServletDemo1">
      <jsp:param value="<%= x %>" name="password"/>
      <jsp:param value="fandong" name="username"/>
    </jsp:forward>
  </body>
</html>

Step2、ServletDemo1.java

package cn.itcast.web.servlet;
import *;
public class ServletDemo1 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username=request.getParameter("username");
        System.out.println(username);
        String x = (String)request.getParameter("password");
        System.out.println(x);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

Step3、在IE中键入:htpp://localhost:8080/day08/5.jsp可以看到:fandong 12
例9、应用实例之一。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp:usebean</title>   
  </head>
  <body>
  <%--创建一个Person对象,这个对象的名字叫做person,(如果在page域中有了一个Person就直接拿过来用,不另外创建)--%>
<%-- useBean标签的标签提只在useBean标签实例化bean时才执行--%>
    <jsp:useBean id="person" class="cn.itcast.domain.Person" scope="page">
    Fandong!!!!
</jsp:useBean>
    <%=person.getName() %>
  </body>
</html>

    上面的过程中,当浏览器第一次访问1.jsp时,useBean标签会实例化Person对象,此时标签之间的Fandong!!!!会执行下去,会在浏览其中显示,但是,当第二次访问1.jsp时就不会执行了,因为已经在page域当中创建了persion的对象了!
例10、2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp:setProperty标签</title>   
  </head>
  <body>
        <jsp:useBean id="person" class="cn.itcast.domain.Person" scope="page"/>
    <%--手工为bean赋值 --%>
    <jsp:setProperty name="person" property="name" value="xxx"/>
    <%--赋当前时间值给属性birthday --%>
    <jsp:setProperty name="person" property="birthday" value="<%=new Date()%>"/> 
    <%=person.getName() %><br/>
    <%=person.getBirthday() %><br/>
    <%--用请求参数给bean的属性赋值 --%>
    <jsp:setProperty property="name" name="person" param="name"/>
    <jsp:setProperty property="age" name="person" param="age"/>
    <%=person.getName() %><br/>
    <%=person.getAge() %><br/>
  </body>
</html>

    在IE中键入http://localhost:8080/day09/2.jsp?name=fandong&age=12可以得到结果:
xxx
Sat Sep 15 17:52:51 CST 2012
fandong
12
例11、为所有参数赋值。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp:setProperty标签</title>   
  </head>
  <body>
    <jsp:useBean id="person" class="cn.itcast.domain.Person" scope="page"/>
    <%--用所有的请求参数为bean赋值 --%>
    <jsp:setProperty property="*" name="person"/>
    <%=person.getName()%>
上面这一句代码等同于<jsp:getProperty name=”person” ptoperty=”name”/>
    <%=person.getAge()%>   
  </body>
</html>

    在IE中键入http://localhost:8080/day09/2.jsp?name=fandong&age=12可以得到结果:
fandong
12
(注意IE栏中带过来的参数名称应该与bean中的属性名一样)
说明:在servlet当中自动将”12”转为了整形。这个标签支持8中数据类型的转换(把客户机提交的字符串转为8中基本数据类型赋值到jean当中)。
例13、使用Jsp+javabean编写一个计算器页面,javaBean具有firstNum、secondNum、result、operator属性,并提供一个calculate方法.
补充:实现各种数的精确运算:

package cn.itcast.domain;
import java.math.BigDecimal;
public class Demo1 {
    public static void main(String[] args){
        BigDecimal a=new BigDecimal("0.1");
        BigDecimal b=new BigDecimal("0.006");
        BigDecimal c=new BigDecimal("0.3");
        System.out.println(a.add(b).toString());
        System.out.println(a.multiply(b).toString());
        System.out.println(a.divide(c, 10,BigDecimal.ROUND_HALF_UP));
        //表示保留小数点后面10位
    }
}

输出结果为:
0.106
0.0006
0.3333333333
Step1、calculator.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>计算器</title>   
  </head>
  <body style="text-align: center">
   <jsp:useBean id="calculatorBean" class="cn.itcast.domain.CalculatorBean"></jsp:useBean>
   <jsp:setProperty property="*" name="calculatorBean"/>
   <% try{ calculatorBean.calculator(); }catch(Exception e) { out.write(e.getMessage());//把异常给用户友好提示 } %> 
    <br/>--------------------------------------------------------<br/>
    计算结果是:
    <jsp:getProperty property="firstNum" name="calculatorBean"/>
    <jsp:getProperty property="operator" name="calculatorBean"/>
    <jsp:getProperty property="secondNum" name="calculatorBean"/>
    =
    <jsp:getProperty property="result" name="calculatorBean"/>
    <br/>--------------------------------------------------------<br/>
    <form action="/day09/calculator.jsp" method="post">
    <table width="40%" border="1">
       <tr>
          <td colspan="2">简单的计算器</td>
       </tr>
       <tr>
           <td>第一个参数</td>
           <td>
               <input type="text" name="firstNum"/> 
           </td>
       </tr>
       <tr>
           <td>运算符</td>
           <td>
               <select name="operator">
                  <option value="+">+</option>
                  <option value="-">-</option>
                  <option value="*">*</option>
                  <option value="/">/</option>

               </select>
           </td>
       </tr>
       <tr>
           <td>第二个参数</td>
           <td><input type="text" name="secondNum"/> </td>
       </tr>
       <tr>
           <td colspan="2">
              <input type="submit" value="计算"/>
           </td>
       </tr>
    </table>
    </form>
  </body>
</html>

Step2、CalculatorBean.java

package cn.itcast.domain;
import java.math.BigDecimal;
//封转计算器数据的bean
public class CalculatorBean {
    private String firstNum="0";
    private String secondNum="0";
    private char operator='+';
    private String result;
    public String getFirstNum() {
        return firstNum;
    }
    public void setFirstNum(String firstNum) {
        this.firstNum = firstNum;
    }
    public String getSecondNum() {
        return secondNum;
    }
    public void setSecondNum(String secondNum) {
        this.secondNum = secondNum;
    }
    public char getOperator() {
        return operator;
    }
    public void setOperator(char operator) {
        this.operator = operator;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public void calculator(){
        BigDecimal first=new BigDecimal(this.firstNum);
        BigDecimal second=new BigDecimal(this.secondNum);
        switch (this.operator) {
        case '+':{
            this.result=first.add(second).toString();
            break;}
        case '-':{
            this.result=first.subtract(second).toString();
            break;}
        case '*':{
            this.result=first.multiply(second).toString();
            break;}
        case '/':{
            if(second.doubleValue()==0){
                throw new RuntimeException("被除数不能为0");
            }
            this.result=first.divide(second,10,BigDecimal.ROUND_HALF_UP).toString();
            break;}
        default:{
            throw new RuntimeException("运算符错误!");
            }
        }
    }
}

例14、EL表达式例程。(3.jsp)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>EL表达式例程</title>   
  </head>
  <body>
    <% String data="fandong"; request.setAttribute("data",data); %>
     ${data}<%--相当于pageContext.findAttribute(“data”);--%>
  </body>
</html>

在IE中键入:http:localhost:8080/day09/3.jsp便可以看到:
fandong
例15、EL表达式快速入门。
Step1、Person.java

package cn.itcast.domain;
import java.util.Date;
public class Person {
    private String name;
private Address address;
    public Person() {
        super();
    }
    public Person(String name) {
        super();
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
}

Step2、Address.java

package cn.itcast.domain;
public class Address {
    private String city;
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
}

Step3、3.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%%@page import="cn.itcast.domain.Person"%%>
<%@page import="cn.itcast.domain.Address"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>EL表达式例程</title>   
  </head>
  <body>
     <% String data="fandong"; request.setAttribute("data",data); %>
            ${data}<%--相当于pageContext.findAttribute(“data”);--%>
     <br>
     <% Person p=new Person(); p.setName("denghongmei!"); request.setAttribute("person",p); %>
            ${person.name}
            <br>
      <% Person p1=new Person(); Address a=new Address(); a.setCity("上海"); p1.setAddress(a); request.setAttribute("p1",p1); %>
             ${p1.address.city}
             <br>
       <%-- p1上面的request设置的属性名称,而后面的为bean封装的属性--%>
       <%--EL表达式读取集合当中的内容--%>
       <% List list=new ArrayList(); list.add(new Person("aaa")); list.add(new Person("bbb")); list.add(new Person("ccc")); request.setAttribute("list",list); %>
            ${list[0].name}
            <br>
        <% Map map=new HashMap(); map.put("aa",new Person("aaaa")); map.put("bb",new Person("bbbb")); map.put("cc",new Person("cccc")); map.put("dd",new Person("dddd")); map.put("1111",new Person("eeee")); request.setAttribute("map123",map); %>
                ${map123.bb.name}
                <br>
         <%--用${map123.1111.name}取不出来数据的,这是要用[]来取 --%>
               ${map123['1111'].name}  
               <br>
         <%--得到当前web应用的名称,用在超链接等地方 --%>
               ${pageContext.request.contextPath}
               <br>
               <a href="${pageContext.request.contextPath}/index.jsp">点击</a>
  </body>
</html>

例16、使用jstl和EL完成集合的迭代。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="cn.itcast.domain.Person"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%--上面一行的作用是导入标签库,上面的uri怎么来的? 在eclipse左侧目录点击day09项目->Reference Libraries->standard.jar->META-INF->c.tld->找到映射的<uri>http://java.sun.com/jsp/jstl/core</uri>--%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>使用jstl+EL完成集合迭代</title>   
  </head>
  <body>
    <% List list=new ArrayList(); list.add(new Person("aaa")); list.add(new Person("bbb")); list.add(new Person("ccc")); request.setAttribute("list",list); %>
      <c:forEach var="person" items="${list }">
      <%--将迭代的每个元素放在person变量当中 --%>
          ${person.name }<br/>
      </c:forEach>
      <br>
        <% Map map=new HashMap(); map.put("aa",new Person("aaaa")); map.put("bb",new Person("bbbb")); map.put("cc",new Person("cccc")); map.put("dd",new Person("dddd")); map.put("1111",new Person("eeee")); request.setAttribute("map123",map); %>
        <c:forEach var="entry" items="${map123}">
        <%--对map的迭代实际上是对map.entrySet返回的set<Map.entry>结合进行迭代 --%>
          ${entry.key} : ${entry.value.name} <br/>
     <%--判断标签 --%>
        </c:forEach>
        <c:if test="${user!=null}">
                               欢迎您:${user.username}
        </c:if>
        <c:if test="${user==null}">
        用户名:<input type="text"/>
        密码:<input type="password"/>
        </c:if>
  </body>
</html>

你可能感兴趣的:(javaee学习之路(十四)JSP编程实例)