java深入探究07-jsp

RequestDispatcher
是web资源包装类
<jsp:include>只能实现固定jsp文件名
他可以翻译为:RequestDispatcher(filename).include(request,response);
这里实现的是:跳转到指定的fileName地址,包含

转发重定向区别:

  requset,response信息一起过去

我们可以把它想成一个web资源的盒子,用来对web资源封装好一起处理

  转发:请求不变只是请求发给服务器后,服务器将请求还了一个给浏览器,所以浏览器的url不变

  重定向:发送请求给服务器,服务器response回一个新的链接给浏览器,让浏览器从新发送一个请求给服务器,这就是重定向,之前的request中的保存的东西也就不在了,我们能看到的区别就是url变了

1.为什么出现JSP

  Servlet是动态开发语音,而jsp是可以htmlServlet结合的不仅能编写java代码可以布局样式,类似于.NET中的cshtml

2.Jsp的执行过程

  a) 找到Tomcatwork目录存放jsp的临时文件-》翻译成java文件-》编译成class文件-》构造类对象-》调用方法

  b) Jsphtml部分被编译到Servletserver方法中,java部分被编译到jsp_server

3.Jsp的生命周期

  a) Servlet生命周期

    构造方法-init方法-service方法-destroy方法

  b) Jsp的生命周期

    翻译jsp->java->编译java-class->构造方法-init方法-service方法-destory方法

4.Jsp语法

  a) Jsp模板:html部分就是jsp模板

  b) Jsp表达式:<%=变量或表达式 %>想浏览器输出变量或表达式结果,out.writer();

  c) Jsp脚本:<% java脚本 %> jsp编译器直接将这部分代码复制到jsp_service()方法

  d) jsp声明:<%!变量或方法%>声明jsp的成员变量和成员方法

  e) Jsp注释:<%!--jsp注释-->

5.Jsp的三大指令

  a) Include指令

  1. 静态引入其他页面,将两个jsp文件翻译为一个java文件,所以不能出现重复的模板html部分代码
  2. 语法:<%include file=”path路径”%>

  b) Page指令

  1. 告诉tomcat怎么将jsp文件翻译为java文件
  2. 例子:

    <% page import=”java.lang.util.*”

                   Language=”java”

         pageEncoding=”utf-8”

       contentType=”text/html; charset=utf-8”

         errorPage=”” //指定当前错误页面的处理页面

       isPageError=false;指定当前页面是否是错误处理页面,是的话可以用jsp内置错误对象exception,反之不可

    %>

      配置全局的错误处理页面方式

      在web.xml中设置:不同的错误代码调到不同的错误页面全局配置

         <!-- 全局错误处理页面配置 -->

         <error-page>

           <error-code>500</error-code>

           <location>/common/500.jsp</location>

         </error-page>

        <error-page>

           <error-code>404</error-code>

           <location>/common/404.html</location>

       </error-page>

    Session=true;

    Buffer=8kb;   jsp页面的缓存器大小

    isELIngore=false 是否忽略EL

例子:语法例子

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"
    import="java.util.*"%>
<!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>jsp语法</title>
</head>
<body>
    <!-- jsp表达式 -->
    <%
        //变量
        String name="xiaoping";
        int a=10;
        int b=20;
    %>
    <%=name %>
    <%=(a-b) %>
    <!-- jsp脚本 -->
    <%
        //生成随机数
        Random d=new Random();
        float num=d.nextFloat();
    
    %>
    <%
        for(int i=1;i<6;i++){
    %>
    <!-- 穿插html 代码 -->
        <h<%=i %>>标题<%=i %></h<%=i %>>
    <%
        }
    %>
    
    <!-- 练习:使用html代码显示99乘法表 -->
    <%
        for(int i=1;i<9;i++){
            for(int j=1;j<9;j++){
    %>
                <%=i %> x <%=j %>=<%=(i*j) %>&nbsp;
        <%
            }
        %>
        <br/>
    <%    
        }
    %>
    <%
        String age="20";
    %>
    <!-- jsp声明 -->
    <%!
        String name="xiaoping";
        public String getName(){
            return name;
        }
    %>
    <!-- html注释 -->
    <%-- <jsp:forward page="/jsp1/index/jsp">内置标签</jsp:forward> --%>
    <%-- jsp注释--%>
</body>
</html>
View Code

  c) Taglib指令

  1. 引入标签

6.jsp的内置对象

  a) 内置对象

    在Jsp开发中我们会频繁用到一些对象,一一创建太麻烦,sun提供了内置对象为我们创建好了,目前有8种重要的内置对象

    Responserequest,config(ServletConfig),pageContext,out(jspWriter),application(ServletContext),pageObject this,exception(Throwable)

  b) 内置对象详解

  1. Out对象
    1. jspWriter类型向缓冲区写内容;printWriter向浏览器写内容
    2. 什么情况下缓冲区内容会输出:溢出;刷新;关闭;执行完毕jsp页面
  2. PageContext

    在定义标签的时候pageContext时常使用

  1. 就是ServletContext对象就是PageContext类型可以获取其他八种内置对象

    a) 原因:在将jspjava代码部分翻译到jsp_Service()中去时在这里面创建完8中内置对象,之后又将这8中对象封装到pageContext中了

    b) 调用方法:pageContext.getXXX();

  1. 本身也是域对象下面四个域对象pageContext都能用

    a) ServeltContext context

    b) PageContext; page

    c) HttpSession; session

    d) HttpServletRequest Request

      一:保存数据

        1)默认情况保存的是page域:PageContext.setAttribute(“name”);

        2)可以向四个域中保存对象:PageContext.setAttribute(“name”,域范围常量)

      二:获得数据

        1)默然情况获得page域的:PageContext.getAttribute(“name”);

        2)可以向四个域中保存对象:PageContext.sgetAttribute(“name”,域范围常量)

        3)自动从四个域中查找:pageContext.findAttribute("name");

        4)域范围常量:

          PageContext.PAGE_SCOPE

          PageContext.REQUEST_SCOPE

          PageContext..SESSION_SCOPE

          PageContext.APPLICATION_SCOPE

        5)域顺序:page->request->session->appliction(serlvetContext)

        6)这四个域的作用范围:

        a) Page域:只能在jsp页面当前页面使用

        b) Request域:只能在同一个请求中使用

        c) Session域:只能在同一个回话中使用

        d) Context域:可以在整个web应用中使用

