欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA WEB 的一种开发模式---MVC模式和分层思想

程序员文章站 2024-02-26 19:10:58
...

MVC开发模式

  • M:Model模型
    • JavaBean的四种作用域
  • V:View视图
    • Jsp技术
  • C:Controller控制器
    • Servlet技术

JAVA WEB 的一种开发模式---MVC模式和分层思想

  • ps:
    JavaBean:就是一个普通类(实体bean),包含三样标准:一个无参构造、私有属性、公共的getter和setter方法

分层思想

将应用分为三个层面:WEB层,业务层,数据访问层
客户端通过WEB层调用业务层的功能,再从业务层的功能中调取数据访问层,数据访问层再从数据库中拿到想要的数据。
JAVA WEB 的一种开发模式---MVC模式和分层思想

案例分析:登录与注册

  1. 登录:
    JAVA WEB 的一种开发模式---MVC模式和分层思想
  2. 注册:
    JAVA WEB 的一种开发模式---MVC模式和分层思想
  3. 使用JavaBean封装数据
  4. 总体的包:
    撒旦
    JAVA WEB 的一种开发模式---MVC模式和分层思想
    com.lwb.domain:javaBean实体类
    com.lwb.dao dao接口
    com.lwb.dao.impl dao的实现类
    com.lwb.exception 异常
    com.lwb.service 业务实现接口
    com.lwb.service.impl 实现接口
    com.lwb.servlet Servlet类
    com.lwb.utils 链接数据库

代码:

  1. index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

  </head>
  
  <body>
  <center>
  <c:if test="${empty user }">
	  <form action="${pageContext.request.contextPath }/servlet/loginServlet" method="post">
	  	用户名:<input type="text" name="username"><br/>
	  	密码:<input type="password" name="pwd"><br/>
	  	<input type="submit" value="登录"><br/>
	  </form>
	  <h1>若未注册,点击注册</h1>
	  <a href="/day12/register.jsp">注册</a>
  </c:if>
  <c:if test="${not empty user }">
  	<h1>欢迎你!!亲爱的${user.username }!!</h1>
  	<a href="${pageContext.request.contextPath  }/servlet/loginOutServlet">注销</a>
  </c:if>
  </center>
  </body>
</html>
  1. register.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">
<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 }/servlet/regServlet" method="post">
		用户名:<input type="text" name="username"/ value="${uf.username }">${uf.msg.username }${error }<br/>
		密码:<input type="password" name="pwd"/>${uf.msg.pwd }<br/>
		确认密码:<input type="password" name="pwd2"/>${uf.msg.pwd2 }<br/>
		邮箱:<input type="text" name="mailbox" value="${uf.mailbox }"/>${uf.msg.mailbox }<br/>
		生日:<input type="text" name="birthday" value="${uf.birthday}"/>${uf.msg.birthday }<br/>
		<input type="submit" value="注册"/><br/>
	</form>

</body>
</html>
  1. com.lwb.dao.UserDao.java
package com.lwb.dao;

import com.lwb.domain.User;

public interface UserDao {
	//添加用户信息
	public void addUser(User user)throws Exception;
	
	//查找用户数据
	public User findUser(User user)throws Exception;
	
	//查找用户名
	public boolean findByUserName(String username);

}
  1. com.lwb.dao.impl.UserDaoImpl.java
package com.lwb.dao.impl;

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

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

public class UserDaoImpl implements UserDao {

	public void addUser(User user) throws Exception {
		Connection conn = null;
		PreparedStatement ps = null;
		
		try {
					conn = DBUtils.getConnection();
		ps = conn.prepareStatement("insert into user(username,pwd,mailbox,birthday)values(?,?,?,?)");
		
		ps.setString(1, user.getUsername());
		ps.setString(2, user.getPwd());
		ps.setString(3, user.getMailbox());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String Date = sdf.format(user.getBirthday());
		ps.setString(4, Date);
		
		int i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("添加失败");
		}finally{
			DBUtils.clossAll(null, ps, conn);
		}
		
		

	}

	@Override
	public User findUser(User user) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		User u = null;
		
		try {
			conn = DBUtils.getConnection();
			ps = conn.prepareStatement("select * from user where username = ? and pwd = ?");
			
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPwd());
			
