架构实例之SpringTest

1、开发工具和开发环境

      开发工具: MyEclipse10,JDK1.6.0_13(32位),Tomcat7.0(32位),mysql5.7.13

开发环境:WIN7

2、SpringTest实现功能

用户登录、用户注册、退出登录。

3、SpringTest使用技术

      本实例使用了JSP、Spring3.1框架、JdbcTemplate来实现用户登录、用户注册和退出登录功能。系统架构图如图一所示:

 

图一:SpringTest系统架构图

4、具体实现

(1)在MyEclipse中新建一个Web项目,并命名为SpringTest。项目建立完成后,鼠标选择该项目并点击右键选择MyEclipse选项,再选择Add Spring Capabilities选项,再选择Spring3.1Core Libraries,最后点击finish按钮即可初步完成Spring框架环境搭建;

(2)在src中会自动生成一个appllicaitonContext.xml文件,此处把该文件放到WebRoot/WEB-INF目录下,并把该文件重新命名为spring-servlet.xml;

(3)在WebRoot/WEB-INF/lib下放入以下三个jar包spring.jar、mysql-connector-java-5.0.8-bin.jar、commons-dbcp.jar,此处即可完成本项目的所有玩家搭建,接下来就是具体代码的书写;

(4)首先,完成web.xml中的相关配置,具体代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name> <filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app

(5)接下来,就是spring-servlet.xml中的相关配置,具体代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- 配置数据源与事务 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/demo_test</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>root</value>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean> <!-- 定义DAO -->
<bean id="userDAO" class="com.liu.spring.dao.UserDAO">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<bean id="UserDAOProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref local="userDAO" />
</property>
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean> <!-- 定义视图 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.InternalResourceView
</value>
</property>
<!-- JSP都放在/目录下 -->
<property name="prefix">
<value>/</value>
</property>
<!-- JSP页面的后缀都四.JSP -->
<property name="suffix">
<value>.jsp</value>
</property>
</bean> <!-- 定义映射 -->
<bean id="loginMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/login.do">loginAction</prop>
</props>
</property>
</bean>
<bean id="logoutMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/logout.do">logoutAction</prop>
</props>
</property>
</bean>
<bean id="registerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/register.do">registerAction</prop>
</props>
</property>
</bean> <!---定义Action-->
<bean id="loginAction"
class="com.liu.spring.actions.LoginAction">
<property name="commandClass">
<value>com.liu.spring.forms.LoginForm</value>
</property>
<!-- 指定DAO类 -->
<property name="userDAO">
<ref local="userDAO" />
</property>
<!-- 指定失败要返回的页面 -->
<property name="formView">
<value>login</value>
</property>
<!-- 指定成功要返回的页面 -->
<property name="successView">
<value>welcome</value>
</property>
</bean>
<bean id="logoutAction"
class="com.liu.spring.actions.LogoutAction">
<property name="commandClass">
<value>com.liu.spring.forms.LoginForm</value>
</property>
<property name="successView">
<value>login</value>
</property>
</bean>
<bean id="registerAction"
class="com.liu.spring.actions.RegisterAction">
<property name="commandClass">
<value>com.liu.spring.forms.RegisterForm</value>
</property>
<!-- 指定DAO类 -->
<property name="userDAO">
<ref local="userDAO" />
</property>
<!-- 指定失败要返回的页面 -->
<property name="formView">
<value>register</value>
</property>
<property name="successView">
<value>login</value>
</property>
</bean> </beans>

(6)用户登录、注册表单类具体代码:

用户登录表单类代码如下:

package com.liu.spring.forms;

public class LoginForm {
private String username; private String password; public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} }

用户注册表单类代码如下:

package com.liu.spring.forms;

public class RegisterForm {
private String username; private String password1; private String password2; private String email; public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getPassword1() {
return password1;
} public void setPassword1(String password1) {
this.password1 = password1;
} public String getPassword2() {
return password2;
} public void setPassword2(String password2) {
this.password2 = password2;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
}
}

(7)用户登录、注册、退出Action类具体代码:

用户登录Action类代码