例子:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"
    import="java.util.*"
    session="true"
    isErrorPage="true"
    %>
<!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>测试jsp的语法</title>
</head>
<body>
<!-- 内置对象 -->
    <!-- pageContext -->
    <%
        /* 1)可以获取其他8种内置对象 */
        response.getWriter().write("是否相等?"+(out==pageContext.getOut())+"<br/>");
    %>
    <!-- 域对象 -->
    <!--pageContext:作用于当前jsp
    request:作用于同一请求
    session:作用于同一回话
    context:作用于当前web -->
    <%
        //保存数据,默认情况,保存到page域中
        pageContext.setAttribute("message","page's message");
        pageContext.setAttribute("message", "session's message", PageContext.SESSION_SCOPE);//保存到session 中
        pageContext.setAttribute("message", "request's message", pageContext.REQUEST_SCOPE);//保存到request域中
        //request.setAttribute("message", "request's message")//等价于上面一个
    %>
    <%
        //获取数据,默认情况保存在page域中
        String message=(String)pageContext.getAttribute("message");
        out.write(message);
        
    %>
    <!-- 从Request域中获取对象
    原则:
    1)在哪个域保存数据,就必须从哪个域中取出数据  -->
    <%=pageContext.getAttribute("message",PageContext.PAGE_SCOPE) %><br/>
    <%=pageContext.getAttribute("message",PageContext.REQUEST_SCOPE) %><br/>
    <%=pageContext.getAttribute("message",PageContext.SESSION_SCOPE) %><br/>
    <%=pageContext.getAttribute("message",PageContext.APPLICATION_SCOPE) %><br/>
    
    <!-- 按照一定的顺序查找
    查找顺序:page域-》request-》session域-》Context域原则小范围到大范围 -->
    <%=pageContext.findAttribute("message") %>
    <!-- 转发从定向 -->
    <%
        //装发
        request.getRequestDispatcher("/jsp1/index.html");
        //从定向
        /* response.sendRedirect("/jsp1/index.html"); */
    %>
    
</body>
</html>
View Code

7.JspServlet如何结合

  a) Jsp+Servlet模式

    Jsp通过java代码擅长输出html

    Servlet任务:

      接受参数-》处理逻辑代码-》将结果保存在域对象中-》跳转到jsp界面

    Jsp任务:

      从域对象中获得数据-》把数据显示在浏览器中

例子:百万富翁竞猜游戏

jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"
    import="java.util.*"
    %>
<!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>百万富翁竞猜游戏</title>
</head>
<body>
    <%
        //显示提示信息
        String msg=(String)request.getAttribute("msg");
        if(msg!=null){
            out.write("<font color='red'>"+msg+"</font>");
        }
    %>
    <%
        //获取竞猜次数
        Integer times=(Integer)request.getAttribute("times");
        if(times!=null){
            out.write(",你还有"+(5-times)+"次机会!");
        }
    %>
    <!-- 提交表当数据 -->
    <form action="/jsp1/GuessServlet" method="post">
        请输入30以下的整数:<input type="text" name="lucyNo"/>
        <!-- 这里可以提交我们的尝试次数 -->
        <%
            if(times!=null){
            %>
            <input type="hidden" name="times" value="<%=times%>"/>
            <%
            }
        %>
        
        <input type="submit" value="开始竞猜"/>
    </form>
</body>
</html>
View Code

Servlet

package Servlet;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 产生一串幸运数字
 */
public class GuessServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    int answer;
    /**
     * 新游戏方法。产生一个新的幸运数字
     */
    public void newGame(){
        Random random = new Random();
        answer = random.nextInt(30);
    }
    
    public GuessServlet(){
        //第一次访问
        newGame();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
        
        //1.接收输入的数字
        String lucyNoStr = request.getParameter("lucyNo");
        System.out.println("答案:"+answer);
        Integer lucyNo = null;
        //2.判断幸运数字和用户的数字
        //2.1 把用户输入的数字转成整数
        if(lucyNoStr!=null || !lucyNoStr.equals("")){
            lucyNo = Integer.parseInt(lucyNoStr);
        }
        
        //标记记录当前竞猜的次数
        Integer times = 1;//初始值
        
        //接收客户当前竞猜次数
        String timesStr = request.getParameter("times");
        if(timesStr!=null && !timesStr.equals("")){
            times = Integer.parseInt(timesStr)+1;
        }
        
        
        if(times<5){
            String msg = "";
            //比较
            if(lucyNo>answer){
                //大了
                msg = "可惜,大了点";
            }else if(lucyNo<answer){
                //小了
                msg = "可惜,小了点";
            }else if(lucyNo==answer){
                //等于,中奖
                msg = "恭喜你,中得1000000元现金大奖,请带身份证到xxx地方领奖!";
                times = null;
            }
            //把当前竞猜的次数放入域对象
            request.setAttribute("times", times);
            //把信息放入域对象中
            request.setAttribute("msg", msg);
        }else{
            //产生新的幸运数字
            newGame();
            //游戏结束
            response.getWriter().write("游戏结束。<a href='"+request.getContextPath()+"/05.guess.jsp'>再来一盘</a>");
            return;
        }
        //转发
        request.getRequestDispatcher("/05.guess.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
View Code

8.EL表达式

  1)出现的原因

    jsp开发的原则:jsp页面少写甚至不写java代码;就出现了EL 来代替jsp中的java部分代码

    作用:想浏览器输出域对象中的变量值或者表达式计算的结果

  2)语法

    a)获取标识符数据${标识符}:内部原理是调用了PageContext.findAttribute(标识符)从request,session,application,page域对象中找对应的值找不到就放回null

    b)获取javabean中的属性,数组,Collection,Map类型的集合中的数据

      ${user.address.city}

      ${user.list[0]}:访问有序集合中的摸个位置元素

  3)11个隐式对象web开发常用对象

    $(隐式对象名称):获得对象的引用

   c)注意事项:

      EL表达式是JSP2.0规范中的一门技术,想要正确解析,需要支持Servlet2.4、JSP2.0技术

      如果Tomcat不能使用EL表达式

