6.java设计模式

jsp的设计模式与案例
  jsp的两种开发模式
  model1(jsp+javabean)
    jsp:负责业务逻辑和内容的展示
    javabean:数据的封装及对数据的操作
  model2(jsp+servlet+javabean)
    jsp:展示
    servlet:业务逻辑处理
    javabean:数据的封装及对数据的操作

javabean:
  可重用的组件
  要求:
    必须是public class
    一般把它的字段私有,提供get/set/is方法
    必须有一个空参构造器
    一般还是实现序列化接口

public class User {
	private String username;
	private String password;
	private Integer age;
	private Date birthday;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String toString(){
		return this.username+":"+this.password+":"+this.age+":"+this.birthday;
	}
}

 

  在model1下使用javabean(了解)
    <jsp:useBean id="user" class="domain.User"></jsp:useBean> ><!-- id是给javabean起个 名字 -->
    <jsp:setProperty property="username" name="user"/> <!-- setProperty 相当于调用setUsername -->
    username:<jsp:getProperty property="username" name="user"/><br/><!-- 相当于调用getUsername -->

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
	<form action="${pageContext.request.contextPath }/model1/model1.jsp" method="post">
		用户名:<input name="username" type="text"><br/>
		密码:<input name="password" type="password"><br/>
		<input type="submit">
	</form> 
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
	<jsp:useBean id="user" class="domain.User"></jsp:useBean> ><!-- id是给javabean起个 名字 -->
	<jsp:setProperty property="username" name="user"/> <!-- setProperty 相当于调用setUsername -->
	<jsp:setProperty property="password" name="user"/> <!--name为id -->
	<hr/>
	username:<jsp:getProperty property="username" name="user"/><br/><!-- 相当于调用getUsername -->
	password:<jsp:getProperty property="password" name="user"/>
</body>
</html>

  

  在model2下使用javabean
    beanUtils的使用步骤:
      1.导入jar包 commons-beanutils-1.8.3.jar和commons-logging-1.1.1.jar
      2.在java代码中直接使用beanutils.populate(对象,map)
    自定义转换器的步骤:
      1.自定义一个类,实现Converter
      2.重写方法
        public Object convert(Class type, Object value) {
          System.out.println(type); //class java.util.Date,就是要转换成的类型
          System.out.println(value); //2009-10-2,就是页面上获取的内容
          return null;//return 跟的是给bean的值
        }
      3.注册自定义转换器
        ConvertUtils.register(converter,clazz)
        converter:自定义的转换器    
        clazz:要转换成的类型

/**
 * 模拟getParameterMap()
 * @author mjl
 *
 */
public class Test {

    public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
        // TODO Auto-generated method stub
        Map<String,String[]> map=new HashMap();
        map.put("username", new String[]{"tom"});
        map.put("password",new String[]{ "123"});
        
        User user=new User();
        map2Bean(user,map);
        System.out.println(user);
        
    }

    private static void map2Bean(User user, Map<String, String[]> map) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
        //获取所有方法
        Method[] methods=user.getClass().getDeclaredMethods();
        
        //获取map中所有键
        Set<String> key=map.keySet();
        
        //遍历方法
        for (Method method : methods) {
            
            //遍历键
            for (String name : key) {
                if(("set"+name).equalsIgnoreCase(method.getName())){
                    
                    //invoke(class, 参数)
                    method.invoke(user, map.get(name));
                }
            }
        }
    }    

}

 

public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        
        //1.获取参数
        Map<String,String[]> map=request.getParameterMap();
        User user=new User();
        try {
            //Converter只支持一些基本的类型
            //但当属性值不是8种基本类型,而我们赋String类型,则需要重写ConvertUtils.register方法
            ConvertUtils.register(new MyConverter(), java.util.Date.class);
            
            //map和user相关联
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(user);
    }
}


/**
 * 自定义转换器
 * @author mjl
 *
 */
public class MyConverter implements Converter{

    @Override
    /*
     * 传入要转化成的类和提交的待转换参数
     * @see org.apache.commons.beanutils.Converter#convert(java.lang.Class, java.lang.Object)
     */
    public Object convert(Class type, Object value) {
        System.out.println(type+"-------"+value); //class java.util.Date-------2009-10-2
        
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        try {
            return df.parse((String)value);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return null;
    }

}

 

MVC设计模式:
  model:模型 封装数据,封装对数据库的操作
  view:视图 展示。jsp
  controller:控制 接收参数,封装业务逻辑
  java的设计模式:
    web:
      主要功能:接收参数,调用service,页面的跳转,显示信息
    service(业务逻辑层):
      主要功能:处理业务逻辑,调用dao的操作
    dao(data access objec):数据访问对象
      主要功能:对数据库的操作 crud

案例:注册

注册表单

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>bookStore 商城-商品信息展示</title>
    </head>
    <body>
        <!-- head 一行两列的表格-->
        <%@include file="/public/head.jsp" %>
        
