大数据正式20

大数据正式20

JavaEE开发模式

  • 为什么要有JavaEE开发模式
    1. 之前的代码混在一起太乱
    2. 项目越来越大,代码结构太差
    3. 之前设计分层不清,不便于维护和扩展
    4. 。。。。。
  • 发展阶段一
    • Servlet:
      • 本质上是java代码,所以非常便于处理逻辑,但是不擅长输出界面
    • jsp:
      • 看起来像HTML,但是内部可以写java代码,是一种动态web资源开发技术,非常便于编写界面,嵌入的代码也可以用来处理部分逻辑。但是这样做的话,jsp又产生了大量的代码,又难以维护和扩展
    • javaBean+jsp
      • 这种开发模式下,jsp负责接收请求、资源调度、展示页面,javaBean负责数据的封装、数据处理、数据的持久化等操作
      • 这种模式不可避免的又在jsp里写java代码
  • 发展阶段二
    • Servlet+JavaBean+Jsp
      • Servlet:资源调度
      • JavaBean:封装数据、处理数据、持久化数据
      • Jsp:展示数据
      • MVC设计思想:
        • M:Model,模型【封装数据、处理数据】
        • V:View,视图【和用户交互】
        • C:Controller,控制器【控制程序的流转】
        • 尽量做到:这三个部分尽量相互独立,互不影响;这样可以让软件结构清晰,模块之间互不干扰,有利于软件的设计、开发和维护
  • 发展阶段三

    • 模块组装
    • mvc架构
    • JavaEE经典的三层架构

      • 分层的目的:
        1. 代码更加具有优良的结构,便于开发和调试
        2. 便于层与层的代码复用,减少代码冗余
        3. 在更改模块时可以不影响其他模块的使用,实现模块的复用
          1. mysql->oracle【只需写个新的实现类】
          2. web->android【service和dao层不需要修改】
      • 三层独立:不要将特有的对象作为参数传给其它层,否则形成入侵,耦合度形成并变高,这种耦合是有害的,应该尽量避免,实现高内聚,低耦合
      • 解耦的实现

        1. 不要互换传递层特有的对象,尽量避免。
        2. 但是再小心,层与层早晚要发生关系的,此时需要将耦合管理起来

          1. Spring框架
          2. 接口+配置文件+工厂模式

            package com.easymall.factory;
            
            import java.io.File;
            import java.io.FileInputStream;
            import java.io.FileNotFoundException;
            import java.io.IOException;
            import java.util.Properties;
            
            public class BasicFactory {
            
                private static BasicFactory factory = new BasicFactory();
                private static Properties prop = null;
            
                static {
                    prop = new Properties();
                    try {
                        prop.load(new FileInputStream(new File(BasicFactory.class
                                .getClassLoader().getResource("config.properties")
                                .getPath())));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            
                private BasicFactory() {
                    super();
                }
            
                public static BasicFactory getFactory() {
                    return factory;
                }
            
                @SuppressWarnings("unchecked")
                public <T> T getObj(Class<T> c) {
                    System.out.println(prop);
                    String name = prop.getProperty(c.getSimpleName());
                    System.out.println(name);
                    Class<?> basic = null;
                    Object obj = null;
                    try {
                        basic = Class.forName(name);
                        obj = basic.newInstance();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    return (T) obj;
                }
            }
            

javaEE三层架构流程演示

  • 注册逻辑

软件分层换底层

  • 可能影响的原因
    • HttpServlet的传递,改换成Android就蒙圈了
    • 各层之间的对象引用写死
  • 只需改相应的层即可
  • 详细看代码重构中的具体结构与相应的代码

EasyMall代码重构

  • 之前的结构
  • 重构之后的结构

重构具体代码

  • com.easymall.dao

    • UserDao

      package com.easymall.dao;
      
      import com.easymall.domain.User;
      
      public interface UserDao {
      
          /**
           * 通过用户名查询数据库中是否有该数据记录
           * 
           * @param user
           * @return 是否存在该用户名对应的数据记录
           */
          public boolean findUserByUserName(User user);
      
          /**
           * 添加用户信息
           * 
           * @param user用户信息实体
           * @return void
           */
          public void addUser(User user);
      
          /**
           * 通过账号和密码来查询数据库是否有此账号
           * 
           * @param username
           * @param password
           * @return 返回通数据库是否有此账号和密码对应的记录
           */
          public boolean findUserByNameAndPass(String username, String password);
      
      }
      
    • UserDaoImpl

      package com.easymall.dao;
      
      import java.sql.Connection;
      import java.sql.PreparedStatement;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      
      import com.easymall.domain.User;
      import com.easymall.utils.MySqlUtils;
      
      public class UserDaoImpl implements UserDao {
          Connection conn = null;
          PreparedStatement stat = null;
          ResultSet rs = null;
      
          public boolean findUserByUserName(User user) {
              try {
                  conn = MySqlUtils.getConn();
                  stat = conn.prepareStatement("select * from user where username=?");
                  stat.setString(1, user.getUsername());
                  rs = stat.executeQuery();
                  return rs.next();
              } catch (SQLException e) {
                  return false;
              } finally {
                  MySqlUtils.close(conn, stat, rs);
              }
          }
      
          public void addUser(User user) {
      
              conn = MySqlUtils.getConn();
              try {
                  stat = conn.prepareStatement("insert into user values(?,?,?,?)");
                  stat.setString(1, user.getUsername());
                  stat.setString(2, user.getPassword());
                  stat.setString(3, user.getNickname());
                  stat.setString(4, user.getEmail());
                  stat.executeUpdate();
              } catch (SQLException e) {
                  e.printStackTrace();
              } finally {
                  MySqlUtils.close(conn, stat, rs);
              }
      
          }
      
          public boolean findUserByNameAndPass(String username, String password) {
              conn = MySqlUtils.getConn();
              try {
                  stat = conn
                          .prepareStatement("select * from user where username=? and password=?");
                  stat.setString(1, username);
                  stat.setString(2, password);
                  rs = stat.executeQuery();
                  return rs.next();
              } catch (SQLException e) {
                  return false;
              } finally {
                  MySqlUtils.close(conn, stat, rs);
              }
          }
      
      }
      
  • com.easymall.domain

    • User

      package com.easymall.domain;
      
      /**
       * 注册用户
       * 
       * @author Administrator
       * 
       */
      public class User {
          private int id;
          private String username;
          private String password;
          private String nickname;
          private String email;
      
          public User() {
              super();
          }
      
          public User(int id, String username, String password, String nickname,
                  String email) {
              super();
              this.id = id;
              this.username = username;
              this.password = password;
              this.nickname = nickname;
              this.email = email;
          }
      
          public int getId() {
              return id;
          }
      
          public void setId(int id) {
              this.id = id;
          }
      
          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 getNickname() {
              return nickname;
          }
      
          public void setNickname(String nickname) {
              this.nickname = nickname;
          }
      
          public String getEmail() {
              return email;
          }
      
          public void setEmail(String email) {
              this.email = email;
          }
      
      }
      
  • com.easymall.exception

    • MsgException

      package com.easymall.exception;
      
      @SuppressWarnings("serial")
      public class MsgException extends RuntimeException {
          public MsgException() {
          }
      
          public MsgException(String msg) {
              super(msg);
          }
      }
      
  • com.easymall.factory

    • BasicFactory

      package com.easymall.factory;
      
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileNotFoundException;
      import java.io.IOException;
      import java.util.Properties;
      
      public class BasicFactory {
      
          private static BasicFactory factory = new BasicFactory();
          private static Properties prop = null;
      
          static {
              prop = new Properties();
              try {
                  prop.load(new FileInputStream(new File(BasicFactory.class
                          .getClassLoader().getResource("config.properties")
                          .getPath())));
              } catch (FileNotFoundException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
          private BasicFactory() {
              super();
          }
      
          public static BasicFactory getFactory() {
              return factory;
          }
      
          @SuppressWarnings("unchecked")
          public <T> T getObj(Class<T> c) {
              System.out.println(prop);
              String name = prop.getProperty(c.getSimpleName());
              System.out.println(name);
              Class<?> basic = null;
              Object obj = null;
              try {
                  basic = Class.forName(name);
                  obj = basic.newInstance();
              } catch (ClassNotFoundException e) {
                  e.printStackTrace();
              } catch (InstantiationException e) {
                  e.printStackTrace();
              } catch (IllegalAccessException e) {
                  e.printStackTrace();
              }
              return (T) obj;
          }
      }
      
  • com.easymall.service

    • UserService

      package com.easymall.service;
      
      import com.easymall.domain.User;
      import com.easymall.exception.MsgException;
      
      public interface UserService {
          /**
           * 注册用户
           * 
           * @param user封装了要注册用户的数据
           * @throws 注册中用户信息有误则抛出异常
           */
          void regist(User user) throws MsgException;
      
          /**
           * 查询账号是否重复
           * 
           * @param 用户实体
           * @return 返回数据库中是否有此用户名
           */
          boolean checkHasUsername(User user);
      
          /**
           * 
           * 检查用户名和密码
           * 
           * @param username
           * @param password
           * @return 返回是否存在该账户和密码
           */
          boolean checkUsernameAndPassord(String username, String password);
      
          /**
           * 添加一名用户
           * 
           * @param user
           * @return void
           */
          void addUser(User user);
      
      }
      
    • UserServiceImpl

      package com.easymall.service;
      
      import com.easymall.dao.UserDao;
      import com.easymall.domain.User;
      import com.easymall.exception.MsgException;
      import com.easymall.factory.BasicFactory;
      
      public class UserServiceImpl implements UserService {
          UserDao ud = BasicFactory.getFactory().getObj(UserDao.class);
      
          public void regist(User user) throws MsgException {
              boolean hasUser = ud.findUserByUserName(user);
              // 如果用户名重复则抛出异常
              if (hasUser) {
                  throw new MsgException("该账号已经存在!");
              } else {
                  // 如果用户名不重复则向数据库写入信息
                  ud.addUser(user);
              }
          }
      
          public boolean checkHasUsername(User user) {
              // 找到返回true,找不到返回false
              return ud.findUserByUserName(user);
          }
      
          public boolean checkUsernameAndPassord(String username, String password) {
              return ud.findUserByNameAndPass(username, password);
          }
      
          public void addUser(User user) {
              ud.addUser(user);
          }
      
      }
      
  • com.easymall.utils

    • MySqlUtils

      package com.easymall.utils;
      
      import java.sql.Connection;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import java.sql.Statement;
      
      import com.mchange.v2.c3p0.ComboPooledDataSource;
      
      public class MySqlUtils {
          // 创建数据库连接池--数据连接池只允许有一个
          private static ComboPooledDataSource cpds = new ComboPooledDataSource();
      
          // 将构造函数私有化,不允许创建该实例
          private MySqlUtils() {
              super();
          }
      
          // 获取连接
          public static Connection getConn() {
              Connection conn = null;
              try {
                  conn = cpds.getConnection();
              } catch (SQLException e) {
                  // 没有获得数据库连接的异常处理[有待详细处理]
                  throw new RuntimeException(e);
              }
              return conn;
          }
      
          // 关闭资源
          public static void close(Connection conn, Statement stat, ResultSet rs) {
              if (conn != null) {
                  try {
                      conn.close();
                  } catch (SQLException e) {
                      e.printStackTrace();
                  } finally {
                      conn = null;
                  }
              }
              if (stat != null) {
                  try {
                      stat.close();
                  } catch (SQLException e) {
                      e.printStackTrace();
                  } finally {
                      stat = null;
                  }
              }
              if (rs != null) {
                  try {
                      rs.close();
                  } catch (SQLException e) {
                      e.printStackTrace();
                  } finally {
                      rs = null;
                  }
              }
          }
      
      }
      
  • com.easymall.web

    • CheckHasUsernameServlet

      package com.easymall.web;
      
      import java.io.IOException;
      
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      import com.easymall.domain.User;
      import com.easymall.factory.BasicFactory;
      import com.easymall.service.UserService;
      
      @SuppressWarnings("serial")
      public class CheckHasUsernameServlet extends HttpServlet {
          private boolean hasUser = false;
          UserService userService = BasicFactory.getFactory().getObj(
                  UserService.class);
      
          protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                  throws ServletException, IOException {
              try {
                  // 获取用户名并解决乱码
                  String username = new String(req.getParameter("username").getBytes(
                          "iso8859-1"), "utf-8");
                  // 查询数据库中是否有此用户
                  User user = new User(-1, username, null, null, null);
                  hasUser = userService.checkHasUsername(user);
              } catch (Exception e) {
                  throw new RuntimeException(e);
              }
              // 返回json格式的数据
              System.out.println(hasUser);
              resp.getWriter().write("{\"hasUser\":" + hasUser + "}");
          }
      
          protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                  throws ServletException, IOException {
              this.doGet(req, resp);
          }
      
      }
      
    • LoginServlet

      package com.easymall.web;
      
      import java.io.IOException;
      import java.net.URLEncoder;
      
      import javax.servlet.ServletException;
      import javax.servlet.http.Cookie;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.servlet.http.HttpSession;
      
      import com.easymall.factory.BasicFactory;
      import com.easymall.service.UserService;
      
      @SuppressWarnings("serial")
      public class LoginServlet extends HttpServlet {
          // 处理逻辑
          UserService us = BasicFactory.getFactory().getObj(
                  UserService.class);
      
          public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              this.doPost(request, response);
          }
      
          public void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              // 解决乱码
              request.setCharacterEncoding("utf-8");
              response.setCharacterEncoding("utf-8");
              response.setContentType("text/html;charset=utf-8");
      
              // 获取用户名和密码
              String username = request.getParameter("username") == null ? ""
                      : request.getParameter("username");
              String password = request.getParameter("password") == null ? ""
                      : request.getParameter("password");
              // 处理记住用户名的逻辑
              if ("true".equals(request.getParameter("remname"))) {
                  System.out.println("sdfg");
                  Cookie cookie = new Cookie("remname", URLEncoder.encode(username,
                          "utf-8"));
                  cookie.setMaxAge(60 * 60 * 24 * 30);
                  cookie.setPath(request.getContextPath());
                  response.addCookie(cookie);
              } else {// 不保存--删除Cookie
                  Cookie cookie = new Cookie("remname", "");
                  cookie.setMaxAge(0);
                  cookie.setPath(request.getContextPath());
                  response.addCookie(cookie);
              }
              // 检查用户名和密码
              if (us.checkUsernameAndPassord(username, password)) {
                  // 获取session
                  HttpSession session = request.getSession();
                  // 在session中加入相应的标记
                  session.setAttribute("username", username);
                  // 回到主页
                  response.getWriter().write("登录成功!正在跳转。。。");
                  response.setHeader("refresh", "2;url=" + request.getContextPath()
                          + "/index.jsp");
              } else {
                  response.addHeader("refresh", "0;url=" + request.getContextPath()
                          + "/login.jsp?msg=" + URLEncoder.encode("账号密码错误!", "utf-8"));
              }
          }
      }
      
    • LogOutServlet

      package com.easymall.web;
      
      import java.io.IOException;
      
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      @SuppressWarnings("serial")
      public class LogOutServlet extends HttpServlet {
          public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              this.doPost(request, response);
          }
      
          public void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              // 解决乱码
              response.setCharacterEncoding("utf-8");
              response.setContentType("text/html;charst=utf-8");
              // 杀死session--先进行判断用户是否有session--防止恶意攻击
              if (request.getSession(false) != null) {
                  request.getSession(false).invalidate();
              }
              // 回到主页
              // 注销中。。。
              response.getWriter().write("注销成功!正在跳转到主页。。。");
              response.setHeader("refresh", "2;url=" + request.getContextPath()
                      + "/index.jsp");
          }
      }
      
    • RegistServlet

      package com.easymall.web;
      
      import java.io.IOException;
      
      import javax.servlet.ServletContext;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      import com.easymall.domain.User;
      import com.easymall.exception.MsgException;
      import com.easymall.factory.BasicFactory;
      import com.easymall.service.UserService;
      
      @SuppressWarnings("serial")
      public class RegistServlet extends HttpServlet {
          UserService us = BasicFactory.getFactory().getObj(UserService.class);
      
          public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              try {
                  // 0.获取应用参数
                  ServletContext sc = this.getServletContext();
                  String encode = sc.getInitParameter("encode");
      
                  // 1.解决requestpost请求乱码 解决response输出数据乱码
                  request.setCharacterEncoding(encode);
                  response.setCharacterEncoding(encode);
                  response.setContentType("text/html;charset=" + encode);
      
                  // 2.获取请求参数
                  String username = request.getParameter("username");
                  String password = request.getParameter("password");
                  String password2 = request.getParameter("password2");
                  String nickname = request.getParameter("nickname");
                  String email = request.getParameter("email");
                  String valistr = request.getParameter("valistr");
      
                  // 验证码校验--获取请求参数的验证码,获取session中的验证码,对比并进行相应的操作
                  String valistr2 = (String) request.getSession().getAttribute(
                          "valistr2");
                  if (valistr == null || valistr2 == null
                          || !valistr.equals(valistr2)) {
                      request.setAttribute("msg", "验证码不正确!");
                      request.getRequestDispatcher(
                              request.getContextPath() + "/regist.jsp").forward(
                              request, response);
                      return;
                  }
                  // 3.检查数据有效性 如果有问题 向浏览器报错
                  if (username == null || "".equals(username)) {
                      throw new MsgException("用户名不能为空!");
                  }
      
                  if (password == null || "".equals(password)) {
                      throw new MsgException("密码不能为空!");
                  }
      
                  if (password2 == null || "".equals(password2)) {
                      throw new MsgException("确认密码不能为空!");
                  }
      
                  if (!password.equals(password2)) {
                      throw new MsgException("两次密码不一致!");
                  }
      
                  if (nickname == null || "".equals(nickname)) {
                      throw new MsgException("昵称不能为空!");
                  }
      
                  if (email == null || "".equals(email)) {
                      throw new MsgException("邮箱不能为空!");
                  }
      
                  if (!email.matches("^\\w+@\\w+(\\.\\w+)+$")) {
                      throw new MsgException("邮箱格式不正确!");
                  }
      
                  if (valistr == null || "".equals(valistr)) {
                      throw new MsgException("验证码不能为空!");
                  }
      
                  // 4.存入数据库
                  User user = new User(-1, username, password, nickname, email);
                  if (us.checkHasUsername(user)) {// 账号重复
                      throw new MsgException("账号重复");
                  } else {// 账号不重复
                      // 存储数据
                      us.addUser(user);
                  }
                  // 5.向浏览器报告成功 回到主页
                  response.getWriter().write("注册成功!正在前往主页------>>>");
                  response.setHeader("refresh", "1;url=" + request.getContextPath()
                          + "/index.jsp");
              } catch (MsgException e) {
                  String msg = e.getMessage();
                  response.getWriter().write(msg);
                  response.setHeader("refresh", "1;url=/regist.jsp");
              } catch (Exception e) {
                  e.printStackTrace();
                  throw new RuntimeException(e);
              }
          }
      
          public void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              this.doGet(request, response);
          }
      }
      
    • ValiImageServlet.java

      package com.easymall.web;
      
      import java.awt.Color;
      import java.awt.Font;
      import java.awt.Graphics2D;
      import java.awt.image.BufferedImage;
      import java.io.IOException;
      import java.util.Random;
      
      import javax.imageio.ImageIO;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      @SuppressWarnings("serial")
      public class ValiImageServlet extends HttpServlet {
          // 背景参数
          private int base = 30;
          private int height = base;
          private int width = base * 4;
      
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                  throws ServletException, IOException {
              // 禁止浏览器缓存图片
              resp.setHeader("Cache-Control", "no-cache");
              resp.setHeader("Progma", "no-cache");
              resp.setDateHeader("Expires", 0);
              // 创建内存中的图片
              BufferedImage di = new BufferedImage(width, height,
                      BufferedImage.TYPE_INT_RGB);
              // 获取画布画背景
              Graphics2D g2 = (Graphics2D) di.getGraphics();
              // 填充矩形
              g2.setColor(Color.white);
              g2.fillRect(0, 0, width, height);
              // 绘制边框
              g2.setColor(Color.red);
              g2.drawRect(0, 0, width - 1, height - 1);
              // 写字并保存到session
              String valistr2 = "";
              g2.setFont(new Font("微软雅黑", Font.BOLD, 25));
              for (int i = 0; i < 4; i++) {
                  String s = Integer.toString(getRandom(0, 10));
                  valistr2 += s;
                  g2.setColor(new Color(getRandom(0, 255), getRandom(0, 255),
                          getRandom(0, 255)));
                  int temp = getRandom(-45, 45);
                  g2.rotate(temp / 180.0 * Math.PI, 10 + 30 * i, 20);
                  g2.drawString(s, 10 + 30 * i, 20);
                  g2.rotate(-temp / 180.0 * Math.PI, 10 + 30 * i, 20);
              }
              System.out.println("当前验证码:" + valistr2);
              req.getSession().setAttribute("valistr2", valistr2);
              // 画干扰线
              for (int i = 0; i < 3; i++) {
                  g2.setColor(new Color(getRandom(0, 255), getRandom(0, 255),
                          getRandom(0, 255)));
                  g2.drawLine(getRandom(0, width), getRandom(0, height),
                          getRandom(0, width), getRandom(0, height));
              }
              // 画干扰点
              for (int i = 0; i < 5; i++) {
                  g2.setColor(new Color(getRandom(0, 255), getRandom(0, 255),
                          getRandom(0, 255)));
                  g2.drawOval(getRandom(0, width), getRandom(0, height), 5, 5);
              }
              // 画出图片
              ImageIO.write(di, "JPG", resp.getOutputStream());
              // 关闭画布
              g2.dispose();
          }
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                  throws ServletException, IOException {
              this.doGet(req, resp);
          }
      
          // 获取随机数
          private int getRandom(int start, int end) {
              Random random = new Random();
              return start + random.nextInt(end - start);
          }
      
      }
      
  • 配置文件

    • c3p0.properties

      c3p0.driverClass=com.mysql.jdbc.Driver
      c3p0.jdbcUrl=jdbc:mysql://localhost:3306/easymall
      c3p0.user=root
      c3p0.password=root
      
    • config.properties

      UserService=com.easymall.service.UserServiceImpl
      UserDao=com.easymall.dao.UserDaoImpl
      
    • web.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <web-app version="2.5" 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-app_2_5.xsd">
      
          <!-- 全局参数的设置 -->
          <context-param>
              <param-name>encode</param-name>
              <param-value>utf-8</param-value>
          </context-param>
      
          <!-- Servlet地址对应设置 -->
          <servlet>
              <servlet-name>RegistServlet</servlet-name>
              <servlet-class>com.easymall.web.RegistServlet</servlet-class>
          </servlet>
          <servlet>
              <servlet-name>CheckHasUsernameServlet</servlet-name>
              <servlet-class>com.easymall.web.CheckHasUsernameServlet</servlet-class>
          </servlet>
          <servlet>
              <servlet-name>LoginServlet</servlet-name>
              <servlet-class>com.easymall.web.LoginServlet</servlet-class>
          </servlet>
          <servlet>
              <servlet-name>LogOutServlet</servlet-name>
              <servlet-class>com.easymall.web.LogOutServlet</servlet-class>
          </servlet>
        <servlet>
          <servlet-name>ValiImageServlet</servlet-name>
          <servlet-class>com.easymall.web.ValiImageServlet</servlet-class>
        </servlet>
      
      
          <!-- Servlet映射设置 -->
          <servlet-mapping>
              <servlet-name>RegistServlet</servlet-name>
              <url-pattern>/RegistServlet</url-pattern>
          </servlet-mapping>
          <servlet-mapping>
              <servlet-name>CheckHasUsernameServlet</servlet-name>
              <url-pattern>/CheckHasUsernameServlet</url-pattern>
          </servlet-mapping>
          <servlet-mapping>
              <servlet-name>LoginServlet</servlet-name>
              <url-pattern>/LoginServlet</url-pattern>
          </servlet-mapping>
          <servlet-mapping>
              <servlet-name>LogOutServlet</servlet-name>
              <url-pattern>/LogOutServlet</url-pattern>
          </servlet-mapping>
        <servlet-mapping>
          <servlet-name>ValiImageServlet</servlet-name>
          <url-pattern>/ValiImageServlet</url-pattern>
        </servlet-mapping>
      
          <!-- 欢迎页面 -->
          <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
          </welcome-file-list>
      </web-app>
      
  • jsp页面(主要看EL+jstl;样式这里省略)

    • foot.jsp

      <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      <!DOCTYPE HTML>
      <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
      <link rel="stylesheet" href="css/foot.css" />
      <div id="common_foot">
          <p>
              Copyright © 2011-2015 达内软件技术有限公司 版权所有 保留一切权利 苏B2-20130048号 |
              京ICP备09062682号-9 <br> 网络文化经营许可证苏网文[2012]0401-019号
          </p>
      </div>
      
    • head.jsp

      <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      <%@  taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
      <!DOCTYPE HTML>
      <link rel="stylesheet" href="css/head.css" />
      <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
      
      <div id="common_head">
          <div id="line1">
              <div id="content">
                  <c:if test="${sessionScope.username!=null}">
                  您好:${sessionScope.username}&nbsp;&nbsp;|&nbsp;&nbsp;<a
                          href="${requestScope.contextPath }/LogOutServlet">注销 </a>
                  </c:if>
                  <c:if test="${sessionScope.username==null}">
                      <a href="${requestScope.contextPath }/login.jsp">登录</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a
                          href="${requestScope.contextPath }/regist.jsp">注册</a>
                  </c:if>
              </div>
          </div>
          <div id="line2">
              <img id="logo" src="img/head/logo.jpg" /> <input type="text" name="" />
              <input type="button" value="搜索" /> <span id="goto"> <a
                  id="goto_order" href="#">我的订单</a> <a id="goto_cart" href="#">我的购物车</a>
              </span> <img id="erwm" src="img/head/qr.jpg" />
          </div>
          <div id="line3">
              <div id="content">
                  <ul>
                      <li><a href="#">首页</a>
                      </li>
                      <li><a href="#">全部商品</a>
                      </li>
                      <li><a href="#">手机数码</a>
                      </li>
                      <li><a href="#">电脑平板</a>
                      </li>
                      <li><a href="#">家用电器</a>
                      </li>
                      <li><a href="#">汽车用品</a>
                      </li>
                      <li><a href="#">食品饮料</a>
                      </li>
                      <li><a href="#">图书杂志</a>
                      </li>
                      <li><a href="#">服装服饰</a>
                      </li>
                      <li><a href="#">理财产品</a>
                      </li>
                  </ul>
              </div>
          </div>
      </div>
      
    • index.jsp

      <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
          buffer="0kb"%>
      <!DOCTYPE HTML>
      <html>
      <head>
      <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
      <link rel="stylesheet" href="css/index.css" />
      <title>欢迎光临EasyMall</title>
      </head>
      <body>
          <%@include file="head.jsp"%>
          <div id="index">
              <div id="line1">
                  <img src="img/index/banner_big.jpg" />
              </div>
              <div id="line2">
                  <img id="line2_1" src="img/index/adv1.jpg" /> <img id="line2_2"
                      src="img/index/adv2.jpg" /> <img id="line2_3"
                      src="img/index/adv_l1.jpg" />
              </div>
              <div id="line3">
                  <img id="line3_1" src="img/index/adv3.jpg" /> <img id="line3_2"
                      src="img/index/adv4.jpg" />
                  <div id="line3_right">
                      <img id="line3_3" src="img/index/adv_l2.jpg" /> <img id="line3_4"
                          src="img/index/adv_l3.jpg" />
                  </div>
              </div>
              <div id="line4">
                  <img src="img/index/217.jpg" />
              </div>
              <div id="line5">
                  <span id="line5_1"> <img src="img/index/icon_g1.png" />&nbsp;&nbsp;500强企业
                      品质保证 </span> <span id="line5_2"> <img src="img/index/icon_g2.png" />&nbsp;&nbsp;7天退货
                      15天换货 </span> <span id="line5_3"> <img src="img/index/icon_g3.png" />&nbsp;&nbsp;100元起免运费
                  </span> <span id="line5_4"> <img src="img/index/icon_g4.png" />&nbsp;&nbsp;448家维修网点
                      全国联保 </span>
              </div>
          </div>
          <%@include file="foot.jsp"%>
      </body>
      </html>
      
    • login.jsp

      <%@page import="java.net.URLDecoder"%>
      <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
      <!DOCTYPE HTML>
      <html>
      <head>
      <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
      <link rel="stylesheet" href="css/login.css" />
      <title>EasyMall欢迎您登陆</title>
      </head>
      <body>
          <h1>欢迎登陆EasyMall</h1>
          <form action="/LoginServlet" method="POST">
              <table>
                  <c:if test="${param.msg!=null}">
                      <tr>
                          <td colspan='2'><font color='#ff0000'> <!-- 注:这里没有解决乱码的jstl标签,所以用java代码来写--><%=new String(request.getParameter("msg").getBytes(
                              "iso8859-1"), "utf-8")%> </font>
                          </td>
                      </tr>
                  </c:if>
                  <tr>
                      <td class="tdx">用户名:</td>
                      <td><input type="text" name="username" id="username" value="${cookie.remname.value}" />
                      </td>
                  </tr>
                  <tr>
                      <td class="tdx">密码:</td>
                      <td><input type="password" name="password" /></td>
                  </tr>
                  <tr>
                      <td colspan="2"><input type="checkbox" name="remname"
                          value="true"
                          <c:if test="${cookie.remname!=null }">checked="checked"</c:if> />记住用户名
                          <input type="checkbox" name="autologin" value="true" />30天内自动登陆</td>
                  </tr>
                  <tr>
                      <td colspan="2"><input type="submit" value="登陆" />
                      </td>
                  </tr>
              </table>
          </form>
          <script type="text/javascript">
              //给账号设值
              var username = "${cookie.remname.value}";
              document.getElementById("username").value = decodeURIComponent(username);
          </script>
      </body>
      </html>
      
    • regist.jsp

      <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
      <!DOCTYPE HTML>
      <html>
      <head>
      <title>欢迎注册EasyMall</title>
      <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
      <link rel="stylesheet" href="css/regist.css" />
      <script type="text/javascript" src="js/jquery-1.4.2.js"></script>
      <script type="text/javascript">
          $(document).ready(
                  function() {
                      var canSubmit = true;//提交的标志
                      //用户名已存在检查(ajax)    
                      $("input[name='username']").blur(
                              function() {
                                  if ($("input[name='username']").val() != "") {
                                      $.get("/CheckHasUsernameServlet?"
                                              + $.param({
                                                  "username" : $(
                                                          "input[name='username']")
                                                          .val()
                                              }), function(data) {
                                          if ($.parseJSON(data).hasUser) {
                                              //提示该账户已有
                                              $("input[name='username']")
                                                      .next("span").text("用户名重复!");
                                              canSubmit = false;
                                          } else {
                                              $("input[name='username']")
                                                      .next("span").text("");
                                              canSubmit = true;
                                          }
                                      });
                                  }
                              });
      
                      //两次密码的一致性检验(失去焦点)
                      $("input[name='password2']").blur(
                              function() {
                                  if ($("input[name='password2']").val() != "") {
                                      if ($("input[name='password']").val() != $(
                                              "input[name='password2']").val()) {//密码不一致
                                          $("input[name='password2']").next("span")
                                                  .text("密码不一致!");
                                          canSubmit = false;
                                      } else {
                                          $("input[name='password2']").next("span")
                                                  .text("");
                                          canSubmit = true;
                                      }
                                  }
                              });
                      //检查邮箱的格式是否正确
                      $("input[name='email']").blur(function() {
                          var email_Reg = /^\w+@\w+(\.\w+)+$/;
                          if ($(this).val() != "" && email_Reg.test($(this).val())) {
                              $(this).next("span").text("");
      
                              canSubmit = true;
                          } else {
                              $(this).next("span").text("邮箱格式不正确!");
                              canSubmit = false;
                          }
                      });
                      //验证码切换(点击事件)
                      $("#yzm_img").click(
                              function() {
                                  $(this).attr(
                                          "src",
                                          "/ValiImageServlet?time="
                                                  + new Date().getTime());
                              });
                      //表单提交事件
                      $("form").submit(function() {
                          //判断所有的输入框是否为空
                          $.each($("input[type!='submit']"), function() {
                              if ($(this).val() == "") {//密码不一致
                                  $(this).nextAll("span").text("数据不能为空!");
                                  canSubmit = false;
                              } else {
                                  $(this).nextAll("span").text("");
                                  canSubmit = true;
                              }
                          });
                          return canSubmit;
                      });
                  });
      </script>
      </head>
      <body>
          <h1>欢迎注册EasyMall</h1>
          <form action="/RegistServlet" method="POST" onsubmit="">
              <table>
                  <tr>
                      <td class="tds">用户名:</td>
                      <td><input type="text" name="username"
                          value="${param.username }"><span></span></td>
                  </tr>
                  <tr>
                      <td class="tds">密码:</td>
                      <td><input type="password" name="password"><span></span>
                      </td>
                  </tr>
                  <tr>
                      <td class="tds">确认密码:</td>
                      <td><input type="password" name="password2"><span></span>
                      </td>
                  </tr>
                  <tr>
                      <td class="tds">昵称:</td>
                      <td><input type="text" name="nickname"
                          value="${param.nickname }"><span></span></td>
                  </tr>
                  <tr>
                      <td class="tds">邮箱:</td>
                      <td><input type="text" name="email" value="${param.email }"><span></span>
                      </td>
                  </tr>
                  <tr>
                      <td class="tds">验证码:</td>
                      <td><input type="text" name="valistr"><img id="yzm_img"
                          src="/ValiImageServlet" style="cursor: pointer" /><span><font
                              color="#ff0000">${requestScope.msg }</font> </span>
                      </td>
                  </tr>
                  <tr>
                      <td colspan="2"><input type="submit" value="注册用户" /></td>
                  </tr>
              </table>
          </form>
      </body>
      </html>
      
  • 所需jar包
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乘风御浪云帆之上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值