首页 > 学院 > 开发设计 > 正文

MVC模式构建JavaWeb程序【有图解有源码,易理解易掌握】

2019-11-14 09:19:43
字体:
来源:转载
供稿:网友

一、MVC设计模式基础

1.第一层V,即View,是视图层,通常情况下是jsp页面或HTML页面,JSP页面中主要由JSTL标签以及EL表达式来显示Servlet传来的数据,并且通过用户操作来传递数据给控制层。

2.第二层C,即Controller,是控制层,基本上是Servlet程序,接收来自视图层传来的数据,发送给第三层业务逻辑层,让其处理后,根据不同的数据,来控制视图层的显示,起到了数据与视图之间的桥梁作用。

3.第三层M,即Model,是组件层,控制着业务逻辑,接收控制层传来的数据,并与持久层(数据库)交互,反馈给控制层,所有的业务逻辑代码均在组件层内。

二、基于MVC设计模式开发javaWeb程序的图解。

这是一个简单的用Maven构建的JavaWeb程序,具有登录注册功能。下面是图解。

三、源代码

1.登录页面

<%@ 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>登录</title></head><body>	<h1>登录</h1>	<form action="LoginController" method="POST">		<input type="text" name="username"/>		<input type="passWord" name="password"/>		<input type="submit" name="submit"/>	</form>	</body></html>

2.注册页面

<%@ 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>注册</title></head><body>	<h1>注册</h1>	<form action="RegisterController" method="POST">		<input type="text" name="username"/>		<input type="password" name="password"/>		<input type="submit" name="submit"/>	</form></body></html>

3.登陆后的主页面

<%@ 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>主界面</title></head><body>	用户名:${sessionScope.userInfo.username }</body></html>

4.控制登录的servlet

package servlet.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.*;import dao.LoginHandler;import javabeans.UserInfo;public class LoginController extends HttpServlet {		@Override	PRotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{		doPost(request, response);	}	@Override	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{		response.setContentType("text/html");		UserInfo userInfo = new UserInfo();		userInfo.setUsername((String)request.getParameter("username"));		userInfo.setPassword((String)request.getParameter("password"));		LoginHandler handler = new LoginHandler();		if(handler.check(userInfo)){			HttpSession session = request.getSession(true);			session.setAttribute("userInfo", userInfo);			request.getRequestDispatcher("/WEB-INF/main.jsp").forward(request, response);		}else{			response.sendRedirect("login.jsp");		}	}}5.控制注册的servlet

package servlet.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.*;import dao.RegisterHandler;import javabeans.UserInfo;public class RegisterController extends HttpServlet {	@Override	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{		doPost(request, response);	}	@Override	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{		response.setContentType("text/html");		UserInfo userInfo = new UserInfo();		userInfo.setUsername(request.getParameter("username"));		userInfo.setPassword(request.getParameter("password"));		RegisterHandler handler = new RegisterHandler();		if(handler.register(userInfo)){			response.sendRedirect(getServletConfig().getServletContext().getContextPath() + "/login.jsp");		}else{			response.sendRedirect(getServletConfig().getServletContext().getContextPath() + "/register.jsp");		}	}}6.登录业务逻辑组件

package dao;import java.sql.*;import javabeans.UserInfo;import utils.DB;public class LoginHandler {		private boolean flag = false;	public boolean check(UserInfo userInfo){		DB db = new DB();		PreparedStatement pstmt = db.getPreparedStatement("SELECT * FROM user_table WHERE username=?");		try {			pstmt.setString(1, userInfo.getUsername());			ResultSet rs = pstmt.executeQuery();			while(rs.next()){				System.out.println(rs.getString(2));				if(userInfo.getPassword().equals(rs.getString(2))){					flag = true;				}			}		} catch (SQLException e) {			e.printStackTrace();		}		return flag;	}}7.注册业务逻辑组件

package dao;import java.sql.*;import javabeans.UserInfo;import utils.DB;public class RegisterHandler {		public boolean register(UserInfo userInfo){		DB db = new DB();		PreparedStatement pstmt = db.getPreparedStatement("SELECT * FROM user_table WHERE username=?");		try {			pstmt.setString(1, userInfo.getUsername());			ResultSet rs = pstmt.executeQuery();			if(rs.next()){				return false;			}			pstmt = db.getPreparedStatement("INSERT INTO user_table VALUES(?,?)");			pstmt.setString(1, userInfo.getUsername());			pstmt.setString(2, userInfo.getPassword());			pstmt.execute();			return true;		} catch (SQLException e) {			e.printStackTrace();			return false;		}	}}8.数据库操作组件
package utils;import java.sql.*;import java.util.logging.Logger;public class DB{	private Connection connection = null;	private ResultSet resultSet = null;	private Statement statement = null;	private String dbName = "db";	private String username = "root";	private String password = "admin";	private String url = "jdbc:MySQL://localhost:3306/" + dbName;	private Logger logger = Logger.getLogger(this.getClass().getName());	public DB(){};	public Connection connect()	{		try		{			//加载驱动			Class.forName("com.mysql.jdbc.Driver");			//此时MySQL的Driver已经加入到DriverManager中,然后连接数据库			connection = DriverManager.getConnection(url, username, password);		}		catch(Exception e)		{			logger.fine("连接失败");;			e.printStackTrace();		}		return connection;	}	//获得Statement类的对象,可以用此对象的方法执行sql语句	public Statement getStatement()	{		this.connect();		logger.info("con" + connection.toString());		try		{				statement = connection.createStatement();		}catch (Exception e)		{			logger.info("获取statement失败");			e.printStackTrace();		}				return statement;	}	public PreparedStatement getPreparedStatement(String sql){		this.connect();		PreparedStatement pstmt = null; 		try {			pstmt = connection.prepareStatement(sql);		} catch (SQLException e) {			logger.info("获取preparedstatement失败");		}		return pstmt;	}	//查询	public ResultSet query(String sql)	{		this.getStatement();		logger.info("sta" + statement.toString());		try		{			resultSet = statement.executeQuery(sql);		}		catch (Exception e) 		{			logger.info("获取结果集失败");			e.printStackTrace();		}		logger.info("res" + resultSet);		return resultSet;	}	//更新数据库	public int update(String sql)	{		int i = -1;		this.getStatement();		try		{			i = statement.executeUpdate(sql);			logger.info("插入后i=" + i);		}		catch(Exception e)		{			logger.info("更新失败");			e.printStackTrace();		}		return i;	}}

如有任何问题,可以私信我。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表