、      升级Tomcat6.0;<% page isELIgnored=false%>

例子:

    <%
        String name="xiaoping";
        //放到域对象总
        pageContext.setAttribute("name", name);
    %>
    <%--
    1)从四个域中自动搜索
    EL表达式:${name}
            等级与<%=pageContext.findAttribute("name")%>
    2)从指定与中获取对象:EL有12种隐式对象
            ${pageScope.name}
            等价于:<%=pageContext.getAttribute("name",PageContext.pageScope)%>
     --%>
    ${pageScope.name }
    
    
    <!-- 2.输入不同类型的数据 -->
    <%
        Student student=new Student("xiaoping",20);
        pageContext.setAttribute("student", student);
    %>
    <%--使用EL获取对象 --%>
    ${student.name}-${student.age}
    
    <!-- 3。EL表达式 -->
    ${10+5}
    ${10>5 }
    ${true&&false}
    ${empty name}
View Code

9.Jsp标签

  1)出现原因:

    替代jsp中java代码,代码简化

  2)标签分类:

    内置标签;自定义标签;jstl(java Standard tag libarary java标准标签库)

    想要使核心标签:需要先将核心标签导入

    a)内置标签:

      <jsp:forward>//request.getRequestDipsacher("/路径").forward(request,response);

      <jsp:param/> 参数标签 ?name=eric

      <jsp:include> 包含其他页面,动态包含

    b)jstl:

      使用步骤:

        1)导入包到项目中

        2)在jsp页面中导入标签库

          <%@taglib url="标签库声明文件tld文件的标记" prefix="前缀"%>

        3)使用标签库中的标签

      核心标签库:

        <c:set />     保存数据到域对象中

        <c:out/>     从域中取出数据

        <c:if/>       单条件判断

        <c:choose/> + <c:when/> + <c:otherwise/>  多条件判断

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=gb2312" %>
<c:set value="${param.count}" var="count“  />
<c:choose>
    <c:when test="${count == 0}">
        对不起,没有符合您要求的记录。
    </c:when>
    <c:otherwise>
        符合您要求的记录共有${count}条.
    </c:otherwise>
</c:choose>
View Code

        <c:forEach />  遍历数据

varStatus="": 当前正在遍历元素的状态对象。(count属性:当前位置,从1开始)

        <c:forTokens/>  遍历特殊字符串

        <c:redirect/>   重定向

 例子:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"
    import= "java.util.*,Servlet.Student"
    %>
<%@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>Insert title here</title>
</head>
<body>
<!-- 动作标签 -->
    <%--转发 --%>
    <%
        //request.getRequestDispatcher("urlpath").forward(request, response);
    %>
    <%--参数--%>
    <%-- <jsp:forward page="url地址">
        <jsp:param value="name" name="value"/>
        <jsp:param value="name" name="value"/>
    </jsp:forward> --%>
    <%--包含 --%>
    <jsp:include page="/common/header.jsp">
        <jsp:param value="name" name="value"/>
    </jsp:include>
    <%@include file="/common/header.jsp" %>
    <!-- 两个包含的区别:前者是包含被编译后的文件;后者是包含没有编译的文件html -->

<!-- 核心标签库 -->
    <%--
        1.需要导入标签连接:<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        2.<c:out/><c:set/><c:if/><c:foreach/><c:forTokens/><c:redrect/>
     --%>
     <c:set var="name" value="xiaopinig" scope="request"></c:set>
     ${name }
     <%-- default: 当value值为null时,使用默认值
    escapeXml: 是否对value值进行转义,false,不转义,true,转义(默认) --%>
     <c:out value="${name }" default="<h3>标题3</h3>" escapeXml="true"></c:out>
     <c:if test="${empty msg}" var="aaa" >条件成立</c:if>
     <!-- choose标签+when标签+otherwirse标签: 多条件判断 -->
     <c:set var="score" value="56"></c:set>
     <c:choose>
         <c:when test="${score>=90&&score<=100 }">优秀</c:when>
         <c:when test="${score>=90&&score<=100 }">优秀</c:when>
         <c:when test="${score>=90&&score<=100 }">优秀</c:when>
         <c:when test="${score>=90&&score<=100 }">优秀</c:when>
     </c:choose>
     
        <%--  <c:forEach></c:forEach> --%>
    <%
        //List
         List<Student>  list = new ArrayList<Student>();
         list.add(new Student("rose",18));
         list.add(new Student("jack",28));
         list.add(new Student("lucy",38));
         //放入域中
         pageContext.setAttribute("list",list);
         
         //Map
         Map<String,Student> map = new HashMap<String,Student>();
         map.put("100",new Student("mark",20));
         map.put("101",new Student("maxwell",30));
         map.put("102",new Student("narci",40));
         //放入域中
         pageContext.setAttribute("map",map);
     %>
         
         <hr/>
         <c:forEach items="${list }" var="student" varStatus="varSta">
             序号:${varSta.count }-姓名:${student.name }-年龄:${student.age }<br/>
         </c:forEach>
         
         <%-- <c:forTokens items="" delims=""></c:forTokens> 循环特殊字符串--%>
         <%
             String str="sdfas-df-a-sdf-a";
         pageContext.setAttribute("str", str);
         %>
         <c:forTokens items="${str }" delims="-" var="s">
             ${s }<br/>
         </c:forTokens>
         
         
         <!-- redrict:重定向 -->
         <c:redirect url="http://www.baidu.com"></c:redirect>