package com.liu.spring.actions;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController; import com.liu.spring.dao.UserDAO;
import com.liu.spring.forms.LoginForm;
import com.liu.spring.util.Constants; public class LoginAction extends SimpleFormController {
UserDAO userDAO; public UserDAO getUserDAO() {
return userDAO;
} public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
} protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
LoginForm loginForm = (LoginForm) command;
if (isValid(loginForm)) {
request.getSession().setAttribute(Constants.USERNAME_KEY, loginForm.getUsername());
return new ModelAndView(getSuccessView());
} else {
@SuppressWarnings("unchecked")
Map<String, Object> modle = errors.getModel();
modle.put("loginForm", loginForm);
return new ModelAndView(getFormView(), modle);
}
} public boolean isValid(LoginForm loginForm) {
// if (loginForm.getUsername().equals("admin")
// && loginForm.getPassword().equals("admin")) {
// return true;
// } else {
// return false;
// } if(userDAO.isValid(loginForm.getUsername(), loginForm.getPassword())) {
return true;
} else {
return false;
}
}
}

其中,用户登录中使用了一个USERNAME_KEY字段,此处单独建立一个Constants类来实现,具体代码如下:

package com.liu.spring.util;

public class Constants {
public final static String USERNAME_KEY = "username"; }

用户注册Action类代码

package com.liu.spring.actions;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController; import com.liu.spring.dao.User;
import com.liu.spring.dao.UserDAO;
import com.liu.spring.forms.RegisterForm; public class RegisterAction extends SimpleFormController { UserDAO userDAO; public UserDAO getUserDAO() {
return userDAO;
} public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
} public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
String method = request.getParameter("method");
if (method == null || method.equals("init")) {
return init(command, errors);
} else if (method.equals("register")) {
return register(request, response, command, errors);
} else {
RegisterForm registerForm = (RegisterForm) command;
@SuppressWarnings("unchecked")
Map<String, Object> modle = errors.getModel();
modle.put(getFormSessionAttributeName(), registerForm);
return new ModelAndView(getSuccessView(), modle);
}
} public ModelAndView init(Object command, BindException errors)
throws Exception {
RegisterForm registerForm = (RegisterForm) command;
@SuppressWarnings("unchecked")
Map<String, Object> modle = errors.getModel();
modle.put(getFormSessionAttributeName(), registerForm);
return new ModelAndView(getFormView(), modle);
} public ModelAndView register(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
RegisterForm registerForm = (RegisterForm) command;
if (!isExist(registerForm)) {
add(registerForm);
@SuppressWarnings("unchecked")
Map<String, Object> modle = errors.getModel();
modle.put(getSuccessView(), registerForm);
response.sendRedirect("login.do");
return null;
//return new ModelAndView(getSuccessView(), modle);
} else {
@SuppressWarnings("unchecked")
Map<String, Object> modle = errors.getModel();
modle.put(getFormSessionAttributeName(), registerForm);
return new ModelAndView(getFormView(), modle);
}
} public boolean isExist(RegisterForm registerForm) {
// if (registerForm.getUsername().equals("admin")) {
// return true;
// } else {
// return false;
// }
if (userDAO.isExist(registerForm.getUsername())) {
return true;
} else {
return false;
}
} public void add(RegisterForm registerForm) {
User user = new User();
user.setUsername(registerForm.getUsername());
user.setPassword(registerForm.getPassword1());
user.setEmail(registerForm.getEmail());
userDAO.insertUser(user);
}
}

用户退出Action类代码

package com.liu.spring.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController; public class LogoutAction extends SimpleFormController { protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
request.getSession().invalidate();
response.sendRedirect("login.do");
return null;
//return new ModelAndView(getSuccessView());
}
}

(8)用户登录和注册进行数据库验证类代码

使用JDBCTemplate完成POJO类User类的创建,具体代码如下:

package com.liu.spring.dao;

public class User {
protected String id; protected String username; protected String password; protected String email; public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} }

使用JDBCTemplate完成数据操作类UserDAO类的创建,具体代码如下:

