Java Web编程的主要组件技术——MVC设计模式
参考书籍:《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>
密  码:<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设计模式的更多相关文章
- Java Web编程的主要组件技术——Struts入门
参考书籍:<J2EE开源编程精要15讲> Struts是一个开源的Java Web框架,很好地实现了MVC设计模式.通过一个配置文件,把各个层面的应用组件联系起来,使组件在程序层面联系较少 ...
- Java Web编程的主要组件技术——JDBC
参考书籍:<J2EE开源编程精要15讲> JDBC(Java DataBase Connectivity)是Java Web应用程序开发的最主要API之一.当向数据库查询数据时,Java应 ...
- Java Web编程的主要组件技术——Hibernate核心组件
参考书籍:<J2EE开源编程精要15讲> Hibernate配置文件 1) hibernate.cfg.xml <?xml version='1.0' encoding='UTF-8 ...
- Java Web编程的主要组件技术——Struts核心组件
参考书籍:<J2EE开源编程精要15讲> Struts配置文件struts-config.xml Struts核心文件,可配置各种组件,包括Form Beans.Actions.Actio ...
- Java Web编程的主要组件技术——Servlet
参考书籍:<J2EE开源编程精要15讲> Servlet是可以处理客户端传来的HTTP请求,并返回响应,由服务器端调用执行,有一定编写规范的Java类. 例如: package test; ...
- Java Web编程的主要组件技术——Hibernate入门
参考书籍:<J2EE开源编程精要15讲> Hibernate是对象/关系映射(ORM,Object/Relational Mapping)的解决方案,就是将Java对象与对象关系映射到关系 ...
- Java Web编程的主要组件技术——Struts的高级功能
参考书籍:<J2EE开源编程精要15讲> Struts对国际化的支持 "国际化"(I18N)指一个应用程序在运行时能根据客户端请求所来的国家/地区.语言的不同显示不同的 ...
- Java Web编程的主要组件技术——JSP
参考书籍:<J2EE开源编程精要15讲> JSP(Java Server Page)页面由HTML代码和嵌入其中的Java代码组成. 简单的JSP页面如: <html> < ...
- [原创]java WEB学习笔记19:初识MVC 设计模式:查询,删除 练习(理解思想),小结 ,问题
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
随机推荐
- Matlab与微积分计算
一.极限问题的解析解 1.1 单变量函数的极限 格式1: L= limit( fun, x, x0) 格式2: L= limit( fun, x, x0, ‘left’ 或 ‘right’) > ...
- 【技术贴】解决bug mantisbt APPLICATION ERROR #1502 没有找到类别
解决bug mantisAPPLICATION ERROR #1502 没有找到类别 mantisbt出现1502问题解决:引起问题的原因:当提交的问题有分类,此时删除此分类,就会出现下面的情况.问题 ...
- 基于 Eclipse 平台的代码生成技术
------------------------------------------------------------------ 转自http://www.ibm.com/developerwor ...
- 高性能网络编程2----TCP消息的发送
转 陶辉 taohui.org.cn 在上一篇中,我们已经建立好的TCP连接,对应着操作系统分配的1个套接字.操作TCP协议发送数据时,面对的是数据流.通常调用诸如send或者write方法来发送数据 ...
- Boost简介
原文链接: 吴豆豆http://www.cnblogs.com/gdutbean/archive/2012/03/30/2425201.html Boost库 Boost库是为C++语言标准库提供扩 ...
- TYVJ P1016 装箱问题
P1016 装箱问题 时间: 1000ms / 空间: 131072KiB / Java类名: Main 背景 太原成成中学第2次模拟赛 第三道 描述 有一个箱子容量为v(正整数,o≤v≤20000) ...
- lintcode:两个数的和
题目 两数之和 给一个整数数组,找到两个数使得他们的和等于一个给定的数target. 你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标.注意这里下标的范围是1到n,不 ...
- HTML5入门4---HTML5 与 HTML4 同一网页的不同写法
HTML4写法 css: body { font-family: "Lucida Sans Unicode", "Lucida Grande", Verdana ...
- VIM Taglist + ctags
Windows下 进入http://ctags.sourceforge.net/ 下载ctags 把ctags58.zip解压,随便放个地方,我放到了Home\Vim\vim72下,在ctags58文 ...
- Jdk命令之jps
jps -- Java Virtual Machine Process Status Tool jps命令类似于Linux下的ps命令,可以列出本机所有正在运行的java进程.