参考书籍:《J2EE开源编程精要15讲》

MVC(Model View Controller),Model(模型)表示业务逻辑层,View(视图)代表表述层,Controller(控制)表示控制层。

在Java Web应用程序中,

  View部分一般用JSP和HTML构建。客户在View部分提交请求,在业务逻辑层处理后,把结果返回给View部分显示

  Controller部分一般用Servlet组成,把用户的请求发给适当的业务逻辑组件处理;处理后又返回Controller,把结果转发给适当的View组件

  Model部分包括业务逻辑层和数据库访问层,一般由JavaBean或EJB(Enterprise JavaBean,企业级JavaBean)构建。数据访问层也叫数据持久层,与数据库打交道,常用JDBC API或Hibernate构建。

示例:

View部分:

  index.jsp

 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>登陆界面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<form method="post" action="LoginServlet">
用户名:<input type="text" name="username" size="15"><br><br>
密&nbsp&nbsp码:<input type="password" name="password" size="15"><br><br>
<input type="submit" name="submit" value="登陆"><br>
</form>
</body>
</html>

  main.jsp

 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>主页面</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<h1>
<%=session.getAttribute("username") %>,你成功登陆,现已进入主界面!
</h1>
</body>
</html>

  register.jsp

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>注册页面</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<h1>
<%=session.getAttribute("username") %>,你未能成功登陆。
<br>现已进入注册页面,请注册你的信息!
</h1>
</body>
</html>

Controller部分:

  LoginServlet.java

 /**
* 控制组件,在web.xml中将<servlet-mapping>标签内的<url-pattern>设置为"/LoginServlet",
* 所以能接受来自index.jsp中action="LoginServlet"的表单的HTTP POST请求
*/
package login; 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;
import javax.servlet.http.HttpSession; public class LoginServlet extends HttpServlet { /**
* Constructor of the object.
*/
public LoginServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response); } /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //获取请求中的用户名和密码
String username=request.getParameter("username");
String password=request.getParameter("password"); //生成一个Session对象,在main.jsp和register.jsp中可以根据Session对象获取用户名
HttpSession session=request.getSession(true);
session.removeAttribute("username");
session.setAttribute("username", username); //调用业务逻辑组件,检查该用户是否已注册
LoginHandler login=new LoginHandler();
boolean mark=login.checkLogin(username,password); //根据查询结果跳转
if(mark)
response.sendRedirect("main.jsp");
else
response.sendRedirect("register.jsp");
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

