以用户的注册功能为例介绍Java的MVC开发模式

分层思想

MVC开发模式分为:web层(表现层),业务层,数据访问层
目的:高内聚,低耦合,方便后期维护
包: com.itheima.domin 实体类
com.itheima.dao ——数据访问层接口
com.itheima.daoimpl—— 接口实现类
com.itheima.service ——业务层接口
com.itheima.serviceimpl ——业务层接口实现类
com.itheima.utils ——工具类
com.itheima.exception—— 异常处理类
com.itheima.servlet—— servlet类

先写一个实例类

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private int id;
    private String username;
    private String password;
    private String email;
    private Date birthday;

    public void setId(int id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getEmail() {
        return email;
    }

    public Date getBirthday() {
        return birthday;
    }
}

完成dao层的接口以及实现类

## 接口 ##
package com.itheima.dao;

import com.itheima.domain.User;

public interface UserDao {
    /**
     * 添加用户信息的方法
     * @param user
     * @throws Exception
     */
    public void addUser(User user) throws Exception;
}
## 实现类 ##
package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;

public class UserDaoImpl implements UserDao {
    @Override
    public void addUser(User user) throws Exception{
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("INSERT INTO users(username,PASSWORD,email,birthday) VALUES (?,?,?,?)");
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.setString(3, user.getEmail());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date = simpleDateFormat.format(user.getBirthday());
            preparedStatement.setString(4, date);
            int i = preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("添加用户信息失败");
        } finally {
            DBUtils.closeAll(null, preparedStatement, connection);
        }
    }
}

完成service层的接口以及实现类

## 接口 ##
package com.itheima.service;

import com.itheima.domain.User;

public interface UserService {
    /**
     * 注册
     * @param user
     * @throws Exception
     */
    public void register(User user) throws Exception;
}
## 实现类 ##
package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.domain.User;
import com.itheima.service.UserService;

public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDaoImpl();
    @Override
    public void register(User user) throws Exception {
        userDao.addUser(user);
    }
}

写一个简单的主页以及登录页面 ##

## 主页:index.jsp ##
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018-08-30
  Time: 16:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <a href="reg.jsp">注册</a>
  </body>
</html>


## 登录页面:reg.jsp ##
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018-09-05
  Time: 9:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/regServlet" method="post">
        用户名<input type="text" name="username"><br>
        密码<input type="password" name="password"><br>
        确认密码<input type="password" name="repassword"><br>
        邮箱<input type="text" name="email"><br>
        生日<input type="text" name="birthday"><br>
        <input type="submit" value="注册">
    </form>
</body>
</html>

完成注册servlet ##.

package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "regServlet")
public class regServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        User user = new User();
        try {
            //获取表单数据
            ConvertUtils.register(new Converter() {     //注册一个日期转换器
                @Override
                public Object convert(Class type, Object value) {
                    Date date1 = new Date();
                    if(value instanceof String){
                        String date = (String) value;
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            date1 = simpleDateFormat.parse(date);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    return date1;
                }
            }, Date.class);
            BeanUtils.populate(user, request.getParameterMap());
            //调用业务逻辑
            UserService userService  = new UserServiceImpl();
            userService.register(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //分发转向
        response.getWriter().write("注册成功,1秒后跳转回主页");
        response.setHeader("refresh", "1;url="+request.getContextPath()+"/index.jsp");
    }

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

启动服务器,访问主页进行注册,刷新数据库即可完成

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值