        <!-- menu 一行一列的表格-->
        <%@include file="/public/menu.jsp" %>
        
        <!-- search 一行一列的表格 -->
        <div id="search">
            <table width="100%" bgcolor="#B6B684">
                <tr align="right">
                    <td>
                        search
                        <input type="text"/>
                        <input type="button" value="搜索"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    </td>
                </tr>
            </table>
        </div>
        
        <!-- content -->
        <div id="content">
            <form action="${pageContext.request.contextPath}/regist" method="post">
                <table align="center" bgcolor="#FFFFF4" width="60%">
                    <tr>
                        <td>
                            <h1>新会员注册<font color="red">${regist_msg }</font></h1>
                            <table align="center">
                                <tr>
                                    <td align="right" >会员邮箱:</td>
                                    <td>
                                        <input type="text" name="email"/>
                                    </td>
                                    <td align="left">
                                        <font color="#ff0000">${map.email_msg }</font>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="right">会员名:</td>
                                    <td>
                                        <input type="text" name="username" class="txtinput"/>
                                    </td>
                                    <td align="left">
                                        <font color="#ff0000"></font>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="right">密码:</td>
                                    <td>
                                        <input type="password" name="password" class="txtinput"/>
                                    </td>
                                    <td align="left">
                                        <font color="#ff0000"></font>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="right">重复密码:</td>
                                    <td>
                                        <input type="text" name="repassword"/>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="right">性别:</td>
                                    <td>
                                        <input type="radio" name="sex" value="男"/><input type="radio" name="sex" value="女"/></td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td align="right">联系电话:</td>
                                    <td>
                                        <input type="text" name="telephone"/>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="right">个人介绍:</td>
                                    <td>
                                        <input type="textarea" name="introduce"/>
                                    </td>
                                </tr>
                            </table>
                            <h1>注册校验</h1>
                            <table align="center" width="80%" cellspacing="2">
                                <tr>
                                    <td align="right">输入校验码:</td>
                                    <td>
                                        <input type="text" name="checkcode" class="txtinput"/>
                                    </td>
                                    <td>${requestScope["code.msg"] }</td> <!-- code.msg,单独不可以写进去,.表示get。用域对象表示出来 -->
                                </tr>
                                <tr>
                                    <td>&nbsp;</td>
                                    <td colspan="2">
                                        <img src="${pageContext.request.contextPath }/code" id="imgId" alt="验证码" class="txtinput" style="height:30px"/>
                                        <a href="javascript:void(0)" onclick="changeCode()">看不清?换一张</a>
                                        <!-- 表示这个链接不做跳转动作,执行onClick事件。 -->
                                    </td>
                                </tr>
                                <tr>
                                    <td align="center" colspan="3">
                                        <input value="同意并提交" style="background:orange;height:30px;width:100px;text-align:center;" type="submit"/>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </form>
            
        </div>
        
        <!-- foot 两行两列的表格-->
        <div id="foot">
            <table width="100%" bgcolor="#EFEEDC">
                <tr>
                    <td rowspan="2" align="center">
                        <img src="images/case1/logo.png" alt="图书商城"/>
                    </td>
                    <td>CONTACT US</td>
                </tr>
                <tr>
                    <td>
                        copyright 2008&copyrightBookStore All Rights RESERVED
                    </td>
                </tr>
            </table>
        </div>
        