			rs = ps.executeQuery();
			if(rs.next()){
				u = new User();
				u.setUsername(rs.getString(1));
				u.setPwd(rs.getString(2));
				u.setMailbox(rs.getString(3));
				u.setBirthday(rs.getDate(4));
				u.setId(rs.getInt(5));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DBUtils.clossAll(rs, ps, conn);
		}
		
		return u;
	}

	@Override
	public boolean findByUserName(String username) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = DBUtils.getConnection();
			ps = conn.prepareStatement("select * from user where username = ?");
			ps.setString(1, username);
			rs = ps.executeQuery();
			if(rs.next()){
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBUtils.clossAll(rs, ps, conn);
		}
		return false;
	}

}

  1. com.lwb.domain.User.java
package com.lwb.domain;

import java.util.Date;

public class User {
	private String username;
	private String pwd;
	private String mailbox;
	private Date birthday;
	private int id;
	
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getMailbox() {
		return mailbox;
	}
	public void setMailbox(String mailbox) {
		this.mailbox = mailbox;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}

}

  1. com.lwb.domian.UserForm.java
package com.lwb.domain;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class UserForm {
	private String username;
	private String pwd;
	private String pwd2;
	private String mailbox;
	private String birthday;
	
	Map<String,String>msg = new HashMap<String, String>();
	
public boolean validate(){
		
		if("".equals(username)){
			msg.put("username", "用户名不能为空!");
		}else if(!username.matches("\\w{3,8}")){//用户名:必须输入,且3~8位的字母组成<br>
			msg.put("username", "用户名为3~8位的字母组成");
		}
		
		if("".equals(pwd)){
			msg.put("pwd", "密码不能为空!");
		}else if(!pwd.matches("\\d{3,8}")){//密码:必须输入,3~8位的数组组成<br>
			msg.put("pwd", "密码为3~8位的数字组成");
		}
		
		//确认密码:和密码保持一致<br>
		if(!pwd2.equals(pwd)){
			msg.put("pwd2", "两次密码不一致!");
		}
		
		//邮箱:必须输入,且要符合邮箱的格式<br>
		if("".equals(mailbox)){
			msg.put("mailb", "邮箱不能为空!");
		}else if(!mailbox.matches("\\b^['_a-z0-9-\\+]+(\\.['_a-z0-9-\\+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2}|aero|arpa|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|nato|net|org|pro|tel|travel|xxx)$\\b")){
			msg.put("mailbox", "邮箱格式不正确!");
		}
		
		//生日:必须输入,符合yyyy-MM-dd的格式<br>
		if("".equals(birthday)){
			msg.put("birthday", "生日不能为空!");
		}else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				sdf.parse(birthday);
			} catch (ParseException e) {
				msg.put("birthday", "生日格式不正确!");
			}
		}
		return msg.isEmpty();//当map集合中没有数据时,返回true
		
	}

	public String getUsername() {
		return username;
	}

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

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getPwd2() {
		return pwd2;
	}

	public void setPwd2(String pwd2) {
		this.pwd2 = pwd2;
	}

	public String getMailbox() {
		return mailbox;
	}

	public void setMailbox(String mailbox) {
		this.mailbox = mailbox;
	}

	public String getBirthday() {
		return birthday;
	}

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

	public Map<String, String> getMsg() {
		return msg;
	}

	public void setMsg(Map<String, String> msg) {
		this.msg = msg;
	}

}

  1. com.lwb.exception.UserExistException.java
package com.lwb.exception;

public class UserExistException extends Exception {

	public UserExistException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public UserExistException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public UserExistException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public UserExistException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}
	
}
  1. com.lwb.exception.UsersException.java
package com.lwb.exception;

import java.io.PrintStream;
import java.io.PrintWriter;

public class UsersException extends Exception {

	public UsersException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public UsersException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public UsersException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public UsersException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}
	

}
  1. com.lwb.service.UserService.java
package com.lwb.service;

import com.lwb.exception.UserExistException;
import com.lwb.domain.User;

public interface UserService {
	//注册
	public void register(User user)throws Exception;
	
	//登录
	public User Login(User user);
	
	//根据用户名查找用户是否存在
	public boolean findUserByName(String name) throws UserExistException;

}
  1. com.lwb.service.UserServiceImpl.java
package com.lwb.service.impl;

