SSH整合——架构的历史

来源:互联网 发布:谢云流正太捏脸数据 编辑:程序博客网 时间:2024/05/22 11:40

SSH整合——架构的历史1

写一个小项目,用户注册,有register.jspregisterDeal.jspregisterSuccess.jspregisterFail.jsp

 

A、两层结构

只有JSP页面和数据库

(1)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/csshref="styles.css">

-->

 

  </head>

  

  <body>

    <form action="registerDeal.jsp" method="post">

     用户名:<input type="text" name="username" /><br/>

     密 码:<input type="password" name="password" /><br/>

     确认密码:<input type="password" name="password2" /><br>

     <input type="submit" value="提交" />

    </form>

  </body>

</html>

(2)registerDeal.jsp

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

String username=request.getParameter("username");

String password=request.getParameter("password");

String password2=request.getParameter("password2");

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring""root""root");

String sqlQuery = "select count(*) from user where username= ?";

PreparedStatement psQuery= conn.prepareStatement(sqlQuery);

psQuery.setString(1, username);

ResultSet rs = psQuery.executeQuery();

rs.next();

int count = rs.getInt(1);

if(count > 0){

response.sendRedirect("registerFail.jsp");

psQuery.close();

conn.close();

return;

}

 

String sql = "insert into user values (null,?,?)";

PreparedStatement ps= conn.prepareStatement(sql);

ps.setString(1, username);

ps.setString(2, password);

ps.executeUpdate();

ps.close();

conn.close();

response.sendRedirect("registerSuccess.jsp");

%>

 

(3)registerSuccess.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>Success 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/csshref="styles.css">

-->

 

  </head>

  

  <body>

    Success <br>

  </body>

</html>

(4)registerFail.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>Fail 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/csshref="styles.css">

-->

 

  </head>

  

  <body>

   Fail

  </body>

</html>

(5)以上设计的不利的地方在于,jsp页面封装了数据库操作,当其他应用如JavaEE应用需要使用jsp页面中的逻辑时,将导致不变。根据面向对象设计,至少应该有一个实体类User

 

B、三层结构+Entity+Serice

(1)创建Model

package com.zgy.registration.model;

 

public class User {

private String username;

private String password;

private int id;

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

}

 

(2)创建service

package com.zgy.registration.service;

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

 

import com.zgy.registration.model.User;

 

public class UserManager {

public boolean exists(User u) throws SQLException, ClassNotFoundException {

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/spring""root""root");

String sqlQuery = "select count(*) from user where username= ?";

PreparedStatement psQuery = conn.prepareStatement(sqlQuery);

psQuery.setString(1, u.getUsername());

ResultSet rs = psQuery.executeQuery();

rs.next();

int count = rs.getInt(1);

psQuery.close();

if (count > 0) {

return true;

}

return false;

}

 

public void add(User u) {

try {

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/spring""root""root");

String sql = "insert into user values (null,?,?)";

PreparedStatement ps = conn.prepareStatement(sql);

ps.setString(1, u.getUsername());

ps.setString(2, u.getPassword());

ps.executeUpdate();

ps.close();

conn.close();

catch (ClassNotFoundException e) {

e.printStackTrace();

catch (SQLException e) {

e.printStackTrace();

}

}

}

(3)修改registerDeal.jsp,访问model层和service层,不再访问数据库

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>

<%@ page import="com.zgy.registration.model.*" %>

<%@ page import="com.zgy.registration.service.*" %>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

String username=request.getParameter("username");

String password=request.getParameter("password");

String password2=request.getParameter("password2");

User u = new User();

u.setUsername(username);

u.setPassword(password);

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring""root""root");

UserManager um = new UserManager();

boolean exist = um.exists(u);

if(exist){

response.sendRedirect("registerFail.jsp");

return;

}

um.add(u);

response.sendRedirect("registerSuccess.jsp");

%>

(4)不便之处:其中使用到的sql语句不是面向对象的特性,此时可以使用到Hibernate

 

CN层结构+Entity+Service+Hibernate

(1)使用HibernateAnnotation注解实体类

package com.zgy.registration.model;

 

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

 

@Entity

public class User {

private String username;

private String password;

private int id;

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

@Id

@GeneratedValue

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

}

(2)Hibernate获取SessionFactory

package com.zgy.registration.util;

 

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;

 

public class HibernateUtil {

private static SessionFactory sf;

static {

sf = new AnnotationConfiguration().configure().buildSessionFactory();

}

public static SessionFactory getSessionFactory() {

return sf;

}

}

(3)修改UserManager

package com.zgy.registration.service;

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

 

import org.hibernate.SessionFactory;

import org.hibernate.classic.Session;

 

import com.zgy.registration.model.User;

import com.zgy.registration.util.HibernateUtil;

 

public class UserManager {

public boolean exists(User u) throws SQLException, ClassNotFoundException {

SessionFactory sf = HibernateUtil.getSessionFactory();

Session session = sf.getCurrentSession();

session.beginTransaction();

long count = (Long) session

.createQuery(

"select count(*) from User user "

+ "where user.username= :username")

.setString("username", u.getUsername()).uniqueResult();

session.getTransaction().commit();

if (count > 0) {

return true;

}

return false;

}

 

public void add(User u) {

SessionFactory sf = HibernateUtil.getSessionFactory();

Session session = sf.getCurrentSession();

session.beginTransaction();

session.save(u);

session.getTransaction().commit();

}

}

(4)JUnit单元测试

package com.zgy.registration.service;

 

import static org.junit.Assert.*;

 

import java.sql.SQLException;

 

import junit.framework.Assert;

 

import org.junit.Test;

 

import com.zgy.registration.model.User;

 

public class TestUserManager {

 

@Test

public void testExists() throws SQLException, ClassNotFoundException {

UserManager um = new UserManager();

User u = new User();

u.setUsername("a");

boolean exist = um.exists(u);

Assert.assertEquals(true, exist);

}

@Test

public void testAdd() throws SQLException, ClassNotFoundException {

UserManager um = new UserManager();

User u = new User();

u.setUsername("d");

u.setPassword("d");

boolean exist = um.exists(u);

if(!exist){

um.add(u);

Assert.assertEquals(true, um.exists(u));

}else{

Assert.fail("not added");

}

}

}

(5)数据成功入库。

(6)如果想要实现跨数据库平台的设计,需要抽象出UserDAO,封装数据库的操作



0 0
原创粉丝点击