</body>
</html>
View Code

    c)自定义标签

      步骤:编写java类继承SimpleTagSupport类,叫标签处理器-》

        在web项目的WEB-INF目录下建立tld文件,这个tld叫标签库的声明文件-》

        在jsp页面头部导入自定义标签:<%@taglib uri="http://gz.itcast.cn" prefix="itcast"%>-》最后再使用

      自定义标签的执行过程:

        访问jsp文件,tomcat把jsp文件编译成class文件-》构造对象,调用_jspService()方法-》

        检查jsp的tablib标签,是否存在tld文件,不存在就报错-》存在后读到子标签查询tld文件中是否有这个对象-》

        找到了就找到了class文件-》构造对象调用方法

        构造ShowIpTag对象,然后调用ShowIpTag里面的方法

      生命周期:

        SimpleTag接口:

          setParent(JspTag parent);    //设置父标签

          setJspContext(JspContext context);//获得PageContext内置对象

          setXXX(值);          //设置属性,前提是在定义一个私有变量

          doTag();            //执行标签时调用的方法

          setJspBody(JspFrament jspBody) //设置标签体内容,内容封装到JspFragment

      输出标签体内容格式:

          JSP   在传统标签中使用的。可以写和执行jspjava代码。

          scriptless:  标签体不可以写jspjava代码

          empty:    必须是空标签。

          tagdependent : 标签体内容可以写jspjava代码,但不会执行

    

例子:

java文件:

public class ShowIpTag extends SimpleTagSupport{

    @Override
    public void doTag()throws JspException, IOException {
        //向浏览器输入客户端ip地址
        PageContext page=(PageContext)this.getJspContext();
        HttpServletRequest request=(HttpServletRequest) page.getRequest();
        String host=request.getRemoteHost();
        JspWriter out=page.getOut();
        out.write("使用自定义标签输出客户的IP地址:"+host);
        
    }

    
}
View Code

tld文件

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">
     <!-- 标签可的版本 -->
     <tlib-version>1.1</tlib-version>
     <!-- 标签库的前缀 -->
     <short-name>Mybiaoqian</short-name>
     <!-- tld文件唯一标记 -->
     <uri>http://xiaoping.com</uri>
     
     <!-- 标签的声明 -->
     <tag>
         <name>showIp</name>
         <tag-class>Biaoqian.ShowIpTag</tag-class>
         <body-content>scriptless</body-content>
     </tag>
</taglib>
View Code

jsp文件

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"
    %>
<%@taglib uri="http://xiaoping.com" prefix="Mybiaoqian"%>
<!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>自定义标签</title>
</head>
<body>
    <Mybiaoqian:showIp></Mybiaoqian:showIp>
</body>
</html>
View Code

10.javaBean

  咖啡豆,一种开发规范,也可以说是一种技术

  满足一定条件:

        1)必有有无惨构造函数2)属性私有化3)提供getset方法设置属性

  使用场景

    1)项目中用到实体对象(entity)符合javabean规范

    2EL表达式访问对象属性。${student.name}  调用getName()方法,符合javabean规范。

    3jsp标签中的属性赋值。 setNumInteger num)。符合javabean规范。

    4jsp页面中使用javabean。符合javabean规范

  关于javaBean的动作元素

    1)<jsp:useBean>:查找或者实例化一个javaBean对象

    2)<jsp:setProperty>标签:设置一个javaBean组件的属性

    3)<jsp:getProperty>标签:得到一个javaBean组件的属性

web项目:通讯录的web项目

1.实体
package contact1;
/**
 * 联系人
 * @author Administrator
 *
 */
public class Contact {
    private String id;
    private String name;
    private String gender;
    private int age;
    private String phone;
    private String email;
    private String qq;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getQq() {
        return qq;
    }
    public void setQq(String qq) {
        this.qq = qq;
    }
    @Override
    public String toString() {
        return "Contact [age=" + age + ", email=" + email + ", gender="
                + gender + ", id=" + id + ", name=" + name + ", phone=" + phone
                + ", qq=" + qq + "]";
    }
    
}
View Code

2.工具类

XmlUtil,JdbcUtil

package contact1;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 对jdbc的操作
 * @author Administrator
 *
 */
public class JdbcUtil {
    private static String url = null;
    private static String user = null;
    private static String password = null;
    private static String driverClass = null;
    