        <table width="100%">
            <tr>
                <td></td>
            </tr>
        </table>
    </body>
<script type="text/javascript">
    function changeCode(){
        var imgObj=document.getElementById("imgId");
        imgObj.src="${pageContext.request.contextPath}/code?i="+Math.random();
    }
</script>

</html>


head.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- head 一行两列的表格-->
<div id="head">
<table width="100%">
<tr>
<td>
<img src="images/case1/logo.png" alt="图书商城"/>
</td>
<td align="right"">
<img src="images/case1/cart.gif" alt="购物车"/>
购物车 | 帮助中心 | 我的账户 | 新用户注册 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</td>
</tr>
</table>
</div>

 

menu.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- menu 一行一列的表格-->
<div id="menu">
<table width="100%" bgcolor="#1c3F09">
<tr align="center">
<td>
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;

<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;
<a><font color="#fff">文学</font></a> &nbsp;&nbsp;&nbsp;

<a><font color="#ff0">显示全部商品目录</font></a>
</td>
</tr>
</table>
</div>

 

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<c:if test="${empty user }">
请先<a href="${pageContext.request.contextPath }/login.jsp">登录</a>
</c:if>
<c:if test="${!empty user }">
${user.username }:欢迎回来!
</c:if>
</body>
</html>

 

 

Servlet

package web.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import domain.User;
import exception.UserRegistException;
import service.UserService;

public class RegistServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        
        /*
         * 作用:首先判断验证码
         *     若验证码不一致,返回错误信息(regist.jsp) 提示信息(验证码错误) request
         *     验证码一致,封装参数,调用userservice
         */
        
        //1.获取验证码 
        //1.1获取页面上验证码
        String code=request.getParameter("checkcode");
        
        //1.2获取session域中的验证码
        String sessionCode=(String) request.getSession().getAttribute("session_code");
        request.getSession().removeAttribute("session_code"); //验证码一次性
        
        //2.判断验证码
        //输入验证码不正确
        if(!sessionCode.equalsIgnoreCase(code)){
            //加入错误信息,页面跳转
            request.setAttribute("code.msg", "验证码输入错误");
            request.getRequestDispatcher("/regist.jsp").forward(request,response);
            return;
        }
        
        //3.获取参数
        User user=new User();
        try {
            BeanUtils.populate(user, request.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //3.1数据校验
        //验证邮件
        Map<String,String> map=user.validate();
        if(map!=null && map.size()>0){
            //有错误信息
            request.setAttribute("map", map);
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
            return;
        }
        
        //4.调用userservice
        UserService userService=new UserService();
        //可能抛自定义异常
        try {
            userService.regist(user);
        } catch (UserRegistException e) {
            e.printStackTrace();
            //有异常,添加错误信息,跳转到注册页面
            request.setAttribute("regist_msg", e.getMessage());
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
        }
        
        //5.页面跳转,提示信息
        //5.1将user放到session中
        request.getSession().setAttribute("user", user);
        
        //5.2提示信息 页面跳转
        response.setHeader("refresh", "3;url="+request.getContextPath()+"/success.jsp");
        response.getWriter().print("注册成功,3秒之后跳转到首页!");
        
    }
}


public class CodeServlet extends HttpServlet {

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

        // 使用java图形界面技术绘制一张图片

        int charNum = 4;
        int width = 30 * 4;
        int height = 30;

        // 1. 创建一张内存图片
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        // 2.获得绘图对象
        Graphics graphics = bufferedImage.getGraphics();

        // 3、绘制背景颜色
        graphics.setColor(Color.YELLOW);
        graphics.fillRect(0, 0, width, height);

        // 4、绘制图片边框
        graphics.setColor(Color.BLUE);
        graphics.drawRect(0, 0, width - 1, height - 1);

        // 5、输出验证码内容
        graphics.setColor(Color.RED);
        graphics.setFont(new Font("宋体", Font.BOLD, 20));

        // 随机输出4个字符
        Graphics2D graphics2d = (Graphics2D) graphics;
        // String s = "ABCDEFGHGKLMNPQRSTUVWXYZ23456789";
        String s = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";
        Random random = new Random();
        //session中要用到
        String msg="";
        int x = 5;
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(132);
            String content = String.valueOf(s.charAt(index));
            msg+=content;
            double theta = random.nextInt(45) * Math.PI / 180;
            //让字体扭曲
            graphics2d.rotate(theta, x, 18);
            graphics2d.drawString(content, x, 18);
            graphics2d.rotate(-theta, x, 18);
            x += 30;
        }

        //放入session
        request.getSession().setAttribute("session_code", msg);
        
        // 6、绘制干扰线
        graphics.setColor(Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);

            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }

        // 释放资源
        graphics.dispose();

        // 图片输出 ImageIO
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    

    }

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

    }

}

javabean

package domain;

import java.util.HashMap;
import java.util.Map;