import com.lwb.dao.UserDao;
import com.lwb.dao.impl.UserDaoImpl;
import com.lwb.domain.User;
import com.lwb.exception.UserExistException;
import com.lwb.service.UserService;

public class UserServiceImpl implements UserService {
	
	UserDao userDao = new UserDaoImpl();
	public void register(User user) throws Exception {
		userDao.addUser(user);
		
	}
	
	public User Login(User user) {
		User u = null;
		try {
			u = userDao.findUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return u;
	}

	@Override
	public boolean findUserByName(String name) throws UserExistException {
		boolean b = userDao.findByUserName(name);
		if(b){
			throw new UserExistException("用户名已经存在");
		}
		return false;
	}

}
  1. com.lwb.servlet.LoginOutServlet.java
package com.lwb.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

public class LoginOutServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();//销毁Session对象
		response.sendRedirect(request.getContextPath()+"/index.jsp");//重定向

	}

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

}
  1. com.lwb.servlet.LoginServlet.java
package com.lwb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

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 org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import com.lwb.domain.User;
import com.lwb.service.UserService;
import com.lwb.service.impl.UserServiceImpl;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		User user = new User();
		//获取表单数据
		
		try {
			ConvertUtils.register(new DateLocaleConverter(), Date.class);
			BeanUtils.populate(user, request.getParameterMap());
			//调用业务处理
			UserService us = new UserServiceImpl();
			User u = us.Login(user);
			if(u!=null){
				user = u;
				//分发转向
				request.getSession().setAttribute("user", user);
				request.getRequestDispatcher("/index.jsp").forward(request, response);
			}else{
				response.getWriter().write("用户名或密码错误");
				response.setHeader("refresh", "1;url="+request.getContextPath()+"/index.jsp");
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		


	}

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

}
  1. com.lwb.servlet.RegServlet.java
package com.lwb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

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 org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import com.lwb.domain.User;
import com.lwb.domain.UserForm;
import com.lwb.exception.UserExistException;
import com.lwb.service.UserService;
import com.lwb.service.impl.UserServiceImpl;

public class RegServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		//验证操作
		UserForm uf = new UserForm();
		try {
			BeanUtils.populate(uf, request.getParameterMap());
			
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		if(!uf.validate()){//如果MAP不为空说明有错误信息
			request.setAttribute("uf", uf);
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
			
		}
		
		//获取表单数据
		User user = new User();
		try {
			//日期转换器
			ConvertUtils.register(new DateLocaleConverter(), Date.class);
			BeanUtils.populate(user, request.getParameterMap());

		//调用业务逻辑
			UserService us = new UserServiceImpl();
			//检查用户是否已经被注册
			us.findUserByName(user.getUsername());
			
			us.register(user);
		
		}catch (UserExistException e) {
			request.setAttribute("error", "用户名已存在");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		//分发转向
		response.getWriter().write("注册成功,1秒后跳转首页");
		response.setHeader("refresh", "1;url=" + request.getContextPath() +"/index.jsp");
		
		
	}

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

}
  1. com.lwb.utils.DButils.java
package com.lwb.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class DBUtils {
	private static String driverClass;
	private static String url;
	private static String username;
	private static String password;
	
	static{
		//此对象是用于加载properties文件数据的
		ResourceBundle rb = ResourceBundle.getBundle("dbinfo");
		driverClass = rb.getString("driverClass");
		url = rb.getString("url");
		username = rb.getString("username");
		password = rb.getString("password");
		try {
			Class.forName(driverClass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}		
	}
	
	//得到连接方法
	public static Connection getConnection()throws Exception{
		return DriverManager.getConnection(url,username,password);
	}
	
	//关闭资源的方法
	public static void clossAll(ResultSet rs,Statement stmt,Connection conn){
		//关闭资源
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			conn = null;
		}
	}
}
  1. dbinfo.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc\:mysql\:///
username=
password=

总结

学校在大二的时候交过SpringBoots的时候老师好像讲过但是当时JAVAWEB之前就学了一学期并且JAVA也没有教,所以压根没有听懂,后面再重新从黑马JAVA里面学习的时候,一开始蒙圈的,听过之后再自己写一遍,现在又在博客中理了一遍,现在大致清晰了,如果有什么错误可以告诉我。

相关标签: java