参考书籍:《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. UVA 11149 Power of Matrix 快速幂

    题目链接: http://acm.hust.edu.cn/vjudge/contest/122094#problem/G Power of Matrix Time Limit:3000MSMemory ...

  2. BZOJ3550: [ONTAK2010]Vacation

    3550: [ONTAK2010]Vacation Time Limit: 10 Sec  Memory Limit: 96 MBSubmit: 91  Solved: 71[Submit][Stat ...

  3. [转载]如何申请淘宝app_key、app_secret、SessionKey?

    不知道如何申请淘宝开发平台的App Key?其实申请App key很简单,主要了解申请步骤以及各个App key的数据阶段状态就可以了!下面由淘客帝国为您做详细图文讲解!申请比较简单,不过为了新手能够 ...

  4. PAT-乙级-1048. 数字加密(20)

    1048. 数字加密(20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 本题要求实现一种数字加密方法.首先固 ...

  5. 【Entity Framework】 Entity Framework资料汇总

    Fluent API : http://social.msdn.microsoft.com/Search/zh-CN?query=Fluent%20API&Refinement=95& ...

  6. oracle 用户 多个表空间

    首先,授权给指定用户. 一个用户的默认表空间只能有一个,但是你可以试下用下面的语句为其授权在别的表空间中创建对像: alter user  username quota 0||unlimited on ...

  7. 【Unity3D】iOS 推送实现

    原地址:http://www.iappfan.com/%E3%80%90unity3d%E3%80%91ios-%E6%8E%A8%E9%80%81%E5%AE%9E%E7%8E%B0/ #impor ...

  8. Firefox下网页缩放时防止div被挤到下一层

    http://wu110cheng.blog.163.com/blog/static/13334965420121120102439190/ Firefox下网页缩放时防止div被挤到下一层 问题:三 ...

  9. Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    之前有一篇<5分钟构建spring web mvc REST风格HelloWorld>介绍了普通方式开发spring web mvc web service.接下来看看使用spring b ...

  10. C# 使用TimeSpan计算两个时间差

    转载:http://www.cnblogs.com/wifi/articles/2439916.html 可以加两个日期之间任何一个时间单位. private string DateDiff(Date ...