JavaEE学习日志(六十八):黑马商城项目(一)

JavaEE学习日志持续更新----> 必看!JavaEE学习路线(文章总汇)

黑马商城项目(一)

总体需求

  • 用户模块
    • 登录
    • 注册
    • 退出登录
    • 修改
  • 商品模块
    • 商品的展示
    • 分类展示
  • 购物车模块
  • 订单模块
    • 在线支付
  • 后台管理模块

本章功能实现

完成用户(User)模块的:

  • 注册
  • 登录
  • 退出登录

域名解析服务器

在这里插入图片描述

前后端分离

在这里插入图片描述

AJAX跨域访问

在这里插入图片描述
跨域问题来源于JavaScript的同源策略,即只有 协议+主机名+端口号 (如存在)相同,则允许相互访问。也就是说JavaScript只能访问和操作自己域下的资源,不能访问和操作其他域下的资源。

//允许AJAX跨域访问
response.setHeader("Access-Control-Allow-Origin", "http://www.itheima326.com:8020");
//AJAX访问允许客户端保存cookie
response.setHeader("Access-Control-Allow-Credentials","true");

BaseServlet抽取

package com.itheima.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public abstract class BaseServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       try {
           //获取客户端提交的数据,方法名
           String md = request.getParameter("method");
           Class clazz = this.getClass();
           Method method = clazz.getMethod(md, HttpServletRequest.class, HttpServletResponse.class);
           method.invoke(this, request, response);
       }catch (Exception ex){
           ex.printStackTrace();
       }
    }

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

用户注册

实现步骤

  • 客户端发起AJAX请求,表单数据提交到服务器Servlet
  • Servlet接收客户端请求数据并封装JavaBean
  • 调用业务层方法
  • 业务层调用持久层方法
  • Servlet将注册结果封装对象,向客户端回写JSON数据
  • 客户端判断JSON数据,跳转页面

前端

注意:

  • <form>表单中加入
    <input type="hidden" name="method" value="register">
    可以多提交一组隐藏的数据
  • $("#regForm").serialize()可以获得表单中所有提交的数据
<script type="text/javascript">
		$(function(){
			//注册按钮绑定事件
			$("#regBut").click(function(){
				//把表单数据提交到服务器,异步提交
				var params = $("#regForm").serialize();
				//把数据以AJAX形式提交到Servlet
				//工具函数,传递url,参数,回调函数
				HM.ajax("/user",params,function(data){
					//data就是响应回的json
					if(data.code==1){
						//页面跳转到登录页面
						location.href="http://www.itheima331.com:8020/web/login.html"
					}
				});
			});
		});
	</script>

UserServlet

注意:

  • 使用BaseServlet抽取
  • 封装一个响应结果对象,封装3个成员
    状态码 int
    状态码信息 String
    响应数据 Object
  • 使用bean工厂,传递UserService接口,创建UserService接口的实现类对象
package com.itheima.web;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.BeanFactory;
import com.itheima.utils.UUIDUtils;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet(urlPatterns = "/user")
public class UserServlet extends BaseServlet {
    //bean工厂,获取业务层接口实现类对象
    private UserService userService = BeanFactory.newInstance(UserService.class);
    /*
        请求,处理客户端的注册功能
        获取表单数据Map
        把数据封装到JavaBean对象
        调用业务层传递JavaBean
        响应回客户端
     */
    public void register(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        }catch (Exception ex){
            ex.printStackTrace();
        }

        //user对象数据不全,需要手动设置
        //设置激活码,1
        user.setState(1);
        //设置主键
        user.setUid(UUIDUtils.getUUID());
        userService.register(user);
        //结果对象创建
        //封装状态码和对应的信息,不要写死
        Result result = new Result(Result.SUCCESS,"注册成功");
        //对象转成json
        //print默认调用toString()
        response.getWriter().print(JSONObject.fromObject(result));

    }
}

UserService

使用bean工厂,传递UserDao接口,创建UserDao接口的实现类对象

package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.BeanFactory;