package com.liu.spring.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; public class UserDAO {
private DataSource dataSource; public DataSource getDataSource() {
return dataSource;
} public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
} public boolean isValid(String username, String password) {
@SuppressWarnings("rawtypes")
List userList = new ArrayList();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
userList = jdbcTemplate.query("SELECT * FROM userInfo WHERE username='"
+ username + "' and password='" + password + "'",
new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum)
throws SQLException {
User user = new User();
user.setId(rs.getString("ID"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
return user;
}
});
if (userList.size() > 0) {
return true;
} else {
return false;
}
} public boolean isExist(String username) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.queryForInt("SELECT count(*) FROM userInfo WHERE username='" + username
+ "'");
if (count > 0) {
return true;
} else {
return false;
}
} public void insertUser(User user) {
String username = user.getUsername();
String password = user.getPassword();
String email = user.getEmail();
JdbcTemplate jt = new JdbcTemplate(getDataSource());
jt.update("insert into userInfo(username,password,email) values ('"
+ username + "','" + password + "','" + email + "');");
}
}

(9)视图层用户登录,用户注册和登录成功后JSP界面代码

用户登录JSP页面代码(login.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="styles.css">
--> </head> <body>
<form name="form1" action="login.do" method="post">
<table width="200" border="1">
<tr>
<td colspan="2">登录窗口</td>
</tr>
<tr>
<td>用户名</td>
<td><input type="text" name="username" size="10"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password" size="10"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="登录"> <a
href="register.do?method=init">注册新用户</a></td>
</tr>
</table>
</form> </body>
</html>

用户注册JSP页面代码(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>My JSP 'register.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>
<form name="form1" action="register.do?method=register" method="post">
<table width="200" border="1">
<tr>
<td colspan="2">注册窗口</td>
</tr>
<tr>
<td>用户名</td>
<td><input type="text" name="username" size="10"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password1" size="10"></td>
</tr>
<tr>
<td>确认密码</td>
<td><input type="password" name="password2" size="10"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" size="10"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="登录"> <a
href="login.do">返回</a></td>
</tr>
</table>
</form> </body>
</html>

登录成功后JSP页面代码(welcome.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 'welcome.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>
<form name="form1" action="logout.do" method="post">
<table width="200" border="1">
<tr>
<td colspan="2">登录成功</td>
</tr>
<tr>
<td>欢迎你,</td>
<td><%=(String) session.getAttribute("username")%></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="退出"></td>
</tr>
</table>
</form>
</body>
</html>

5、运行结果

开启Tomcat服务后,打开浏览器输入:http://localhost:8080/SpringTest/login.jsp,将会出现下图二所示结果:

图二:用户登录界面

点击注册新用户,将会出现以下图三所示结果(点击登陆,如果注册成功就会返回到登陆界面,如果未成功则保留在注册界面):

图三:用户注册界面

用上图中注册的账号进行登陆,登陆成功后出现下图四所示结果:

图四:用户登陆成功后界面

PS:本项目具体源码GitHub链接:https://github.com/miaomiaoqiushui/SpringTest

架构实例之SpringTest的更多相关文章

  1. 架构实例之Demo_JSP_JavaBean_Servlet

    架构实例之Demo_JSP_JavaBean_Servlet 1.开发工具和开发环境       开发工具: MyEclipse10,JDK1.6.0_13(32位),Tomcat7.0(32位),m ...

  2. 架构实例之Demo_JSP_JavaBean

    架构实例之Demo_JSP_JavaBean 1.开发工具和开发环境      开发工具: MyEclipse10,JDK1.6.0_13(32位),Tomcat7.0(32位),mysql5.7.1 ...

  3. 架构实例之Demo_JSP

    架构实例之Demo_JSP 1.开发工具和开发环境       开发工具: MyEclipse10,JDK1.6.0_13(32位),Tomcat7.0(32位),mysql5.7.13 开发环境:W ...

  4. 【DDD】领域驱动设计实践 —— 架构风格及架构实例

    概述 DDD为复杂软件的设计提供了指导思想,其将易发生变化的业务核心域放置在限定上下文中,在确保核心域一致性和内聚性的基础上,DDD可以被多种语言和多种技术框架实现,具体的框架实现需要根据实际的业务场 ...

  5. JavaWeb学习之三层架构实例(三)

    引言 通过上一篇博客JavaWeb学习之三层架构实例(二)我们基本上已经实现了对学生信息列表的增删改查操作(UI除外),但是不难看出,代码冗余度太高了,尤其是StudentDao这个类,其中的增删改查 ...

  6. JavaWeb学习之三层架构实例(二)

    引言 这个实例是上一个实例JavaWeb学习 三层架构实例(一)的加强版,实现的是在前端对数据库中student表的 增.删.改.查 操作.关于三层组成云云,这里就不再叙述. 实例 效果图 先来看一下 ...

  7. linux驱动由浅入深系列:高通sensor架构实例分析之二(驱动代码结构)【转】

    本文转载自:https://blog.csdn.net/radianceblau/article/details/73498303 本系列导航: linux驱动由浅入深系列:高通sensor架构实例分 ...

  8. linux驱动由浅入深系列:高通sensor架构实例分析之三(adsp上报数据详解、校准流程详解)【转】

    本文转载自:https://blog.csdn.net/radianceblau/article/details/76180915 本系列导航: linux驱动由浅入深系列:高通sensor架构实例分 ...

  9. java:Session(概述,三层架构实例(实现接口封装JDBC),Session实现简单购物车实例)

    1.Session概述: Session:在计算机中,尤其是在网络应用中,称为“会话控制”.Session 对象存储特定用户会话所需的属性及配置信息.这样,当用户在应用程序的 Web 页之间跳转时,存 ...

随机推荐

  1. SQL常见的系统存储过程

    1.sp_datebases 列出服务器上的所有数据库信息,包括数据库名称和数据库大小 例:exec sp_datebases 2.sp_helpdb 报告有关指定数据库或所有数据库的信息 例:exe ...

  2. 悟透JavaScript

    要理解JavaScript,你得首先放下对象和类的概念,回到数据和代码的本原.前面说过,编程世界只有数据和代码两种基本元素,而这两种元素又有着纠缠不清的关系.JavaScript就是把数据和代码都简化 ...

  3. 在 Git 中 Checkout 历史版本

    昨天写代码的时候,误删了一个文件.今天发现的时候,commit 已经 push 到版本库了.本想用 git reset 回退版本,找回文件后重新提交.但是想起 Git 是一个版本控制系统哎,直接从版本 ...

  4. Python 3.4 send mail

    #coding=utf-8 #Python 3.4 https://docs.python.org/3.4/library/ #IDE:Visual Studio 2015 Window10 impo ...

  5. Linux Cmd Tool 系列之—history & search command history

    History cmd is for list Bash's log of the historical cmd you typed 1. List last n commands history n ...

  6. java web学习总结(八) -------------------HttpServletResponse对象(二)

    一.HttpServletResponse常见应用--生成验证码 1.1.生成随机图片用作验证码 生成图片主要用到了一个BufferedImage类,

  7. 推荐15款响应式的 jQuery Lightbox 插件

    利用现代 Web 技术,网络变得越来越轻巧与.模态框是突出展现内容的重要形式,能够让用户聚焦到重要的内容上去.在这个列表中,我们编制了15款响应式的 jQuery 灯箱库,这将有助于开发人员创建和设计 ...

  8. html5 canvas简易版捕鱼达人游戏源码

    插件描述:html5利用canvas写的一个js版本的捕鱼,有积分统计,鱼可以全方位移动,炮会跟着鼠标移动,第一次打开需要鼠标移出背景图,再移入的时候就可以控制炮的转动,因为是用的mouseover触 ...

  9. SharePoint 2016 图文安装教程

    前言 SharePoint 2016如约而至,之前也装过预览版,但是这次是正式版,还是分享一个完整的安装过程给大家,希望能给有需要的人有所帮助. 1.首先安装操作系统,我这里是Windows Serv ...

  10. 两种方法设置disabled属性

    //两种方法设置disabled属性 $('#fileup').attr("disabled",true); $('#fileup').attr("disabled&qu ...