    /**
     * 静态代码块中(只加载一次)
     */
    static{
        try {
            //读取db.properties文件
            Properties props = new Properties();
            /**
             *  . 代表java命令运行的目录
             *  在java项目下,. java命令的运行目录从项目的根目录开始
             *  在web项目下,  . java命令的而运行目录从tomcat/bin目录开始
             *  所以不能使用点.
             */
            //FileInputStream in = new FileInputStream("./src/db.properties");
            
            /**
             * 使用类路径的读取方式
             *  / : 斜杠表示classpath的根目录
             *     在java项目下,classpath的根目录从bin目录开始
             *     在web项目下,classpath的根目录从WEB-INF/classes目录开始
             */
            InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
            
            //加载文件
            props.load(in);
            //读取信息
            url = props.getProperty("url");
            user = props.getProperty("user");
            password = props.getProperty("password");
            driverClass = props.getProperty("driverClass");
            
            
            //注册驱动程序
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("驱程程序注册出错");
        }
    }

    /**
     * 抽取获取连接对象的方法
     */
    public static Connection getConnection(){
        try {
            Connection conn = DriverManager.getConnection(url, user, password);
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    
    /**
     * 释放资源的方法
     */
    public static void close(Connection conn,Statement stmt){
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
    
    public static void close(Connection conn,Statement stmt,ResultSet rs){
        if(rs!=null)
            try {
                rs.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw new RuntimeException(e1);
            }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
}}
View Code
package contact1;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 对jdbc的操作
 * @author Administrator
 *
 */
public class JdbcUtil {
    private static String url = null;
    private static String user = null;
    private static String password = null;
    private static String driverClass = null;
    
    /**
     * 静态代码块中(只加载一次)
     */
    static{
        try {
            //读取db.properties文件
            Properties props = new Properties();
            /**
             *  . 代表java命令运行的目录
             *  在java项目下,. java命令的运行目录从项目的根目录开始
             *  在web项目下,  . java命令的而运行目录从tomcat/bin目录开始
             *  所以不能使用点.
             */
            //FileInputStream in = new FileInputStream("./src/db.properties");
            
            /**
             * 使用类路径的读取方式
             *  / : 斜杠表示classpath的根目录
             *     在java项目下,classpath的根目录从bin目录开始
             *     在web项目下,classpath的根目录从WEB-INF/classes目录开始
             */
            InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
            
            //加载文件
            props.load(in);
            //读取信息
            url = props.getProperty("url");
            user = props.getProperty("user");
            password = props.getProperty("password");
            driverClass = props.getProperty("driverClass");
            
            
            //注册驱动程序
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("驱程程序注册出错");
        }
    }

    /**
     * 抽取获取连接对象的方法
     */
    public static Connection getConnection(){
        try {
            Connection conn = DriverManager.getConnection(url, user, password);
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    
    /**
     * 释放资源的方法
     */
    public static void close(Connection conn,Statement stmt){
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
    
    public static void close(Connection conn,Statement stmt,ResultSet rs){
        if(rs!=null)
            try {
                rs.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw new RuntimeException(e1);
            }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
}}
View Code

3.操作通讯录

  1)接口

package contact1;

import java.util.List;
/**
 * 操作联系人接口
 * @author Administrator
 *
 */
public interface ContactDao {
    public void addContact(Contact contact);//添加联系人
    public void updateContact(Contact contact);//修改联系人
    public void deleteContact(String id);//删除联系人
    public List<Contact> findAll();  //查询所有联系人
    public Contact findById(String id);//根据编号查询联系人
    public boolean checkContact(String name);//根据姓名查询是否重复
}
View Code

  2)面向xml存储数据的实现类,面向MySql数据库的实现类

package contact1;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class ContactDaoImpl implements ContactDao {
    /**
     * 添加联系人
     */
    public void addContact(Contact contact) {
        try {
            File file = new File("e:/contact.xml");
            Document doc = null;
            Element rootElem = null;
            if(!file.exists()){
                /**
                 * 需求: 把contact对象保存到xml文件中
                 */
                //如果没有xml文件,则创建xml文件
                doc = DocumentHelper.createDocument();
                //创建根标签
                rootElem = doc.addElement("contactList");
            }else{
                //如果有xml文件,则读取xml文件
                doc = XMLUtil.getDocument();
                //如果有xml文件,读取根标签
                rootElem = doc.getRootElement();
            }

            //添加contact标签
            /**
             * <contact id="1">
                    <name>eric</name>
                    <gender>男</gender>
                    <age>20</age>
                    <phone>1343333</phone>
                    <email>eric@qq.com</email>
                    <qq>554444</qq>
                </contact>
             */
            Element contactElem = rootElem.addElement("contact");
            
            /**
             * 由系统自动生成随机且唯一的ID值,赋值给联系人
             */
            String uuid = UUID.randomUUID().toString().replace("-","");
            
            contactElem.addAttribute("id", uuid);
            contactElem.addElement("name").setText(contact.getName());
            contactElem.addElement("gender").setText(contact.getGender());
            contactElem.addElement("age").setText(contact.getAge()+"");
            contactElem.addElement("phone").setText(contact.getPhone());
            contactElem.addElement("email").setText(contact.getEmail());
            contactElem.addElement("qq").setText(contact.getQq());
            
            //把Document写出到xml文件
            XMLUtil.write2xml(doc);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除联系人
     */
    public void deleteContact(String id) {
        try {
            //1.读取xml文件
            Document doc = XMLUtil.getDocument();
            //2.查询需要删除id的contact
            Element contactElem = (Element)doc.selectSingleNode("//contact[@id='"+id+"']");
            //删除标签
            if(contactElem!=null){
                contactElem.detach();
            }
            
            //3.把Document写出到xml文件
            XMLUtil.write2xml(doc);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询所有联系人
     */
    public List<Contact> findAll() {
        //1.读取xml文件
        Document doc = XMLUtil.getDocument();
        
        //2.创建List对象
        List<Contact> list = new ArrayList<Contact>();
        //3.读取contact标签
        @SuppressWarnings("unchecked")
        List<Element> conList = (List<Element>)doc.selectNodes("//contact");
        for(Element e:conList){
            //创建COntact对象
            Contact c = new Contact();
            c.setId(e.attributeValue("id"));
            c.setName(e.elementText("name"));
            c.setGender(e.elementText("gender"));
            c.setAge(Integer.parseInt(e.elementText("age")));
            c.setPhone(e.elementText("phone"));
            c.setEmail(e.elementText("email"));
            c.setQq(e.elementText("qq"));
            //把Contact放入list中
            list.add(c);
        }
        return list;
    }

    /**
     * 根据编号查询联系人
     */
    public Contact findById(String id) {
        Document doc = XMLUtil.getDocument();
        Element e = (Element)doc.selectSingleNode("//contact[@id='"+id+"']");
        
        Contact c = null;
        if(e!=null){
            //创建COntact对象
            c = new Contact();
            c.setId(e.attributeValue("id"));
            c.setName(e.elementText("name"));
            c.setGender(e.elementText("gender"));
            c.setAge(Integer.parseInt(e.elementText("age")));
            c.setPhone(e.elementText("phone"));
            c.setEmail(e.elementText("email"));
            c.setQq(e.elementText("qq"));
        }
        return c;
    }

    /**
     * 修改联系人
     */
    public void updateContact(Contact contact) {
        /**
         * 需求: 修改id值为2的联系人
         *     1)查询id值为2的contact标签
         *  2)修改contact标签的内容
         */
        try {
            //1.读取xml文件
            Document doc = XMLUtil.getDocument();
            
            Element contactElem = (Element)doc.selectSingleNode("//contact[@id='"+contact.getId()+"']");
            
            //2.修改contact标签内容
            contactElem.element("name").setText(contact.getName());
            contactElem.element("gender").setText(contact.getGender());
            contactElem.element("age").setText(contact.getAge()+"");
            contactElem.element("phone").setText(contact.getPhone());
            contactElem.element("email").setText(contact.getEmail());
            contactElem.element("qq").setText(contact.getQq());
            
            //3.把Document写出到xml文件
            XMLUtil.write2xml(doc);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    public static void main(String[] args) {
        //测试UUID
        String uuid = UUID.randomUUID().toString().replace("-","");
        System.out.println(uuid);
    }

    /**
     * true:重复
     * false:不重复
     */
    public boolean checkContact(String name) {
        //查询name标签的内容和传入的name值是否一致?
        Document doc = XMLUtil.getDocument();
        Element nameElem = (Element)doc.selectSingleNode("//name[text()='"+name+"']");
        if(nameElem!=null){
            return true;
        }else{
            return false;
        }
    }

}
View Code
package contact1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ContactDaoMySQLImpl implements ContactDao{
    /**
     * 添加联系人
     */
    public void addContact(Contact contact) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try{
            //获取连接
            conn = JdbcUtil.getConnection();
            
            String sql = "INSERT INTO contact(id,NAME,gender,age,phone,email,qq) VALUES(?,?,?,?,?,?,?)";
            
            //创建PreparedStatement
            stmt = conn.prepareStatement(sql);
            
            String id = UUID.randomUUID().toString().replace("-", "");
            //设置参数
            stmt.setString(1, id);
            stmt.setString(2, contact.getName());
            stmt.setString(3, contact.getGender());
            stmt.setInt(4, contact.getAge());
            stmt.setString(5, contact.getPhone());
            stmt.setString(6, contact.getEmail());
            stmt.setString(7, contact.getQq());
            
            //执行
            stmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            JdbcUtil.close(conn, stmt);
        }
    }

    public boolean checkContact(String name) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try{
            //获取连接
            conn = JdbcUtil.getConnection();
            
            String sql = "SELECT * FROM contact where name=?";
            
            //创建PreparedStatement
            stmt = conn.prepareStatement(sql);
            
            stmt.setString(1, name);
    
            //执行
            rs = stmt.executeQuery();
            if(rs.next()){
                return true;
            }else{
                return false;
            }
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            JdbcUtil.close(conn, stmt ,rs);
        }
    }

    public void deleteContact(String id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try{
            //获取连接
            conn = JdbcUtil.getConnection();
            
            String sql = "DELETE FROM contact WHERE id=?";
            
            //创建PreparedStatement
            stmt = conn.prepareStatement(sql);
            
            //设置参数
            stmt.setString(1, id);
            
            //执行
            stmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            JdbcUtil.close(conn, stmt);
        }
    }

    public List<Contact> findAll() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try{
            //获取连接
            conn = JdbcUtil.getConnection();
            
            String sql = "SELECT * FROM contact";
            
            //创建PreparedStatement
            stmt = conn.prepareStatement(sql);
    
            //执行
            rs = stmt.executeQuery();
            List<Contact> list = new ArrayList<Contact>();
            while(rs.next()){
                Contact c = new Contact();
                c.setId(rs.getString("id"));
                c.setName(rs.getString("name"));
                c.setGender(rs.getString("gender"));
                c.setAge(rs.getInt("age"));
                c.setPhone(rs.getString("phone"));
                c.setEmail(rs.getString("email"));
                c.setQq(rs.getString("qq"));
                list.add(c);
            }
            return list;
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            JdbcUtil.close(conn, stmt ,rs);
        }
    }

    public Contact findById(String id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try{
            //获取连接
            conn = JdbcUtil.getConnection();
            
            String sql = "SELECT * FROM contact where id=?";
            
            //创建PreparedStatement
            stmt = conn.prepareStatement(sql);
            
            stmt.setString(1, id);
    
            //执行
            rs = stmt.executeQuery();
            Contact c = null;
            if(rs.next()){
                c = new Contact();
                c.setId(rs.getString("id"));
                c.setName(rs.getString("name"));
                c.setGender(rs.getString("gender"));
                c.setAge(rs.getInt("age"));
                c.setPhone(rs.getString("phone"));
                c.setEmail(rs.getString("email"));
                c.setQq(rs.getString("qq"));
            }
            return c;
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            JdbcUtil.close(conn, stmt ,rs);
        }
    }

    /**
     * 修改
     */
    public void updateContact(Contact contact) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try{
            //获取连接
            conn = JdbcUtil.getConnection();
            
            String sql = "UPDATE contact SET NAME=?,gender=?,age=?,phone=?,email=?,qq=? WHERE id=?";
            
            //创建PreparedStatement
            stmt = conn.prepareStatement(sql);

            //设置参数
            stmt.setString(1, contact.getName());
            stmt.setString(2, contact.getGender());
            stmt.setInt(3, contact.getAge());
            stmt.setString(4, contact.getPhone());
            stmt.setString(5, contact.getEmail());
            stmt.setString(6, contact.getQq());
            stmt.setString(7, contact.getId());
            
            //执行
            stmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            JdbcUtil.close(conn, stmt);
        }

    }

}
View Code
XmlUtil
package contact1;

import java.io.File;
import java.io.FileOutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * xml操作类
 * @author Administrator
 *
 */
public class XMLUtil {
    /**
     * 读取xml文档方法
     * @return
     */
    public static Document getDocument(){
        try {
            Document doc = new SAXReader().read(new File("e:/contact.xml"));
            return doc;
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    

    /**
     * 写出到xml文档中
     */
    public static void write2xml(Document doc){
        try {
            FileOutputStream out = new FileOutputStream("e:/contact.xml");
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter writer = new XMLWriter(out,format);
            writer.write(doc);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
View Code

  3)自定义的重名异常类

package contact1;

public class NameRepeatException extends Exception{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public NameRepeatException(String msg){
        super(msg);
    }
}
View Code

4.web项目逻辑层代码

  1)增删改接口:

package contact1;

import java.util.List;
/**
 * Servlet中要操作的接口
 * @author Administrator
 *
 */
public interface ContactService {
    public void addContact(Contact contact)throws NameRepeatException;//添加联系人
    public void updateContact(Contact contact);//修改联系人
    public void deleteContact(String id);//删除联系人
    public List<Contact> findAll();  //查询所有联系人
    public Contact findById(String id);//根据编号查询联系人
}
View Code

  2)实现接口的服务类

package contact1;

import java.util.List;

/**
 * 处理 项目中出现的业务逻辑
 * @author Administrator
 *
 */
public class ContactServiceImpl implements ContactService{
    //ContactDao dao = new ContactDaoImpl();
        ContactDao dao = new ContactDaoMySQLImpl();
        
        public void addContact(Contact contact) throws NameRepeatException {
            //执行业务逻辑判断
            if(dao.checkContact(contact.getName())){
                //重复
                /**
                 * 注意: 如果业务层方法出现任何业务异常,则返回标记(自定义异常)到servlet
                 */
                throw new NameRepeatException("姓名重复,不可使用");
            }
            //如果不重复,才执行添加方法
            dao.addContact(contact);
        }

        public void deleteContact(String id) {
            dao.deleteContact(id);
        }

        public List<Contact> findAll() {
            return dao.findAll();
        }

        public Contact findById(String id) {
            return dao.findById(id);
        }

        public void updateContact(Contact contact) {
            dao.updateContact(contact);
        }
}
View Code

5.Servletweb项目逻辑层

1.AddContactServlet
package Servlet;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import contact1.Contact;
import contact1.ContactService;
import contact1.ContactServiceImpl;
import contact1.NameRepeatException;

public class AddContactServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //接受参数
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String age = request.getParameter("age");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String qq = request.getParameter("qq");
        //调用逻辑
        Contact contact = new Contact();
        contact.setName(name);
        contact.setGender(gender);
        contact.setAge(Integer.parseInt(age));
        contact.setPhone(phone);
        contact.setEmail(email);
        contact.setQq(qq);
        ContactService service = new ContactServiceImpl();
        try {
            service.addContact(contact);//添加的时候可能添加重名的所有生命这个异常
        } catch (NameRepeatException e) {
            //处理自定义业务异常类
            request.setAttribute("msg", e.getMessage());
            //这里跳转是因为有需要保存的
            request.getRequestDispatcher("/addContact.jsp").forward(request, response);
            return;
        }
        //跳转页面不需要保存是么所以是重定向
        response.sendRedirect(request.getContextPath()+"/ListContactServlet");
    }

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

}
DeleContactServelt
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import contact1.ContactService;
import contact1.ContactServiceImpl;

public class DeleContactServlet extends HttpServlet {

    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //1获得参数
            String id = request.getParameter("id");
            //2.处理业务逻辑
            ContactService service = new ContactServiceImpl();
            service.deleteContact(id);
            //3.跳转页面这里是重定向不是跳转了因为这里不需要保存是么东西在request中了用重定向好些
            response.sendRedirect(request.getContextPath()+"/ListContactServlet");
    }

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

}
ListContactServlet
package Servlet;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import contact1.Contact;
import contact1.ContactService;
import contact1.ContactServiceImpl;

public class ListContactServlet extends HttpServlet {

    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //从数据库中获得
        ContactService service = new ContactServiceImpl();
        List<Contact> list = service.findAll();
        //将数据保存到requset域对象
        request.setAttribute("contacts", list);
        //跳转到jsp页面
        request.getRequestDispatcher("/listContact.jsp").forward(request, response);        
    }

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

}
QueryContactServlet
package Servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import contact1.Contact;
import contact1.ContactService;
import contact1.ContactServiceImpl;

/**
 * 修改一列时,先获得者列数据
 * @author Administrator
 *
 */
public class QueryContactServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.接收id
        String id=request.getParameter("id");
        //2.调用service根据id查询联系人的方法
        ContactService service = new ContactServiceImpl();
        Contact contact = service.findById(id);
        //3.查询结果放到request对象中去
        request.setAttribute("contact", contact);
        //4.跳转到更新页面
        request.getRequestDispatcher("/updateContact.jsp").forward(request, response);
    }

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

}
UpdateContextServlet
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import contact1.Contact;
import contact1.ContactService;
import contact1.ContactServiceImpl;

public class UpdateContextServlet extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //1.接收参数
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String age = request.getParameter("age");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String qq = request.getParameter("qq");
        
        //封装成Contact对象
        Contact contact = new Contact();
        contact.setId(id);
        contact.setName(name);
        contact.setGender(gender);
        contact.setAge(Integer.parseInt(age));
        contact.setPhone(phone);
        contact.setEmail(email);
        contact.setQq(qq);
        //业务逻辑
        ContactService service = new ContactServiceImpl();
        service.updateContact(contact);
        //跳转不需要保存是么就可以用重定向了
        response.sendRedirect(request.getContextPath()+"/ListContactServlet");
        
    }

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

6.连接数据库参数的配置文件

db.properties

url=jdbc:mysql:thin:@127.0.0.1:3306:contactsys_web
user=root
password=mysql
driverClass=com.mysql.jdbc.Driver
View Code

7.jsp

addContact.jsp

addContact.jsp
<%@ page language="java" import="java.util.*,contact1.Contact" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>添加联系人</title>
</head>
  <body>
      <center><h3>添加联系人</h3></center>
      <form action="${pageContext.request.contextPath }/AddContactServlet" method="post">
          <table align="center" border="1" width="400xp">
              <tr>
                  <th>姓名</th>
                  <td><input type="text" name="name"/><font color="red">${msg }</font></td>
              </tr>
              <tr>
                   <th>性别</th>
                   <td>
                    <input type="radio" name="gender" value=""/><input type="radio" name="gender" value=""/></td>
            </tr>
            <tr>
                    <th>年龄</th>
                <td><input type="text" name="age"/></td>
              </tr>
            <tr>
                <th>电话</th>
                  <td><input type="text" name="phone"/></td>
              </tr>
            <tr>
                <th>邮箱</th>
                  <td><input type="text" name="email"/></td>
            </tr>
                <tr>
                <th>QQ</th>
                  <td><input type="text" name="qq"/></td>
            </tr>
               <tr>
                  <td colspan="2" align="center">
                <input type="submit" value="保存"/>&nbsp;
                  <input type="reset" value="重置"/></td>
            </tr>
          </table>
      </form>
  </body>
</html>
View Code

listContact.jsp

<%@ page language="java" import="java.util.*,contact1.Contact" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>查询所有联系人</title>
<style type="text/css">
    table td{
        /* 文字居中 */
        text-align: center;
    }
    table{
        border-collapse: collapse;
    }
</style>
</head>
  <body>
      <center><h3>查询所有人</h3></center>
      <table align="center" border="1" width="700px">
          <tr>
            <th>编号</th>
            <th>姓名</th>
               <th>性别</th>
               <th>年龄</th>
            <th>电话</th>
            <th>邮箱</th>
            <th>QQ</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${contacts }" var="con" varStatus="varSta">
            <tr>
                <td>${varSta.count}</td>
                <td>${con.name}</td>
                <td>${con.gender}</td>
                <td>${con.age}</td>
                <td>${con.phone}</td>
                <td>${con.email}</td>
                <td>${con.qq}</td>
                <td><a href="${pageContext.request.contextPath }/QueryContactServlet?id=${con.id}">修改</a> &nbsp;<a href="${pageContext.request.contextPath }/DeleteContactServlet?id=${con.id}">删除</a></td>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="8" align="center"><a href="${pageContext.request.contextPath }//addContact.jsp">[添加联系人]</a></td>
        </tr>
      </table>
  </body>
</html>
View Code
<%@ page language="java" import="java.util.*,contact1.Contact" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>修改联系人</title>
</head>
  <body>
    <center><h3>修改联系人</h3></center>
    <form action="${pageContext.request.contextPath }/UpdateContactServlet" method="post">
        <input type="hidden" name="id" value="${contact.id }" />
        <table align="center" border="" width="300px">
            <tr>
                <th>姓名</th>
                   <td><input type="text" name="name" value="${contact.name }"/></td>
            </tr>
            <tr>
                <th>性别</th>
                   <td>
                <input type="radio" name="gender" value=""  <c:if test="${contact.gender=='男' }">checked="checked"</c:if> /><input type="radio" name="gender" value=""  <c:if test="${contact.gender=='女' }">checked="checked"</c:if> /></td>
            </tr>
            <tr>
                <th>年龄</th>
                <td><input type="text" name="age" value="${contact.age }"/></td>
            </tr>
            <tr>
                <th>电话</th>
                <td><input type="text" name="phone" value="${contact.phone }"/></td>
            </tr>
            <tr>
                <th>邮箱</th>
                <td><input type="text" name="email" value="${contact.email }"/></td>
            </tr>
            <tr>
                <th>QQ</th>
                <td><input type="text" name="qq" value="${contact.qq }"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                <input type="submit" value="保存"/>&nbsp;
                <input type="reset" value="重置"/></td>
            </tr>
        </table>
    </form>
  </body>
</html>
View Code
原文地址:https://www.cnblogs.com/xiaoping1993/p/6839296.html