import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    //bean工厂,获取dao接口实现类
    private UserDao userDao = BeanFactory.newInstance(UserDao.class);
    /*
        接收web层传递的user
        调用dao传递user
     */
    @Override
    public void register(User user) {
        try {
            userDao.register(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}

UserDao

package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.utils.C3P0UtilsXML;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private QueryRunner qr = new QueryRunner(C3P0UtilsXML.getDataSource());
    /*
        实现用户注册
        user对象数据,存储到数据库中
        user对象是业务层传递的
     */
    @Override
    public void register(User user) throws SQLException {
        //添加数据
        String sql = "insert into user values (?,?,?,?,?,?,?,?,?,?)";
        //数据封装到数组中
        Object[] params = {
                user.getUid(),
                user.getUsername(),
                user.getPassword(),
                user.getName(),
                user.getEmail(),
                user.getBirthday(),
                user.getGender(),
                user.getState(),
                user.getCode(),
                user.getRemark()
        };
        qr.update(sql, params);
    }
}

用户登录

实现步骤

  • 客户端发起AJAX请求,表单数据提交到服务器Servlet
  • Servlet接收客户端请求数据并传递到业务层
  • 调用业务层方法获取返回值
  • 业务层调用持久层方法
  • Servlet将登录结果封装成对象,返回JSON数据
  • 登录成功保存session
  • 用户名姓名保存在cookie中,回写浏览器
  • 客户端判断JSON数据,跳转页面
  • 客户端在页面顶部显示登录的用户名

前端

第一部分:登录按钮事件

<script type="text/javascript">
			$(function(){
				//登录按钮绑定点击事件
				$("#submit").click(function(){
					//获取表单数据,用户名和密码
					var params = $("#loginForm").serialize();
					//把数据提交到服务器端
					HM.ajax("/user",params,function(data){
						//data是响应回来的json
						if(data.code==1){
							//登录成功,跳转到首页
							location.href="http://www.itheima331.com:8020/web/index.html";
						}else if(data.code==0){
							//登录失败,json的键message取出数据
							$("#loginMsg").html(data.message).css("color","red");
						}
					});
				});
			});
		</script>

第二部分:显示欢迎,xx

<script type="text/javascript">
	$(function(){
		//取出cookie中的用户名,填充到菜单中
		//工具方法cookieValue函数,传递cookie键,返回值
		var cookieValue = HM.cookieValue("username");
		//判断取出的cookie值
		if(cookieValue==null || cookieValue==""){
			//没有cookie,没有登陆,显示登录注册
			var s = "<li><a href=\"http://www.itheima331.com:8020/web/login.html\">登录</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/register.html\">注册</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/view/cart/list.html\">购物车</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/view/cart/list.html\">我的订单</a></li>";
			$("#login-menu").html(s);
		}else{
			//有cookie,显示你好,xx
			var s = "<li>欢迎,"+cookieValue+"</li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/register.html\">退出登录</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/view/cart/list.html\">购物车</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/view/cart/list.html\">我的订单</a></li>";
			$("#login-menu").html(s);
		}
	});
	
</script>

UserServlet

/*
        请求,处理客户端登录
        获取用户名和密码
        传递业务层,接收返回值User
        判断User对象的值
        user!=null 登录成功
            把user对象存储到session域
            创建cookie,保存用户名
            写回客户端浏览器
            进行响应json
       user==null 登录失败
            进行响应json

     */
    public void login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //调用业务层方法,传递用户名密码,获取返回值User
        User user = userService.login(username, password);
        //判断user对象
        if(user!=null){
            //查询到数据,登录成功
            //user对象存储到session
            request.getSession().setAttribute("user",user);
            //创建cookie对象,保存用户名
            Cookie cookie = new Cookie("username",username);
            //设置cookie参数
            cookie.setMaxAge(60*10);
            cookie.setPath(request.getContextPath());
            //设置cookie携带的域名,域名是顶级域名
            cookie.setDomain("itheima331.com");
            response.addCookie(cookie);
            //进行响应json
            //设置响应的结果对象
            Result result = new Result(Result.SUCCESS,"登录成功");
            response.getWriter().print(JSONObject.fromObject(result));

        }else {
            //没查到
            //进行响应json
            //设置响应的结果对象
            Result result = new Result(Result.FAILS,"登录失败,请检查用户名密码");
            response.getWriter().print(JSONObject.fromObject(result));
        }
    }

UserService

/*
        用户登录方法
        web层传递用户名和密码
        调用dao层传递参数,结果返回到web层
     */
    @Override
    public User login(String username, String password) {
        User user = null;
        try {
            user= userDao.login(username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

UserDao

/*
        用户登录方法
        业务层传递用户名密码
        作为条件查询数据表
        返回User对象
     */
    @Override
    public User login(String username, String password) throws SQLException {
        //拼写查询的sql语句
        String sql = "select * from user where username = ? and password = ?";
        return qr.query(sql,new BeanHandler<User>(User.class),username,password);
    }

退出登录

实现步骤

  • 点击退出登录按钮
  • 服务器端销毁session对象
  • 客户端跳转到首页
  • 页面头部不在显示登录的用户名

前端

<script type="text/javascript">
	$(function(){
		//取出cookie中的用户名,填充到菜单中
		//工具方法cookieValue函数,传递cookie键,返回值
		var cookieValue = HM.cookieValue("username");
		//判断取出的cookie值
		if(cookieValue==null || cookieValue==""){
			//没有cookie,没有登陆,显示登录注册
			var s = "<li><a href=\"http://www.itheima331.com:8020/web/login.html\">登录</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/register.html\">注册</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/view/cart/list.html\">购物车</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/view/cart/list.html\">我的订单</a></li>";
			$("#login-menu").html(s);
		}else{
			//有cookie,显示你好,xx
			var s = "<li>欢迎,"+cookieValue+"</li>\n" +
        "\t\t\t<li><a href=\"#\" οnclick='loginOut()'>退出登录</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/view/cart/list.html\">购物车</a></li>\n" +
        "\t\t\t<li><a href=\"http://www.itheima331.com:8020/web/view/cart/list.html\">我的订单</a></li>";
			$("#login-menu").html(s);
		}
	});
	//退出登录的函数
	function loginOut(){
		//发送请求,退出登录
		HM.ajax("/user","method=loginOut",function(data){
			if(data.code==1){
				location.href="http://www.itheima331.com:8020/web/index.html";
			}
		});
	}
	
</script>

UserServlet

/*
        客户端的退出登录
        销毁session对象
        销毁客户端的cookie
     */
    public void loginOut(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        //销毁session对象
        request.getSession().invalidate();
        //销毁客户端的cookie
        //创建cookie对象,保存用户名
        Cookie cookie = new Cookie("username",null);
        //设置cookie参数
        cookie.setMaxAge(0);
        cookie.setPath(request.getContextPath());
        //设置cookie携带的域名,域名是顶级域名
        cookie.setDomain("itheima331.com");
        response.addCookie(cookie);
        Result result = new Result(Result.SUCCESS,"退出成功");
        response.getWriter().print(JSONObject.fromObject(result));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值