这几天复习了一下MVC,下面就是这几天的学习笔记,有错误的地方,欢迎大家批评指正。
去南京趋势科技参加实习面试的时候,面试官问了我一个问题:MVC是不是一种设计模式?当时我对MVC的理解还不够透彻,就回答了个是(最后趋势挂了!)。原因很简单,文献[1]P526中说MVC是一种复合模式,那当然是设计模式了。关于MVC到底是不是一种设计模式,等我们讨论完MVC后再说。先来说说什么是MVC。
M:Model 模型
负责真正的业务逻辑的处理,是MVC的核心, 模型不依赖于视图和控制器V:View 视图
视图比较简单,视图就是一个软件的用户界面(GUI),C: Controller 控制器
获取View中用户的输入,控制器会解释用户输入,并调用模型处理。
下面是他们之间的一个关系图
[1]P532
MVC主要由3个模式组合而成:组合模式,策略模式和观察者模式
其中视图由于是用户界面,使用了各种控件,控件之间采用了组合模式
视图需要使用控制器来处理用户的输入,如果要实现对用户输入的不同处理,可以更换控制器,他们之间实现了策略模式
视图是模型在屏幕上的显示,视图必须保证它的显示能够正确反映模型的状态,模型一旦发生变换,模型将会通知有关的视图[2]P3。这样,控制器和视图都可以作为模型的观察者,他们之间就实现了观察者模式。
下面我们举个例子,就会更加清楚的理解MVC各个部分之间的关系了
(注:对策略模式和观察者模式不太清楚的童鞋,需要先复习一下这两种模式哦!)
下面的小程序的功能就是一个节拍控制器,代码可以在这里下载(路径:combined\djview),建议大家将代码下载下来,然后运行一遍
其中有两个视图,一个是控制节拍的视图,一个是显示节拍的视图
这个就是控制节拍的视图,你可以输入节拍,下面按钮分别是设置节拍,减小和增加节拍
设置完了之后,就可以在显示界面上显示,此时,显示的是当前节拍:120
下面我们来看一下代码,分别看一下视图,控制器和模型的代码,由于代码很长,大家直接跳过代码,看类图部分。
package headfirst.combined.djview;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//视图
//BeatObserver,BPMObserver分别是视图实现的观察者接口
public class DJView implements ActionListener, BeatObserver, BPMObserver
{
BeatModelInterface model;//视图作为模型的观察者
ControllerInterface controller;//视图使用控制器作为处理用户输入的策略
JFrame viewFrame;
JPanel viewPanel;
BeatBar beatBar;
JLabel bpmOutputLabel;
JFrame controlFrame;
JPanel controlPanel;
JLabel bpmLabel;
JTextField bpmTextField;
JButton setBPMButton;
JButton increaseBPMButton;
JButton decreaseBPMButton;
JMenuBar menuBar;
JMenu menu;
JMenuItem startMenuItem;
JMenuItem stopMenuItem;
//视图需要使用控制器作为策略,同时视图成为模型的观察者
public DJView(ControllerInterface controller, BeatModelInterface model)
{
this.controller = controller;
this.model = model;
model.registerObserver((BeatObserver)this);
model.registerObserver((BPMObserver)this);
}
//显示节拍视图
public void createView()
{
// Create all Swing components here
//JPanel
bpmOutputLabel = new JLabel("offline", SwingConstants.CENTER);
beatBar = new BeatBar();
beatBar.setValue(0);
JPanel bpmPanel = new JPanel(new GridLayout(2, 1));
bpmPanel.add(beatBar);
bpmPanel.add(bpmOutputLabel);
//JPanel
viewPanel = new JPanel(new GridLayout(1, 2));
viewPanel.add(bpmPanel);
//JFrame
viewFrame = new JFrame("View");
viewFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
viewFrame.setSize(new Dimension(100, 80));
viewFrame.getContentPane().add(viewPanel, BorderLayout.CENTER);
viewFrame.pack();
viewFrame.setVisible(true);
}
//控制节拍视图
public void createControls()
{
/////////////////////////////JFrame//////////////////////////////////////
JFrame.setDefaultLookAndFeelDecorated(true);
controlFrame = new JFrame("Control");
controlFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlFrame.setSize(new Dimension(100, 80));
controlPanel = new JPanel(new GridLayout(1, 2));
/////////////////////////////Menubar//////////////////////////////////////
menuBar = new JMenuBar();
controlFrame.setJMenuBar(menuBar);
/////////////////////////////Menu//////////////////////////////////////
menu = new JMenu("DJ Control");
menuBar.add(menu);
//startMenuItem
startMenuItem = new JMenuItem("Start");
startMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
controller.start();
}
});
menu.add(startMenuItem);
//stopMenuItem
stopMenuItem = new JMenuItem("Stop");
stopMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
controller.stop();
}
});
menu.add(stopMenuItem);
//ExitMenuItem
JMenuItem exit = new JMenuItem("Quit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menu.add(exit);
///////////////////////////主体的上面部分//////////////////////////////////////
JPanel insideControlPanel = new JPanel(new GridLayout(3, 1));
//上面部分
JPanel enterPanel = new JPanel(new GridLayout(1, 2));
bpmLabel = new JLabel("Enter BPM:", SwingConstants.RIGHT);
bpmLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
bpmOutputLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
bpmTextField = new JTextField(2);
enterPanel.add(bpmLabel);
enterPanel.add(bpmTextField);
///////////////////////////主体的中间部分//////////////////////////////////////
//setBPMButton
setBPMButton = new JButton("Set");
setBPMButton.setSize(new Dimension(10,40));
setBPMButton.addActionListener(this);
///////////////////////////主体的下面部分//////////////////////////////////////
JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
//increaseBPMButton
increaseBPMButton = new JButton(">>");
increaseBPMButton.addActionListener(this);
buttonPanel.add(increaseBPMButton);
//decreaseBPMButton
decreaseBPMButton = new JButton("<<");
decreaseBPMButton.addActionListener(this);
buttonPanel.add(decreaseBPMButton);
insideControlPanel.add(enterPanel);
insideControlPanel.add(setBPMButton);
insideControlPanel.add(buttonPanel);
//添加顶层Panel
controlPanel.add(insideControlPanel);
controlFrame.getRootPane().setDefaultButton(setBPMButton);
//在JFrame中添加JPanel
controlFrame.getContentPane().add(controlPanel, BorderLayout.CENTER);
controlFrame.pack();
controlFrame.setVisible(true);
}
public void enableStopMenuItem() {
stopMenuItem.setEnabled(true);
}
public void disableStopMenuItem() {
stopMenuItem.setEnabled(false);
}
public void enableStartMenuItem() {
startMenuItem.setEnabled(true);
}
public void disableStartMenuItem() {
startMenuItem.setEnabled(false);
}
//按钮事件
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == setBPMButton)
{
int bpm = Integer.parseInt(bpmTextField.getText());
controller.setBPM(bpm);
}
else
if (event.getSource() == increaseBPMButton)
{
//将用户的输入交给控制器,这里为增加节拍
controller.increaseBPM();
}
else
if (event.getSource() == decreaseBPMButton)
{
controller.decreaseBPM();
}
}
//更新状态,这里作为观察者
public void updateBPM()
{
if (model != null)
{
int bpm = model.getBPM();
if (bpm == 0)
{
if (bpmOutputLabel != null)
{
bpmOutputLabel.setText("offline");
}
}
else
{
if (bpmOutputLabel != null)
{
bpmOutputLabel.setText("Current BPM: " + model.getBPM());
}
}
}
}
//更新状态,这里作为观察者
public void updateBeat()
{
if (beatBar != null) {
beatBar.setValue(100);
}
}
}
接口
package headfirst.combined.djview;
//控制器接口
//视图能够调用的控制器方法都在这里
public interface ControllerInterface
{
void start();
void stop();
void increaseBPM();
void decreaseBPM();
void setBPM(int bpm);
}
实现
package headfirst.combined.djview;
public class BeatController implements ControllerInterface
{
BeatModelInterface model;
DJView view;
//这里为什么要通过构造函数传递一个模型呢?而不是直接在控制器中实例化一个模型?
//因为实际上,模型是可以更换的,而且我们可以通过适配器模式,将一个非模型转换为模型,如后面的心脏适配器
public BeatController(BeatModelInterface model)
{
this.model = model;
view = new DJView(this, model);
view.createView();
view.createControls();
view.disableStopMenuItem();
view.enableStartMenuItem();
model.initialize();
}
public void start() {
model.on();
view.disableStartMenuItem();
view.enableStopMenuItem();
}
public void stop() {
model.off();
view.disableStopMenuItem();
view.enableStartMenuItem();
}
public void increaseBPM()
{
//控制器会解释用户输入,并调用模型处理
int bpm = model.getBPM();
model.setBPM(bpm + 1);
}
public void decreaseBPM()
{
int bpm = model.getBPM();
model.setBPM(bpm - 1);
}
public void setBPM(int bpm)
{
//交给模型处理
model.setBPM(bpm);
}
}
模型接口
package headfirst.combined.djview;
//模型是负责处理真正的业务逻辑
public interface BeatModelInterface
{
void initialize();
void on();
void off();
void setBPM(int bpm);
int getBPM();
//模型中实现了观察者模式
void registerObserver(BeatObserver o);
void removeObserver(BeatObserver o);
void registerObserver(BPMObserver o);
void removeObserver(BPMObserver o);
}
模型实现
package headfirst.combined.djview;
import javax.sound.midi.*;
import java.util.*;
//模型不依赖于视图和控制器,所以不需要有构造函数传递参数
public class BeatModel implements BeatModelInterface, MetaEventListener
{
Sequencer sequencer;
ArrayList beatObservers = new ArrayList();
ArrayList bpmObservers = new ArrayList();
int bpm = 90;
Sequence sequence;
Track track;
public void initialize() {
setUpMidi();
buildTrackAndStart();
}
public void on() {
sequencer.start();
setBPM(90);
}
public void off() {
setBPM(0);
sequencer.stop();
}
public void setBPM(int bpm)
{
this.bpm = bpm;
sequencer.setTempoInBPM(getBPM());
//状态发生改变,通知视图改变状态
notifyBPMObservers();
}
public int getBPM() {
return bpm;
}
void beatEvent() {
notifyBeatObservers();
}
public void registerObserver(BeatObserver o) {
beatObservers.add(o);
}
public void notifyBeatObservers() {
for(int i = 0; i < beatObservers.size(); i++) {
BeatObserver observer = (BeatObserver)beatObservers.get(i);
observer.updateBeat();
}
}
public void registerObserver(BPMObserver o) {
bpmObservers.add(o);
}
public void notifyBPMObservers()
{
for(int i = 0; i < bpmObservers.size(); i++) {
BPMObserver observer = (BPMObserver)bpmObservers.get(i);
observer.updateBPM();
}
}
public void removeObserver(BeatObserver o) {
int i = beatObservers.indexOf(o);
if (i >= 0) {
beatObservers.remove(i);
}
}
public void removeObserver(BPMObserver o) {
int i = bpmObservers.indexOf(o);
if (i >= 0) {
bpmObservers.remove(i);
}
}
public void meta(MetaMessage message) {
if (message.getType() == 47) {
beatEvent();
sequencer.start();
setBPM(getBPM());
}
}
public void setUpMidi() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.addMetaEventListener(this);
sequence = new Sequence(Sequence.PPQ,4);
track = sequence.createTrack();
sequencer.setTempoInBPM(getBPM());
} catch(Exception e) {
e.printStackTrace();
}
}
public void buildTrackAndStart() {
int[] trackList = {35, 0, 46, 0};
sequence.deleteTrack(null);
track = sequence.createTrack();
makeTracks(trackList);
track.add(makeEvent(192,9,1,0,4));
try {
sequencer.setSequence(sequence);
} catch(Exception e) {
e.printStackTrace();
}
}
public void makeTracks(int[] list) {
for (int i = 0; i < list.length; i++) {
int key = list[i];
if (key != 0) {
track.add(makeEvent(144,9,key, 100, i));
track.add(makeEvent(128,9,key, 100, i+1));
}
}
}
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
} catch(Exception e) {
e.printStackTrace();
}
return event;
}
}
我们先来看MVC中的第一个设计模式,组合模式,这个模式比较简单,看上面的代码,视图层用到了很多控件,包括JButton,JPanel等,这些对象很多会划分一组,并将该组对象当做一个对象使用
如下代码:
///////////////////////////主体的下面部分//////////////////////////////////////
JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
//increaseBPMButton
increaseBPMButton = new JButton(">>");
increaseBPMButton.addActionListener(this);
buttonPanel.add(increaseBPMButton);
//decreaseBPMButton
decreaseBPMButton = new JButton("<<");
decreaseBPMButton.addActionListener(this);
buttonPanel.add(decreaseBPMButton);
insideControlPanel.add(buttonPanel);
这里buttonPanel就被当做了一个对象使用
这个就是非常典型的组合模式了.
看视图层代码,BeatObserver,BPMObserver分别是视图实现的观察者接口
这里我们可以看到,视图使用了控制器作为处理用户输入的策略,同时视图作为模型的观察者,需要实现观察者接口
现在我们来增加节拍,点击增加节拍按钮,首先,视图层对增加节拍按钮响应的事件处理代码
//按钮事件
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == setBPMButton)
{
int bpm = Integer.parseInt(bpmTextField.getText());
controller.setBPM(bpm);
}
else
if (event.getSource() == increaseBPMButton)
{
//将用户的输入交给控制器,这里为增加节拍
controller.increaseBPM();
}
else
if (event.getSource() == decreaseBPMButton)
{
controller.decreaseBPM();
}
}
我们可以看到,视图将用户的输入交给控制器,那么控制器呢?看一下控制的处理用户输入的代码:
public void increaseBPM()
{
//控制器会解释用户输入,并调用模型处理
int bpm = model.getBPM();
model.setBPM(bpm + 1);
}
控制器交给了模型去处理了,模型实现了真正的业务逻辑的处理,我们看看模型的实现代码
public void setBPM(int bpm)
{
this.bpm = bpm;
sequencer.setTempoInBPM(getBPM());
//状态发生改变,通知视图改变状态
notifyBPMObservers();
}
模型处理完后,状态发生了改变,就需要通知视图,我状态改变了,你需要向用户展现,我们来看看notifyBPMObservers方法
public void notifyBPMObservers()
{
for(int i = 0; i < bpmObservers.size(); i++) {
BPMObserver observer = (BPMObserver)bpmObservers.get(i);
observer.updateBPM();
}
}
这个方法就通知了所有的观察者,更新状态,前面我们说过了视图实现了BPMObserver,所以视图会使用updateBPM方法更新界面
结合刚刚的图,我们再将它们之间的关系想一遍:视图将用户的输入交给控制器,控制器解读用户的输入,然后调用模型,由模型去处理真正的业务逻辑,模型的处理完后,告诉视图更新状态,将新的状态展示给用户。
如果现在要更换处理用户数据的方式,那么只需要更改控制器就可以了。这就实现了策略模式。
这就是一个比较典型的MVC模式。好了,现在我们回到刚刚的那个问题:MVC到底是不是一种设计模式?元芳,你怎么看?
参考文献[1]中说MVC是一种复合模式,理论上,应该算是一种设计模式吧,这里我想说说我个人的一点观点:我更喜欢把MVC看成是使用组合,策略和观察者模式而实现的一种软件结构。为什么会有这个想法?看完下面的内容,估计你也会同意我的观点。(有不同意见的同学,欢迎一起讨论哦)
经典MVC模式在Web上的应用,就产生了现在我们看到的Web三层结构,可以参考[1]P549
说到网站开发中的三层结构,上网一搜,一大推,这里我给出几篇我觉得写的比较好的
http://blog.csdn.net/yangyuankp/article/details/7880943
http://www.cnblogs.com/kelvin0916/archive/2012/09/24/2700264.html
好像大部分都喜欢将三层结构划分为:
表示层UI
业务逻辑层BLL
数据访问层DAL
下面说说我的理解,因为没有查到权威资料,所以可能理解上有错误,欢迎大家批评指正.
先来看看大家比较熟悉的Java Web
[1]P549
java Web的模式大致如上图
我更喜欢将整个后面部分理解为模型
JSP:视图
servlet:控制器
javabean:模型
下面举个例子,由于示例是本科写的一个小项目,代码写的比较挫,大家就将就看看吧,哈哈
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*,java.util.ArrayList" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel=stylesheet type=text/css href="images/common.css" />
<head>
<SCRIPT language=JavaScript>
function doSubmit(){
if (document.myform.username.value==""){
alert("登陆名不能为空!");
return false;
}
if (document.myform.password.value==""){
alert("密码不能为空!");
return false;
}
//document.myform.submit();
}
</SCRIPT>
</HEAD>
<form action="/RentCar/Login" method="post"><!--表单提交给/RentCar/Login 控制器,他是个servlet-->
<body leftMargin=0 topMargin=0 marginheight="0" marginwidth="0">
<TABLE border=0 cellSpacing=100 cellPadding=0 width="100%" height="100%">
<TR>
<TD><TABLE border=0 cellSpacing=0 cellPadding=0 width=526 align=center>
<TR>
<TD colSpan=2><IMG border=0
src="images/al_top.gif"></TD>
</TR>
<TR>
<TD colSpan=2><TABLE border=0 cellSpacing=0 cellPadding=0 width=526>
<TR>
<TD width=155><IMG border=0
src="images/al_username.gif"></TD>
<TD background=images/al_body_bg.gif
width=105><INPUT class=input_login
maxLength=20 size=15 name=userName></TD>
<TD width=93><IMG border=0
src="images/al_password.gif"></TD>
<TD background=images/al_body_bg.gif
width=105><INPUT class=input_login maxLength=20
size=15 type=password name=password></TD>
<TD width=68><IMG border=0
src="images/al_body_right.gif"></TD>
</TR>
</TABLE></TD>
</TR>
<TR>
<TD colSpan=2><TABLE border=0 cellSpacing=0 cellPadding=0 width=526>
<TR>
<TD width=77><IMG border=0
src="images/al_end_left.gif"></TD>
<TD width=339><TABLE border=0 cellSpacing=0 cellPadding=0 width=339>
<TR>
<TD height=49
background=images/al_end_bg.gif
align=middle>
<input type="radio" name="type" value="admin" checked/>管理员
<input type="radio" name="type" value="driver"/>司机
<input type="radio" name="type" value="servicer"/>客服<br> </TD>
</TR>
<TR>
<TD><IMG border=0
src="images/al_end_end.gif"></TD>
</TR>
</TABLE></TD>
<TD width=110><INPUT onclick="return doSubmit()" border=0
src="images/al_end_right.gif" width=110
height=88 type=image
name=Submit1></TD>
</TR>
</TABLE></TD>
</TR>
</TABLE>
<DIV></DIV>
<DIV style="DISPLAY: none">
<SCRIPT language=javascript charset=gb2312
src="images/click.htm"></SCRIPT>
</DIV>
<NOSCRIPT>
<IFRAME
src="images/sa.htm"></IFRAME>
</NOSCRIPT>
</BODY>
</HTML>
这里实现的是一个登陆界面,登陆者可以有3中身份,管理员Administrator,司机Driver,客户Servicer
我们来看这段代码
<form action="/RentCar/Login" method="post">
将表单提交给/RentCar/Login 他是个servlet,即我们说的控制器,那么这个控制器是怎么工作的呢?
package com.rentcar.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;
import javax.swing.JOptionPane;
import com.rentcar.dao.*;
import com.rentcar.form.*;
import com.rentcar.service.*;
public class Login extends HttpServlet {
/**
* Constructor of the object.
*/
public Login() {
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 {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* 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 {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
//PrintWriter out = response.getWriter();
AdministratorForm admin=new AdministratorForm();
DriverForm driver=new DriverForm();
ServicerForm servicer=new ServicerForm();
//控制器使用到的模型
AdministratorService adminService=new AdministratorService();
DriverService driverService=new DriverService();
ServicerService servicerSer=new ServicerService();
boolean loginStatus=false;
if("null".equals(request.getParameter("type")))
{
JOptionPane.showMessageDialog(null, "用户名密码错误");
//request.getRequestDispatcher("Administrator/WorkerLogin.jsp").forward(request,response);
response.sendRedirect("WorkerLogin.jsp");
}
else
if(request.getParameter("type").equals("admin"))//管理员登录
{
admin.setId(request.getParameter("userName").trim());
admin.setPassword(request.getParameter("password").trim());
loginStatus=adminService.login(admin);//由模型处理
System.out.println(request.getParameter("userName"));
System.out.println(request.getParameter("password"));
if(loginStatus==true)
{
request.getSession().setAttribute("userName",adminService.administratorSelectById(admin).getId());
request.getSession().setAttribute("password",adminService.administratorSelectById(admin).getPassword());
request.getRequestDispatcher("Administrator/index.html").forward(request,response);
}
else
{
JOptionPane.showMessageDialog(null, "用户名密码错误");
//request.getRequestDispatcher("Administrator/WorkerLogin.jsp").forward(request,response);
response.sendRedirect("WorkerLogin.jsp");
}
}
else
if(request.getParameter("type").equals("driver"))//司机登录
{
driver.setId(request.getParameter("userName").trim());
driver.setPassword(request.getParameter("password").trim());
loginStatus=driverService.login(driver);
DriverImpl driverImpl=new DriverImpl();
if(loginStatus==true)
{
request.getSession().setAttribute("userName",driverImpl.selectById(driver).getId());
request.getSession().setAttribute("password",driverImpl.selectById(driver).getPassword());
request.getRequestDispatcher("Driver/index.html").forward(request,response);
}
else
{
JOptionPane.showMessageDialog(null, "用户名密码错误");
// request.getRequestDispatcher("Administrator/WorkerLogin.jsp").forward(request,response);
response.sendRedirect("WorkerLogin.jsp");
}
}
else
if(request.getParameter("type").equals("servicer"))//用户登录
{
servicer.setId(request.getParameter("userName").trim());
servicer.setPassword(request.getParameter("password").trim());
loginStatus=servicerSer.login(servicer);
ServicerImpl servicerImpl=new ServicerImpl();
if(loginStatus==true)
{
request.getSession().setAttribute("userName",servicerImpl.selectById(servicer).getId());
request.getSession().setAttribute("password",servicerImpl.selectById(servicer).getPassword());
request.getRequestDispatcher("Servicer/index.html").forward(request,response);
}
else
{
JOptionPane.showMessageDialog(null, "用户名密码错误");
// request.getRequestDispatcher("Administrator/WorkerLogin.jsp").forward(request,response);
response.sendRedirect("WorkerLogin.jsp");
}
}
else
{
JOptionPane.showMessageDialog(null, "用户名密码错误");
//request.getRequestDispatcher("Administrator/WorkerLogin.jsp").forward(request,response);
response.sendRedirect("WorkerLogin.jsp");
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
其中doPost就是处理代码
我们分析其中的一段:
//控制器使用到的模型
AdministratorService adminService=new AdministratorService();
DriverService driverService=new DriverService();
ServicerService servicerSer=new ServicerService();
boolean loginStatus=false;
if("null".equals(request.getParameter("type")))
{
JOptionPane.showMessageDialog(null, "用户名密码错误");
//request.getRequestDispatcher("Administrator/WorkerLogin.jsp").forward(request,response);
response.sendRedirect("WorkerLogin.jsp");
}
else
if(request.getParameter("type").equals("admin"))//管理员登录
{
admin.setId(request.getParameter("userName").trim());
admin.setPassword(request.getParameter("password").trim());
loginStatus=adminService.login(admin);//由模型处理
System.out.println(request.getParameter("userName"));
System.out.println(request.getParameter("password"));
if(loginStatus==true)
{
request.getSession().setAttribute("userName",adminService.administratorSelectById(admin).getId());
request.getSession().setAttribute("password",adminService.administratorSelectById(admin).getPassword());
request.getRequestDispatcher("Administrator/index.html").forward(request,response);
}
else
{
JOptionPane.showMessageDialog(null, "用户名密码错误");
//request.getRequestDispatcher("Administrator/WorkerLogin.jsp").forward(request,response);
response.sendRedirect("WorkerLogin.jsp");
}
}
我们看看管理员登录过程:
控制器接受到用户输入,然后交给模型处理,模型处理完后,返回,并通知页面更新状态。这个处理过程是不是跟经典的MVC模式很像!
下面给出模型的实现
关于模型的实现,一般采用分层:
分为BLL,DAL层,同时使用了实体层,下面给出实现
AdministratorService
作为业务逻辑层,处理业务逻辑
package com.rentcar.service;
import java.util.ArrayList;
import com.rentcar.dao.*;
import com.rentcar.form.AdministratorForm;
import com.rentcar.form.BusForm;
import com.rentcar.form.CustomerForm;
import com.rentcar.form.DriverForm;
import com.rentcar.form.OrderInfoForm;
import com.rentcar.form.ServicerForm;
public class AdministratorService implements Administrator
{
//客户信息管理
public int customerInfoDelById(CustomerForm customerInfo) {
// TODO Auto-generated method stub
CustomerImpl cus=new CustomerImpl();
return cus.deleteCustomerById(customerInfo);
}
public int customerInfoDelByName(CustomerForm customerInfo) {
// TODO Auto-generated method stub
CustomerImpl cus=new CustomerImpl();
return cus.deleteCustomerByName(customerInfo);
}
public int customerInfoInsert(CustomerForm customerInfo) {
// TODO Auto-generated method stub
CustomerImpl cus=new CustomerImpl();
return cus.insertCustomer(customerInfo);
}
public int customerInfoUpdate(CustomerForm customerInfo) {
// TODO Auto-generated method stub
CustomerImpl cus=new CustomerImpl();
return cus.updateCustomer(customerInfo);
}
public ArrayList<CustomerForm> customerSelectAll() {
// TODO Auto-generated method stub
CustomerImpl cus=new CustomerImpl();
return cus.selectAll();
}
public CustomerForm customerSelectById(CustomerForm customerInfo) {
// TODO Auto-generated method stub
CustomerImpl cus=new CustomerImpl();
return cus.selectById(customerInfo);
}
public CustomerForm customerSelectByName(CustomerForm customerInfo) {
// TODO Auto-generated method stub
CustomerImpl cus=new CustomerImpl();
return cus.selectByName(customerInfo);
}
//司机信息管理
public int driverInfoDelById(DriverForm driverInfo) {
// TODO Auto-generated method stub
DriverImpl dri=new DriverImpl();
return dri.deleteDriverById(driverInfo);
}
public int driverInfoDelByName(DriverForm driverInfo) {
// TODO Auto-generated method stub
DriverImpl dri=new DriverImpl();
return dri.deleteDriverByName(driverInfo);
}
public int driverInfoInsert(DriverForm driverInfo) {
// TODO Auto-generated method stub
DriverImpl dri=new DriverImpl();
return dri.insertDriver(driverInfo);
}
public ArrayList<DriverForm> driverInfoSelectAll() {
DriverImpl dri=new DriverImpl();
return dri.selectAll();
}
public ArrayList<DriverForm> driverInfoSelectAllAvailable() {
DriverImpl dri=new DriverImpl();
return dri.selectAllAvailable();
}
public DriverForm driverInfoSelectById(DriverForm driverInfo) {
DriverImpl dri=new DriverImpl();
return dri.selectById(driverInfo);
}
public DriverForm driverInfoSelectByName(DriverForm driverInfo) {
DriverImpl dri=new DriverImpl();
return dri.selectByName(driverInfo);
}
public ArrayList<DriverForm> driverInfoSelectBySex(DriverForm driverInfo) {
DriverImpl dri=new DriverImpl();
return dri.selectBySex(driverInfo);
}
public int driverInfoUpdate(DriverForm driverInfo) {
DriverImpl dri=new DriverImpl();
return dri.updateDriver(driverInfo);
}
//管理员登录
public boolean login(AdministratorForm admin) {
AdministratorImpl ad=new AdministratorImpl();
String pwd=ad.selectById(admin).getPassword();
if(pwd!=null)
{
if(admin.getPassword().equals(pwd))
return true;
else
return false;
}
return false;
}
//客服信息管理
public int servicerInfoDelById(ServicerForm servicerInfo) {
ServicerImpl ser=new ServicerImpl();
return ser.deleteServicerById(servicerInfo);
}
public ServicerForm servicerInfoDelByName(ServicerForm servicerInfo) {
ServicerImpl ser=new ServicerImpl();
return ser.selectByName(servicerInfo);
}
public int servicerInfoInsert(ServicerForm servicerInfo) {
ServicerImpl ser=new ServicerImpl();
return ser.insertServicerForm(servicerInfo);
}
public int servicerInfoUpdate(ServicerForm servicerInfo) {
ServicerImpl ser=new ServicerImpl();
return ser.updateServicer(servicerInfo);
}
public ArrayList<ServicerForm> servicerSelectAll() {
ServicerImpl ser=new ServicerImpl();
return ser.selectAll();
}
public ServicerForm servicerSelectById(ServicerForm servicerInfo) {
ServicerImpl ser=new ServicerImpl();
return ser.selectById(servicerInfo);
}
public ServicerForm servicerSelectByName(ServicerForm servicerInfo) {
ServicerImpl ser=new ServicerImpl();
return ser.selectByName(servicerInfo);
}
//车辆信息管理
public int busInfoDeleteById(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.deleteBusById(busInfo);
}
public int busInfoDeleteByLicenseNumber(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.deleteBusByLicenseNumber(busInfo);
}
public int busInfoInsert(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.insertBus(busInfo);
}
public ArrayList<BusForm> busInfoSelectAll() {
BusImpl bus=new BusImpl();
return bus.selectAll();
}
public ArrayList<BusForm> busInfoSelectAllAvailable() {
BusImpl bus=new BusImpl();
return bus.selectAllAvailable();
}
public ArrayList<BusForm> busInfoSelectByBrand(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.selectByBrand(busInfo);
}
public ArrayList<BusForm> busInfoSelectByBrandAndModels(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.selectByBrandAndModels(busInfo);
}
public ArrayList<BusForm> busInfoSelectByBrandAndType(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.selectByBrandAndType(busInfo);
}
public BusForm busInfoSelectById(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.selectById(busInfo);
}
public BusForm busInfoSelectByLicenseNumber(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.selectByLicenseNumber(busInfo);
}
public ArrayList<BusForm> busInfoSelectByType(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.selectByType(busInfo);
}
public int busInfoUpdate(BusForm busInfo) {
BusImpl bus=new BusImpl();
return bus.updateBus(busInfo);
}
//订单信息管理
public int orderInfoDeleteById(OrderInfoForm orderInfo) {
OrderInfoImpl order=new OrderInfoImpl();
return order.deleteOrderInfoById(orderInfo);
}
public int orderInfoInsert(OrderInfoForm orderInfo) {
OrderInfoImpl order=new OrderInfoImpl();
return order.insertOrderInfo(orderInfo);
}
public ArrayList<OrderInfoForm> orderInfoSelectAll() {
OrderInfoImpl order=new OrderInfoImpl();
return order.selectAll();
}
public OrderInfoForm orderInfoSelectById(OrderInfoForm orderInfo) {
OrderInfoImpl order=new OrderInfoImpl();
return order.selectById(orderInfo);
}
public int orderInfoUpdate(OrderInfoForm orderInfo) {
OrderInfoImpl order=new OrderInfoImpl();
return order.updateOrderInfo(orderInfo);
}
public int administratorDeleteById(AdministratorForm administratorInfo) {
AdministratorImpl admin=new AdministratorImpl();
return admin.deleteAdministratorById(administratorInfo);
}
public int administratorDeleteByName(AdministratorForm administratorInfo) {
AdministratorImpl admin=new AdministratorImpl();
return admin.deleteAdministratorByName(administratorInfo);
}
public int administratorInsert(AdministratorForm administratorInfo) {
AdministratorImpl admin=new AdministratorImpl();
return admin.insertAdministrator(administratorInfo);
}
public ArrayList<AdministratorForm> administratorSelectAll() {
AdministratorImpl admin=new AdministratorImpl();
return admin.selectAll();
}
public AdministratorForm administratorSelectById(
AdministratorForm administratorInfo) {
AdministratorImpl admin=new AdministratorImpl();
return admin.selectById(administratorInfo);
}
public AdministratorForm administratorSelectByName(
AdministratorForm administratorInfo) {
AdministratorImpl admin=new AdministratorImpl();
return admin.selectByName(administratorInfo);
}
public int administratorUpdate(AdministratorForm administratorInfo) {
AdministratorImpl admin=new AdministratorImpl();
return admin.updateAdministrator(administratorInfo);
}
}
AdministratorImpl
作为数据访问层,负责对Administrator的增,删,改,查,这里注意,DAL只负责对数据库中每张表的增,删,改,查。
package com.rentcar.dao;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.rentcar.form.AdministratorForm;
import com.rentcar.tools.DataManager;
public class AdministratorImpl implements Administrator
{
public int insertAdministrator(AdministratorForm administratorForm)
{
DataManager dataManager=new DataManager();
int result=0;
String id=administratorForm.getId();
String name=administratorForm.getName();
String sex=administratorForm.getSex();
String password=administratorForm.getPassword();
String telephone=administratorForm.getTelephone();
String address=administratorForm.getAddress();
String qq=administratorForm.getQq();
String mailbox=administratorForm.getMailbox();
String cmdString="insert into Administrator values(‘"+id+"‘,‘"+name+"‘,‘"+sex+"‘,‘"+password+"‘,‘"+telephone+"‘,‘"+address+"‘,‘"+qq+"‘,‘"+mailbox+"‘)";
try
{
result=dataManager.executeUpdate(cmdString);
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
public int deleteAdministratorById(AdministratorForm administratorForm)
{
DataManager dataManager=new DataManager();
int result=0;
String id=administratorForm.getId();
String cmdString="delete from Administrator where id=‘"+id+"‘";
try
{
result=dataManager.executeUpdate(cmdString);
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
public int deleteAdministratorByName(AdministratorForm administratorForm)
{
DataManager dataManager=new DataManager();
int result=0;
String name=administratorForm.getName();
String cmdString="delete from Administrator where name=‘"+name+"‘";
try
{
result=dataManager.executeUpdate(cmdString);
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
public int updateAdministrator(AdministratorForm administratorForm)
{
DataManager dataManager=new DataManager();
int result=0;
String id=administratorForm.getId();
String newName=administratorForm.getName();
String newSex=administratorForm.getSex();
String newPassword=administratorForm.getPassword();
String newTelephone=administratorForm.getTelephone();
String newAddress=administratorForm.getAddress();
String newQq=administratorForm.getQq();
String newMailbox=administratorForm.getMailbox();
String cmdString="update Administrator set id=‘"+id+"‘,name=‘"+newName+"‘,sex=‘"+newSex+"‘,password=‘"+newPassword+"‘,telephone=‘"+newTelephone+"‘,address=‘"+newAddress+"‘,qq=‘"+newQq+"‘,mailbox=‘"+newMailbox+"‘ where id=‘"+id+"‘";
try
{
result=dataManager.executeUpdate(cmdString);
}
catch (Exception e)
{
e.printStackTrace();
// TODO: handle exception
}
return result;
}
public AdministratorForm selectById(AdministratorForm administratorForm)
{
DataManager dataManager=new DataManager();
String id=administratorForm.getId();
String cmdString="select * from Administrator where id=‘"+id+"‘";
AdministratorForm administratorForm2=new AdministratorForm();
try
{
ResultSet rs=dataManager.executeQuery(cmdString);
while(rs.next())
{
administratorForm2.setId(rs.getString(1));
administratorForm2.setName(rs.getString(2));
administratorForm2.setSex(rs.getString(3));
administratorForm2.setPassword(rs.getString(4));
administratorForm2.setTelephone(rs.getString(5));
administratorForm2.setAddress(rs.getString(6));
administratorForm2.setQq(rs.getString(7));
administratorForm2.setMailbox(rs.getString(8));
}
}
catch (Exception e)
{
e.printStackTrace();
// TODO: handle exception
}
dataManager.closeConnection();
return administratorForm2;
}
public AdministratorForm selectByName(AdministratorForm administratorForm)
{
DataManager dataManager=new DataManager();
String name=administratorForm.getName();
String cmdString="select * from Administrator where name=‘"+name+"‘";
AdministratorForm administratorForm2=new AdministratorForm();
try
{
ResultSet rs=dataManager.executeQuery(cmdString);
while(rs.next())
{
administratorForm2.setId(rs.getString(1));
administratorForm2.setName(rs.getString(2));
administratorForm2.setSex(rs.getString(3));
administratorForm2.setPassword(rs.getString(4));
administratorForm2.setTelephone(rs.getString(5));
administratorForm2.setAddress(rs.getString(6));
administratorForm2.setQq(rs.getString(7));
administratorForm2.setMailbox(rs.getString(8));
}
}
catch (Exception e)
{
e.printStackTrace();
// TODO: handle exception
}
dataManager.closeConnection();
return administratorForm2;
}
public ArrayList<AdministratorForm> selectAll()
{
DataManager dataManager=new DataManager();
String cmdString="select * from Administrator";
ArrayList<AdministratorForm> list=new ArrayList<AdministratorForm>();
AdministratorForm administratorForm=null;
try
{
ResultSet rs=dataManager.executeQuery(cmdString);
while(rs.next())
{
administratorForm=new AdministratorForm();
administratorForm.setId(rs.getString(1));
administratorForm.setName(rs.getString(2));
administratorForm.setSex(rs.getString(3));
administratorForm.setPassword(rs.getString(4));
administratorForm.setTelephone(rs.getString(5));
administratorForm.setAddress(rs.getString(6));
administratorForm.setQq(rs.getString(7));
administratorForm.setMailbox(rs.getString(8));
list.add(administratorForm);
}
}
catch (Exception e)
{
e.printStackTrace();
// TODO: handle exception
}
dataManager.closeConnection();
return list;
}
}
他实现的接口Administrator:
package com.rentcar.dao;
import java.util.ArrayList;
import com.rentcar.form.AdministratorForm;
public interface Administrator
{
public int insertAdministrator(AdministratorForm administratorForm);
public int deleteAdministratorById(AdministratorForm administratorForm);
public int deleteAdministratorByName(AdministratorForm administratorForm);
public int updateAdministrator(AdministratorForm administratorForm);
public AdministratorForm selectById(AdministratorForm administratorForm);
public AdministratorForm selectByName(AdministratorForm administratorForm);
public ArrayList<AdministratorForm> selectAll();
}
AdministratorForm
实体层
package com.rentcar.form;
import java.sql.Date;
public class AdministratorForm
{
private String id;
private String name;
private String sex;
private String password;
private String telephone;
private String address;
private String qq;
private String mailbox;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getMailbox() {
return mailbox;
}
public void setMailbox(String mailbox) {
this.mailbox = mailbox;
}
}
DBUtility
数据库操作类
package com.rentcar.tools;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Connection;
//这个就是数据库操作类
public class DataManager
{
//JDBC类
String drive= "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url= "jdbc:sqlserver://localhost:1433; DatabaseName=RentCar";
String user="sa";
String password="654393155";
Connection conect = null;
Statement stmt=null;
ResultSet rs = null;
public DataManager()
{
try
{
Class.forName(drive);
}
catch (java.lang.ClassNotFoundException e)
{
e.printStackTrace();
}
}
public Connection getConnection()
{
try
{
conect=DriverManager.getConnection(url,user,password);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return conect;
}
public ResultSet executeQuery(String sql)
{
try
{
conect = DriverManager.getConnection(url,user,password);
stmt = conect.createStatement();
rs = stmt.executeQuery(sql);
}
catch (SQLException ex)
{
ex.printStackTrace();
}
return rs;
}
public int executeUpdate(String sql)
{
int result = 0;
try
{
conect = DriverManager.getConnection(url,user,password);
stmt = conect.createStatement();
result = stmt.executeUpdate(sql);
}
catch (SQLException er)
{
er.printStackTrace();
}
closeConnection();
return result;
}
public void closeResultSet()
{
try
{
if (rs!= null)
{
rs.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void closeStatement()
{
try
{
if (stmt != null)
{
stmt.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void closeConnection() //关闭数据库连接
{
try
{
if (conect != null)
{
conect.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
总结一下,他们之间的关系图如下:
下面再来分析一下ASP.NET中的三层结构
ASP.NET中
.aspx: 视图层
.aspx.cs: 每个.aspx页面都会有一个.aspx.cs文件,原来我一直不理解这个文件有啥作用,现在发现,他的作用就相当于是控制器,处理视图中用户的输入,然后交给模型处理
.cs: 模型
下面举个例子,示例程序为本科毕业设计,也是以登录模块为例,
.aspx就省略了
.aspx.cs登录代码为
//控制器
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (TextBox1.Text == Session["validate"].ToString())//TextBox1.Text == Session["validate"].ToString()
{
String name, password;
//判断用户名密码是否为空
if (userName.Text == "" || userPassword.Text == "")
{
Response.Write("<script language=javascript>alert(‘用户名密码不能为空!‘)</script>");
}
else
{
//判断用户类型
if (userCategory.Items[0].Selected == false && userCategory.Items[1].Selected == false)
{
Response.Write("<script language=javascript>alert(‘请选择用户类型‘)</script>");
}
else
{
if (userCategory.Items[0].Selected == true)//学生登录
{
Session["userCategory"] = "student";
Session["userCategoryCht"] = "学生";
Session["userId"] = userName.Text;
name = userName.Text;
password = userPassword.Text;
//实体层
StudentEntity studentEntity = new StudentEntity();
studentEntity.StudentId = name;
//交给模型处理
BLL.Login login1 = new BLL.Login();
studentEntity = login1.StudentLogin(studentEntity);
if (studentEntity.StudentId != null)
{
//学生登录成功
Response.Redirect("Student/index.aspx");
//Response.Write("<script language=javascript>alert(‘学生登录成功‘)</script>");
}
else
{
//学生登录失败
Response.Write("<script language=javascript>alert(‘学生登录失败‘)</script>");
}
}
else//教师登录
{
Session["userCategory"] = "teacher";
Session["userCategoryCht"] = "教师";
Session["userId"] = userName.Text;
name = userName.Text;
password = userPassword.Text;
TeacherEntity teacherEntity = new TeacherEntity();
teacherEntity.TeacherId = name;
BLL.Login login1 = new BLL.Login();
teacherEntity = login1.TeacherLogin(teacherEntity);
if (teacherEntity.TeacherId != null)
{
//教师登录成功
Response.Redirect("Teacher/index.aspx");
//Response.Write("<script language=javascript>alert(‘教师登录OK!‘)</script>");
}
else
{
//教师登录失败
Response.Write("<script language=javascript>alert(‘教师登录失败‘)</script>");
}
}
}
}
}
else
{
Response.Write("<script language=javascript>alert(‘验证码错误‘)</script>");
}
}
其中模型与java web一样,也是分层的
分为了BLL,DAL层,同时使用了实体层,关于BLL,DAL,和实体层,可以参考刚刚提到的两篇博客,讲解的比较透彻
public class Login
{
//学生登录业务逻辑
public StudentEntity StudentLogin(StudentEntity studentEntity)
{
//交给DAL处理
StudentDALInterface studentImp = new StudentDAL();
StudentEntity newStudentEntity = studentImp.SelectById(studentEntity);
return newStudentEntity;
}
public TeacherEntity TeacherLogin(TeacherEntity teacherEntity)
{
TeacherImp teacherImp = new TeacherImp();
Console.WriteLine("Hello world!");
TeacherEntity newTeacherEntity = teacherImp.SelectById(teacherEntity);
return newTeacherEntity;
}
}
StudentDALInterface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
namespace DALInterface
{
public interface StudentDALInterface
{
bool InsertStudent(StudentEntity student);
bool DeleteStudentById(StudentEntity student);
bool DeleteStudentByName(StudentEntity student);
bool UpdateStudentById(StudentEntity student);
bool UpdateStudentByName(StudentEntity student);
StudentEntity SelectById(StudentEntity student);
StudentEntity SelectByName(StudentEntity student);
}
}
StudentDAL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DALInterface;
using Tools;
using Entity;
using System.Data.SqlClient;
namespace DAL
{
public class StudentDAL : StudentDALInterface
{
DBUtility dataAccess = new DBUtility();
public bool InsertStudent(StudentEntity student)
{
String studentId = student.StudentId;
String studentName = student.StudentName;
String college = student.College;
String studentClass = student.StudentClass;
bool sex = student.Sex;
String studentEmail = student.StudentEmail;
String studentTel = student.StudentTel;
String sqlString = "insert into StudentInfo values(‘"+studentId+"‘,‘"+studentName+"‘,‘"+college+"‘,‘"+studentClass+"‘,"+sex+",‘"+studentEmail+"‘,‘"+studentTel+"‘)";
return dataAccess.ExecSql(sqlString);
}
public bool DeleteStudentById(StudentEntity student)
{
String studentId = student.StudentId;
String sqlString = "delete from StudentInfo where studentId=‘" + studentId + "‘";
return dataAccess.ExecSql(sqlString);
}
public bool DeleteStudentByName(StudentEntity student)
{
String studentName = student.StudentName;
String sqlString = "delete from StudentInfo where studentName=‘" + studentName+ "‘";
return dataAccess.ExecSql(sqlString);
}
public bool UpdateStudentById(StudentEntity student)
{
String studentId = student.StudentId;
String studentName = student.StudentName;
String college = student.College;
String studentClass = student.StudentClass;
bool sex = student.Sex;
String studentEmail = student.StudentEmail;
String studentTel = student.StudentTel;
String sqlString = "update StudentInfo set studentId=‘"+studentId+"‘,studentName=‘"+studentName+"‘,college=‘"+college+"‘,class=‘"+studentClass+"‘,sex="+sex+",studentEmail=‘"+studentEmail+"‘,studentTel=‘"+studentTel+"‘ where studentId=‘"+studentId+"‘";
return dataAccess.ExecSql(sqlString);
}
public bool UpdateStudentByName(StudentEntity student)
{
String studentId = student.StudentId;
String studentName = student.StudentName;
String college = student.College;
String studentClass = student.StudentClass;
bool sex = student.Sex;
String studentEmail = student.StudentEmail;
String studentTel = student.StudentTel;
String sqlString = "update StudentInfo set studentId=‘" + studentId + "‘,studentName=‘" + studentName + "‘,college=‘" + college + "‘,class=‘" + studentClass + "‘,sex=" + sex + ",studentEmail=‘" + studentEmail + "‘,studentTel=‘" + studentTel + "‘ where studentName=‘" + studentName + "‘";
return dataAccess.ExecSql(sqlString);
}
public StudentEntity SelectById(StudentEntity student)
{
String studentId = student.StudentId;
StudentEntity newStudent=new StudentEntity();
String sqlString = "select * from StudentInfo where studentId=‘" + studentId + "‘";
SqlDataReader dataReader = dataAccess.GetDataReader(sqlString);//这里的dataAccess就是DBUtility
while (dataReader.Read())
{
newStudent.StudentId = dataReader[0].ToString();
newStudent.StudentName = dataReader[1].ToString();
newStudent.College = dataReader[2].ToString();
newStudent.StudentClass = dataReader[3].ToString();
newStudent.Sex = Convert.ToBoolean(dataReader[4]);
newStudent.StudentEmail = dataReader[5].ToString();
newStudent.StudentTel = dataReader[6].ToString();
}
dataAccess.CloseConnection();
return newStudent;
}
public StudentEntity SelectByName(StudentEntity student)
{
String studentName = student.StudentName;
StudentEntity newStudent = new StudentEntity();
String sqlString = "select * from StudentInfo where studentName=‘" + studentName + "‘";
SqlDataReader dataReader = dataAccess.GetDataReader(sqlString);
while (dataReader.Read())
{
newStudent.StudentId = dataReader[0].ToString();
newStudent.StudentName = dataReader[1].ToString();
newStudent.College = dataReader[2].ToString();
newStudent.StudentClass = dataReader[3].ToString();
newStudent.Sex = Convert.ToBoolean(dataReader[4]);
newStudent.StudentEmail = dataReader[5].ToString();
newStudent.StudentTel = dataReader[6].ToString();
}
dataAccess.CloseConnection();
return newStudent;
}
}
}
工程结构如下图
java Web和ASP.Net都说完了,下面总结一下,他们可以用下面的一张图表示
由于图片比较大,网页上可能看不清楚,我上传到CSDN上了,大家可以下载,点击下载
今天是端午节,昨天在京东上买的粽子才到,早上跟室友一起吃买回来的粽子,好开心,哈哈。今天没有回去,也没有出去找同学玩,就想一个人在学校看书,因为发现自己有很多东西需要学习,想多用点时间看点书,计算机的世界美妙而又神奇,从算法到软件体系结构,到各种编程语言,再到计算机视觉领域,无不充满了迷人的魅力!今天总结了一下这几天看的MVC模式,写了篇博客,感觉充实而又快乐。下个月就要去杭州的海康威视实习了,未来的路就想计算机世界一样,美妙而又神奇。最后,祝大家端午节快乐!
原文地址:http://blog.csdn.net/qianqing13579/article/details/46576225