架构实例之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中的相关配置,具体代码如下:
encodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 encodingFilter *.do spring org.springframework.web.servlet.DispatcherServlet 1 spring *.do index.jsp
(5)接下来,就是spring-servlet.xml中的相关配置,具体代码如下:
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/demo_test root root PROPAGATION_REQUIRED PROPAGATION_REQUIRED,readOnly org.springframework.web.servlet.view.InternalResourceView / .jsp loginAction logoutAction registerAction com.liu.spring.forms.LoginForm login welcome com.liu.spring.forms.LoginForm login com.liu.spring.forms.RegisterForm register login
(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") Mapmodle = 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") Mapmodle = 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 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 modle = errors.getModel(); modle.put(getSuccessView(), registerForm); response.sendRedirect("login.do"); return null; //return new ModelAndView(getSuccessView(), modle); } else { @SuppressWarnings("unchecked") Map 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+"/";%>My JSP 'login.jsp' starting page
用户注册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 + "/";%>My JSP 'register.jsp' starting page
登录成功后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+"/";%>My JSP 'welcome.jsp' starting page
5、运行结果
开启Tomcat服务后,打开浏览器输入:,将会出现下图二所示结果:
图二:用户登录界面
点击注册新用户,将会出现以下图三所示结果(点击登陆,如果注册成功就会返回到登陆界面,如果未成功则保留在注册界面):
图三:用户注册界面
用上图中注册的账号进行登陆,登陆成功后出现下图四所示结果:
图四:用户登陆成功后界面
PS:本项目具体源码GitHub链接: