一、MVC
MVC 模式代表 Model-View-Controller(模型-视图-控制器) 模式。这种模式用于应用程序的分层开发。
Model(模型) - 模型代表一个存取数据的对象或 JAVA POJO。它也可以带有逻辑,在数据变化时更新控制器。
View(视图) - 视图代表模型包含的数据的可视化。
Controller(控制器) - 控制器作用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图。它使视图与模型分离开。
二、用代码来实现登录和注册
1、dao包,主要用来定义相关接口,并且需要相关的实现接口的方法,主要用来链接数据库;
(1)、登录接口
package com.openlab.dao;
public interface Login {
public String doLogin(String _username,String _password);
}
(2)、注册接口
package com.openlab.dao;
import com.openlab.pojo.Employee;
public interface Register {
public String doRegister(Employee _employee);
}
2、完成dao包中接口的实现
(1)、实现登录接口
package com.openlab.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.openlab.Utils.DBConn;
import com.openlab.dao.Login;
public class LoginImpl implements Login{
//验证登录是否成功
public String doLogin(String _username,String _password){
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
String result="";
String sql="select * from loginuser where userName=? and userPwd=?";
try {
//conn=DbConnUtils.getConnection();
DBConn db=new DBConn();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
pst.setString(1, _username);
pst.setString(2, _password);
rs= pst.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs.next()){
result= "success";
}else{
result= "fail";
}
//DbConnUtils.closeAll(rs, pst, conn);
DBConn.closeAll(rs, pst, null);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
(2)、实现注册接口
package com.openlab.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.openlab.Utils.DbConnUtils;
import com.openlab.dao.Register;
import com.openlab.pojo.Employee;
public class RegisterImpl implements Register{
public String doRegister(Employee _employee){
Connection conn=null;
PreparedStatement pst=null;
String result="";
int count=0;
String sql="insert into loginuser(userName,userPwd,userRePwd,sex,princal,email) values(?,?,?,?,?,?)";
try {
conn=DbConnUtils.getConnection();
pst=conn.prepareStatement(sql);
pst.setString(1, _employee.getRegisterName());
pst.setString(2, _employee.getRepassword());
pst.setString(3, _employee.getRerepassword());
pst.setInt(4, _employee.getSex());
pst.setString(5, _employee.getPrical());
pst.setString(6, _employee.getEmail());
count=pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
if(count>0){
result= "success";
}else{
result= "fail";
}
DbConnUtils.closeAll(null,pst, conn);
return result;
}
}
3、创建实体类
package com.openlab.pojo;
public class Employee {
private String RegisterName;
private String repassword;
private String rerepassword;
private int sex;
private String prical;
private String email;
public String getRegisterName() {
return RegisterName;
}
public void setRegisterName(String registerName) {
RegisterName = registerName;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public String getRerepassword() {
return rerepassword;
}
public void setRerepassword(String rerepassword) {
this.rerepassword = rerepassword;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getPrical() {
return prical;
}
public void setPrical(String prical) {
this.prical = prical;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
4、创建服务登录和注册的接口
(1)、创建服务登录接口
package com.openlab.service;
import com.openlab.pojo.Employee;
public interface LoginService {
public String Login(Employee _Employee);
}
(2)、创建服务注册接口
package com.openlab.service;
import com.openlab.pojo.Employee;
public interface RegisterService {
public String Register(Employee _employee);
}
5、同dao包一样,实现服务层的接口
(1)、实现服务层登录的接口
package com.openlab.service.impl;
import com.openlab.dao.Login;
import com.openlab.dao.impl.LoginImpl;
import com.openlab.pojo.Employee;
import com.openlab.service.LoginService;
public class LoginServiceImpl implements LoginService {
Login login=null;
public String Login(Employee _Employee) {
login=new LoginImpl();
return login.doLogin(_Employee.getRegisterName(), _Employee.getRepassword());
}
}
(2)、实现服务层注册的接口
package com.openlab.service.impl;
import com.openlab.dao.Register;
import com.openlab.dao.impl.RegisterImpl;
import com.openlab.pojo.Employee;
import com.openlab.service.RegisterService;
public class RegisterServiceImpl implements RegisterService {
Register register=null;
public String Register(Employee _employee) {
register=new RegisterImpl();
return register.doRegister(_employee);
}
}
6、创建工具类
(1)、用jdbc写创建链接的方法
package com.openlab.Utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConn {
public Connection conn;
Context ctx = null;
// 定义创建连接的方法
public Connection getConnection() {
try {
ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/hospital");
conn = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet rs, Statement st, Connection conn) {
// 关闭结果集
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
(2)、链接中包含的链接方法和关闭方法
package com.openlab.Utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class DbConnUtils {
/* static String url="jdbc:mysql://127.0.0.1:3306/hospitalnew?useUnicode=true&characterEncoding=UTF-8";
static String username="root";
static String password="root";*/
static String driver=ConfigManager.getProperty("driver");
static String url=ConfigManager.getProperty("url");
static String username=ConfigManager.getProperty("username1");
static String password=ConfigManager.getProperty("password1");
public static Connection getConnection(){
Connection conn=null;
try{
Class.forName(driver);
//创建数据库连接
conn=DriverManager.getConnection(url, username, password);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet rs,Statement st,Connection conn){
//关闭结果集
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static ResultSet getQueryList(Connection _conn,Statement _st,String _sql){
ResultSet rs=null;
try {
rs=_st.executeQuery(_sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
7、通过jsp页面的代码来看看
(1)、登录的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>My JSP 'login.jsp' starting page</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="css/common.css">
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<%
/* Cookie cookies[] = request.getCookies();
boolean flag = false;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("admin")) {
flag = true;
response.sendRedirect("index1.jsp");
break;
}
}
}
*/
%>
<h2>登录页面</h2>
<div id="regiter">
<a href="regiter.jsp">注册</a>
</div>
<div>
<form action="doLogin.jsp" method="post">
<table>
<tr>
<td>用户名:<input type="text" name="username" /></td>
</tr>
<tr>
<td>密码:<input type="password" name="password" /></td>
</tr>
<tr>
<td><span style="color:red;">
<%-- <%
if (session.getAttribute("errors") != null) {
out.print(session.getAttribute("errors"));
}
%> --%>
<%
if (session.getAttribute("errors") != null) {
%>
<%=session.getAttribute("errors")%>
<%
}
%>
</span>
</td>
</tr>
<tr>
<td><input type="submit" value="登录" /> <input type="reset"
value="取消" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
(2)、处理登录的jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.openlab.service.*,com.openlab.service.impl.*,com.openlab.pojo.*" %>
<%
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>My JSP 'doLogin.jsp' starting page</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>
<%
//处理post请求乱码
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
//String username=new String(users.getBytes("ISO-8859-1"),"UTF-8");
String password = request.getParameter("password");
LoginService login = new LoginServiceImpl();
Employee employee=new Employee();
employee.setRegisterName(username);
employee.setRepassword(password);
String result = login.Login(employee);
if (result.equals("success")) {
//登陆成功
//request.setAttribute("login", username); //将登陆人的名字保存在请求范围
session.setAttribute("login", username); //将登陆人的名字保存在会话范围
//response.sendRedirect("index1.jsp"); //重定向
//request.getRequestDispatcher("index1.jsp").forward(request, response); //转发
Cookie cookie1 = new Cookie(username, password);
cookie1.setMaxAge(3600);
response.addCookie(cookie1);
RequestDispatcher rd = request.getRequestDispatcher("index1.jsp");
rd.forward(request, response);
} else {
session.setAttribute("errors", "用户名密码不正确,请重新输入...");
//登陆失败
response.sendRedirect("login.jsp");
}
%>
<%-- 用户名:<%=username %>
密码:<%=password %> --%>
</body>
</html>
(3)、注册页面的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>My JSP 'regiter.jsp' starting page</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="css/common.css">
</head>
<body>
<h2>欢迎来西安市交通大学第一附属医院</h2>
<div>
<form action="doRegister.jsp" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="registerName" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="registerPassword" /></td>
</tr>
<tr>
<td>再次输入密码:</td>
<td><input type="password" name="reregisterPassword" /></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="radio" name="sex" value="0" checked="checked" />男
<input type="radio" name="sex" value="1" />女</td>
</tr>
<tr>
<td>身份:</td>
<td><select name="princal">
<option>--请选择--</option>
<option value="doctor">医生</option>
<option value="nurse">护士</option>
<option value="yuanzhang">院长</option>
<option value="admin">管理员</option>
</select></td>
</tr>
<tr>
<td>email:</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>
<%
if (session.getAttribute("errorsRegister") != null) {
out.print(session.getAttribute("errorsRegister"));
}
%>
</td>
</tr>
<tr>
<td><input type="submit" value="注册" />
</td>
<td><input type="reset" value="取消" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
(4)、处理注册的jsp页面
<%@page import="com.openlab.pojo.Employee,com.openlab.service.*,com.openlab.service.impl.*"%>
<%@ 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>My JSP 'doRegister.jsp' starting page</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="css/common.css">
</head>
<body>
<h2>注册页面</h2>
<%
request.setCharacterEncoding("UTF-8");
String registerName = request.getParameter("registerName");
String registerPassword = request.getParameter("registerPassword");
String reregisterPassword = request.getParameter("reregisterPassword");
String sex = request.getParameter("sex");
String princal = request.getParameter("princal");
String email = request.getParameter("email");
Employee _employee = new Employee();
_employee.setRegisterName(registerName);
_employee.setRepassword(registerPassword);
_employee.setRerepassword(reregisterPassword);
_employee.setSex(Integer.parseInt(sex));
_employee.setPrical(princal);
_employee.setEmail(email);
RegisterService register = new RegisterServiceImpl();
String result = register.Register(_employee);
if (result.equals("success")) {
response.sendRedirect("login.jsp");
} else {
session.setAttribute("errorsRegister", "注册失败...");
response.sendRedirect("register.jsp");
}
%>
</body>
</html>
总结:这是一个相对比较基础的实现过程,我只是总结一下流程方便理解,加油哈!