首先稍微解释一下MVC的含义,M(model),是指数据模型,这就和数据库有关了。V(view),是指视图,通俗讲应该就是网页界面,C(control)就是实现M和V之间的消息的沟通。
网站重要的两个部分就是数据库和界面,我们又通常称之为前台和后台,显然这两个有着密切的关系,但最好把这两个分离开来,或者说,把它们之间的千丝万缕的,隐隐约约的关系,搞的更清晰一些。有一个角色用来单独处理他们之间的关系比较好。这个就是C(control)。于是MVC结构应运而生了。
下面详细谈一下,自己实现的MVC。MVC的结构就是下面的这个图。
下面解释一下我写的代码:
首先是,浏览器发出请求,login,根据web.xml文件配置,请求到达ControlServlet。
ControlServlet解析请求路径,得到请求是login,然后根据mvc.pro(自己定义)的文件配置,
利用反射原理实例化相应的请求Action(本身是一个接口)类的对象,调用相应的方法,再
到ActionForward(专门负责跳转页面的类)里,跳转页面。
下面是代码:
三个包:web webAction webServlet
package web;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 连接数据库的代码
*
* @author txc
*
*/
public class DBlink {
/**
* 判断是是否登入成功的方法
*
* @param userName
* @param usePwd
* @return
* @throws SQLException
*/
public boolean userLogin(String userName, String usePwd)
throws SQLException {
// 这个是连接到数据库的方法
String sql = "select userPwd from userinfo where userName = '"
+ userName + "';";
ResultSet rs = linkDB().executeQuery(sql);
while (rs.next()) {
String pwd = rs.getString(1);
if (pwd.equals(usePwd)) {// 密码正确
return true;
}
}
return false;
}
/**
* 判断是否注册成功的方法
*
* @param userName
* @param userPwd
* @return
* @throws SQLException
*/
public boolean userResgister(String userName, String userPwd)
throws SQLException {
// return true ;
int len = userName.length();
if (len > 20) {
return false;
}
String sql = "select userName from userinfo where userName = '"
+ userName + "';";
ResultSet rs = linkDB().executeQuery(sql);
if (rs.next()) {// 如果存在的话,肯定不行的
// System.out.println("数据库查询了吗?");
// String name = rs.getString(1);
// System.out.println("数据库查询了吗?"+name);
return false;
} else {// 这个用户名没有被注册
sql = "insert into userinfo(userName ,userPwd)values ('"
+ userName + "','" + userPwd + "');";
linkDB().executeUpdate(sql);
return true;
}
}
/*
* 查询的方法
*/
public ResultSet inquire() throws SQLException {
String sql = "select * from userinfo ";
ResultSet rs = linkDB().executeQuery(sql);
return rs;
}
public void operation(int num) throws SQLException {
String sql = " delete from userinfo where id=" + num + ";";
linkDB().executeUpdate(sql);
}
/**
*
* @param sql
* sql代码
* @return 放回结果集对象
*/
private Statement linkDB() {
try {
// 装载对应数据库的驱动类
Class.forName("com.mysql.jdbc.Driver").newInstance();
// 数据库连接串
String dbURL = "jdbc:mysql://localhost:3306/wmszinfo";
// connection 代表程序与数据库的一个连接
Connection con = DriverManager.getConnection(dbURL, "root", "1929");
Statement state = con.createStatement(); // 用于执行sql语句的声明对象,执行后可以方法resultre对象
return state;
} catch (Exception g) {
g.printStackTrace();
}
return null;
}
}
webAction包
package webAction;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import webServlet.ActionForward;
public interface Action {
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) ;
}
这是loginAction类
package webAction;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import web.DBlink;
import webServlet.ActionForward;
public class LoginAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request,
HttpServletResponse response) {
ActionForward af = null;
DBlink db = new DBlink();
String userName = request.getParameter("userName");
String userpwd = request.getParameter("userPwd");
try {
if(db.userLogin(userName, userpwd)){
//如果登入成功
request.getSession().setAttribute("current",userName);
}
af = new ActionForward("index.jsp");//最终总是转到index页面
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return af;
}
}
这是ControlSevlet类
package webServlet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import webAction.Action;
/**
* Servlet implementation class ControlServlet
*/
public class ControlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Properties pro = new Properties();
/**
* @see HttpServlet#HttpServlet()
*/
public ControlServlet() {
super();
// TODO Auto-generated constructor stub
}
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String uri = request.getRequestURI();// 得到请求的路径
File file = new File(uri);
String filename = file.getName();// 只是为了得到login.Action
// 再去掉.Action
StringTokenizer st = new StringTokenizer(filename, ".");
String requestString = "";
if (st.hasMoreElements()) {
requestString = st.nextToken();// 现在是真正得到了login
}
//System.out.println();
// 根据 login得到相应的类
String classname = pro.get(requestString).toString();
try {
Action action = (Action) Class.forName(classname).newInstance();// 根据相应的请求创建相应的对象
// 调用相应的方法
ActionForward af = action.execute(request, response);// 若是登入则登入
// 跳转页面
af.forward(request, response);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void init(){
String path = "/WEB-INF/mvc.pro";
// 我们仔细看一下这些路径是什么意思
try {
pro.load(new FileReader(new File(this.getServletContext().getRealPath(
path))));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是页面跳转的类
package webServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 跳转页面的类
* @author txc
*
*/
public class ActionForward {
String path = "";
// 这是构造方法
public ActionForward(String path){
this.path = path;
}
public void forward(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//跳转页面
request.getRequestDispatcher(path).forward(request, response);
}
}
mvc.pro是一个自定义配置文件
里面的内容,类似于键值对
如:
login=webAction.LoginAction
register=webAction.RegisterAction
exit=webAction.ExitAction
另外它和web.xml放在相同的目录下面。这个文件的加载方法,在ControlServelt里面,即init方法。
<!--EndFragment--><!--EndFragment-->