public class User {
    private Integer id;
    private String email;
    private String username;
    private String password;
    private String sex;
    private String introduce;
    private String telephone;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getIntroduce() {
        return introduce;
    }
    public void setIntroduce(String introduce) {
        this.introduce = introduce;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public User(Integer id, String email, String username, String password, String sex, String introduce,
            String telephone) {
        super();
        this.id = id;
        this.email = email;
        this.username = username;
        this.password = password;
        this.sex = sex;
        this.introduce = introduce;
        this.telephone = telephone;
    }
    public User() {
        super();
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", email=" + email + ", username=" + username + ", password=" + password + ", sex="
                + sex + ", introduce=" + introduce + ", telephone=" + telephone + "]";
    }
    public Map<String, String> validate() {
        //创建Map
        Map<String,String> map=new HashMap();
        
        //验证邮箱
        /*
         * 首先验证邮箱是否为空
         *     若为空,提示邮箱不能为空
         *     若不为空,继续验证邮箱是否符合格式
         *         若不符合,提示邮箱格式不争取
         *         
         */
        if(isNull(email)){
            map.put("email_msg", "邮箱不能为空");
        }else if(!checkEmail(email)){
            map.put("email_msg", "邮箱格式不合法");
        }
        
        return map;
    }
    
    /**
     * 判断邮箱格式
     *     若符合格式,返回true
     *     若不符合格式,返回false
     * @param value
     * @return bolean
     */
    private boolean checkEmail(String value) {
        if(value==null){
            return false;
        }
        //qwer@qq.com.cn
        String reg="^\\w+@\\w+(\\.\\w+)+$";
        return value.matches(reg);
    }
    /**
     * 验证是否为空
     *     若为空返回Null
     *     若不为空返回false
     * @param value
     * @return boolean
     */
    private boolean isNull(String value) {
        //^\s*&
        if(value==null){
            return true;
        }
        return value.matches("^\\s*$");
    }
    
}

UserSevice

public class UserService {
    /**
     * 用户注册
     * @param user 用户信息
     * @throws UserRegistException 
     */
    public void regist(User user) throws UserRegistException {
        //调用userdao的adduser方法
        UserDaoImpl userDao=new UserDaoImpl();
        userDao.addUser(user);
        
    }

}

UserDao

public class UserDaoImpl implements UserDao{
    /**
     * 添加用户
     * @param user 用户信息
     * @throws UserRegistException 
     * @throws SQLException 
     */
    public void addUser(User user) throws UserRegistException {
        //使用JDBC操作数据库
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        
        try {
            conn=JDBCUtils.getConnection();
            
            //编写sql
            //username,password,sex,telephone,email,introduce
            String sql="insert into user values(null,?,?,?,?,?,?)";
            
            //创建语句执行者
            ps=conn.prepareStatement(sql);
            //设置参数
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getSex());
            ps.setString(4, user.getTelephone());
            ps.setString(5, user.getEmail());
            ps.setString(6, user.getIntroduce());
            //执行sql
            int i=ps.executeUpdate();
            if(i==0){
                throw new UserRegistException("注册失败");
            }
            //处理结果
            System.out.println(i);
        } catch (SQLException e) {
            // 数据库异常
            e.printStackTrace();
            throw new UserRegistException("网络异常,请稍后再试");
        }finally{
            //释放资源
            JDBCUtils.closeResources(conn, ps, rs);
        }
    }
}

Exception

/**
 * 自定义异常
 * @author mjl
 *
 */
public class UserRegistException extends Exception{

    public UserRegistException() {
        super();
        
    }

    public UserRegistException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        
    }

    public UserRegistException(String message, Throwable cause) {
        super(message, cause);
        
    }

    public UserRegistException(String message) {
        super(message);
        
    }

    public UserRegistException(Throwable cause) {
        super(cause);
        
    }
    
}

JDBCUtils

public class JDBCUtils {

    static final String DRIVERCLASSNAME;
    static final String URL;
    static final String USER;
    static final String PASSWORD;
    
    static{
        /**
         * ResourceBundle:用于加载properties文件
         *      ResourceBundle bundle=ResourceBundle.getBundle(文件名称);
         *   通过bundle的getString(key)就可以获取指定value
         *    String url=bundle.getString("url");
         */
        ResourceBundle bundle=ResourceBundle.getBundle("jdbc"); //不需要后缀名
        DRIVERCLASSNAME=bundle.getString("driverClassName");
        URL=bundle.getString("url");
        USER=bundle.getString("user");
        PASSWORD=bundle.getString("password");
    }
    
    static{
        try {
            Class.forName(DRIVERCLASSNAME);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
  //获取连接
    public static Connection getConnection() throws SQLException{
        return DriverManager.getConnection(URL,USER,PASSWORD);
    }
    
    public static void closeResources(Connection conn,Statement st,ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

 

posted @ 2018-02-08 15:39  一日看尽长安花cxjj  阅读(144)  评论(0)    收藏  举报