Model部分

  业务逻辑组件,LoginHandler.java

 /**
* 业务逻辑组件,从数据访问组件DBPool中获得数据库链接,检查用户记录是否存在
*/
package login; import java.sql.*; public class LoginHandler {
public LoginHandler(){} Connection conn;
PreparedStatement ps;
ResultSet rs; public boolean checkLogin(String username,String password){
DBPool con=new DBPool();
try{
conn=con.getConnection();
String sql="select * from UserInfo where username=? and password=?";
ps=conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs=ps.executeQuery();
if(rs.next()){
conn.close();
return true;
}
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
return false;
}
}

  数据库访问组件,DBPool.java (MySQL数据库)

 /**
* 数据访问组件,数据库类型为MySQL,
* 登陆数据库用户名:"root",
* 密码:"root",
* 数据库:"user",
* 表:"UserInfo"
*/
package login; import java.sql.*; public class DBPool {
public Connection getConnection() throws SQLException{
Connection con=null; try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8", "root", "root");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
return con;
}
}

配置文件web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Login_Proj</display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>login.LoginServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

应用实例 简单登陆系统:http://pan.baidu.com/s/1eQdAGqI

PS:使用环境Win7 64bit+MyEclipse Professional 2014+phpMyAdmin-2.10.3

Java Web编程的主要组件技术——MVC设计模式的更多相关文章

  1. Java Web编程的主要组件技术——Struts入门

    参考书籍:<J2EE开源编程精要15讲> Struts是一个开源的Java Web框架,很好地实现了MVC设计模式.通过一个配置文件,把各个层面的应用组件联系起来,使组件在程序层面联系较少 ...

  2. Java Web编程的主要组件技术——JDBC

    参考书籍:<J2EE开源编程精要15讲> JDBC(Java DataBase Connectivity)是Java Web应用程序开发的最主要API之一.当向数据库查询数据时,Java应 ...

  3. Java Web编程的主要组件技术——Hibernate核心组件

    参考书籍:<J2EE开源编程精要15讲> Hibernate配置文件 1) hibernate.cfg.xml <?xml version='1.0' encoding='UTF-8 ...

  4. Java Web编程的主要组件技术——Struts核心组件

    参考书籍:<J2EE开源编程精要15讲> Struts配置文件struts-config.xml Struts核心文件,可配置各种组件,包括Form Beans.Actions.Actio ...

  5. Java Web编程的主要组件技术——Servlet

    参考书籍:<J2EE开源编程精要15讲> Servlet是可以处理客户端传来的HTTP请求,并返回响应,由服务器端调用执行,有一定编写规范的Java类. 例如: package test; ...

  6. Java Web编程的主要组件技术——Hibernate入门

    参考书籍:<J2EE开源编程精要15讲> Hibernate是对象/关系映射(ORM,Object/Relational Mapping)的解决方案,就是将Java对象与对象关系映射到关系 ...

  7. Java Web编程的主要组件技术——Struts的高级功能

    参考书籍:<J2EE开源编程精要15讲> Struts对国际化的支持 "国际化"(I18N)指一个应用程序在运行时能根据客户端请求所来的国家/地区.语言的不同显示不同的 ...

  8. Java Web编程的主要组件技术——JSP

    参考书籍:<J2EE开源编程精要15讲> JSP(Java Server Page)页面由HTML代码和嵌入其中的Java代码组成. 简单的JSP页面如: <html> < ...

  9. [原创]java WEB学习笔记19:初识MVC 设计模式:查询,删除 练习(理解思想),小结 ,问题

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

随机推荐

  1. NYOJ-36 最长公共子序列 AC 分类: NYOJ 2014-01-03 20:54 155人阅读 评论(0) 收藏

    #include<stdio.h> #include<string.h> #define N 1010 #define max(x,y) x>y?x:y int dp() ...

  2. Mac OS X 安装并测试 OpenCV

    1. 安装 打开官网的Linux安装OpenCV的网页,打开这个网页的目的不是按照它所提供的步骤安装OpenCV(因为你会遇到一个坑,下文会提到),而是为了安装一些依赖的包或库. 其中的pkg-con ...

  3. uva 1056

    floyd 算法 用了stl 的map 存名字的时候比较方便 #include <cstdio> #include <cstdlib> #include <cmath&g ...

  4. 设置go语言语法高亮

    1. 将$GOROOT/misc/vim/go.vim文件拷贝到-/.vim/syntax/目录下 2. 添加下面代码到~/.vimrc文件中 let mysyntaxfile = "XXX ...

  5. Chpater 10: Sorting

    Internal Sort: Bubble  O(n2) Selection O(n2) Insertion O(n2) Shell O(nlogn) Merge O(nlogn) Heap O(nl ...

  6. 关于DotNetBar中DataGridViewX 自动全屏 Anchor属性无效问题

    由于在DataGridViewX 中使用了控件DataGridViewCheckBoxXColumn会导致 Anchor属性无效问题化,具体原因未知,建议改换为系统自带的DataGridViewChe ...

  7. 分布式内存对象缓存系统Memcached-概述

    全面掌握Memcached 1.       概述 Memcached是danga.com(运营LiveJournal的技术团队)开发的一套分布式内存对象缓存系统,是为了加快网站http://www. ...

  8. mysql外键详解

    1.1.MySQL中“键”和“索引”的定义相同,所以外键和主键一样也是索引的一种.不同的是MySQL会自动为所有表的主键进行索引,但是外键字段必须由用户进行明确的索引.用于外键关系的字段必须在所有的参 ...

  9. C语言的字符测试函数

    C语言的字符测试函数 isalnum, isalpha, isdigit, isxdigit, isblank, isspace, isascii, iscntrl, ispunct, isgraph ...

  10. JavaWeb项目开发案例精粹-第3章在线考试系统-002配置文件及辅助类

    1. <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5&qu ...