使用spring mvc、spring jdbc 实现网站的登录注册功能
1. 据业务模型 创建model 一般实现序列化
2. 用spring 注解(@Repository)定义DAO,在该DAO中用注解(@Autowired)方式注入JdbcTemplate bean,使用JdbcTemplate api实现DAO方法
package com.shopfruit.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* 使用spring jdbc 实现这个dao类
* @author Administrator
*/
@Repository//spring注解定义一个dao
public class UserDao {
1.1 @Autowired//自动注入JdbcTemplate 的bean
private JdbcTemplate jdbcTemplate;
/**
* 用户注册
* @return 1 注册成功、0 注册失败
*/
public intregisterUser(String name,String password){
String sql = "INSERT INTOt_user values(null,?,?);";
int result = jdbcTemplate.update(sql, newObject[]{name,password});
return result;
}
/**
* 用户名校验
* @param name
* @return 1 已存在 0不存在允许注册
*/
public intregisterCheck(String name){
String sql="selectcount(user_id) from t_user where user_name=?";
int result = jdbcTemplate.queryForInt(sql,name);
return result;
}
/**
* 用户登录
* @return 1 验证成功 0验证失败
*/
public intgetMatchCount(String name,String password){
String sql = "SELECTcount(user_id) from t_user where user_name = ? and `password`=?;";
int result = jdbcTemplate.queryForInt(sql, new Object[]{name,password});
return result;
}
}
3.
配置文件装配DAO,在src目录创建spring配置文件applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!--解决spring mvc乱码问题,方式二
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<propertyname="messageConverters">
<list>
<beanid ="utf8StringHttpMessageConverter"
class="com.shopfruit.util.UTF8StringHttpMessageConverter"/>
</list>
</property>
</bean>
-->
<!--扫描类表,将标注有sping注解的类自动转换成bean,同时完成bean的注入 -->
<context:component-scan base-package="com.shopfruit.dao"></context:component-scan>
<context:component-scan base-package="com.shopfruit.service"></context:component-scan>
<!-- 配置数据源 -->
<bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/spring"
p:username="root"
p:password="root"></bean>
<!-- 配置jdbc模板 -->
<bean id="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"></bean>
<!-- 配置数据源事务管理 -->
<bean id="dataSourceTanslationManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"></bean>
<!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod"
expression=" execution(* com.baobaotao.service..*(..))"/>
<aop:advisor pointcut-ref="serviceMethod"advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice"transaction-manager="dataSourceTanslationManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
</beans>
4. 已完成持久层开发和配置,下面完成业务层的开发和配置,配置在上面
package com.shopfruit.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shopfruit.dao.UserDao;
@Service//标注为服务层的bean
public class UserService {
@Autowired
private UserDao userDao;
/**
* 注册检查
* @param name
* @return用户名是否存在,不存在 true,存在false
*/
public booleanregisterCheck(String name){
return userDao.registerCheck(name)==0;
}
/**
* 用户注册
* @param name
* @param password
* @return注册是否成功
*/
public booleanregisterUser(String name,String password){
if(registerCheck(name)){
return userDao.registerUser(name,password)>0;
}
return false;
}
/**
* 登录校验
* @param name
* @param password
* @return用户名密码是否匹配
*/
public booleangetMatchCount(String name,String password){
return userDao.getMatchCount(name,password)>0;
}
}
5.
单元测试业务层
package com.shopfruit.service;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.shopfruit.service.UserService;
//基于JUnit4的spring测试框架
@RunWith(SpringJUnit4ClassRunner.class)
//启动spring容器
@ContextConfiguration(locations = {"/applicationContext.xml"} )
public class TestUserService {
@Autowired
private UserService userService;
@Test
public void testRegisterUser(){
boolean b1 = userService.registerUser("admin", "123456");
assertTrue(b1);
}
@Test
public voidtestRegisterCheck() {
Boolean b1 = userService.registerCheck("admindgzv");
Boolean b2 = userService.registerCheck("adminzfczv");
assertTrue(b1);
assertTrue(b2);
}
@Test
public voidtestGetMatchCount() {
boolean b1 = userService.getMatchCount("admin", "123456");
boolean b2 = userService.getMatchCount("admin1", "123456");
assertTrue(b1);
assertTrue(b2);
}
}
6.展现层的实现
1) 配置spring mvc,以便web容器启动能够自启动spring容器,处理请求。web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ShopFruit</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 从类路径下加载spring配置文件classpath关键字指从类路径加载 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<!-- 负责启动spring容器的监听器,通过上下参数获取spring配置文件的地址 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring mvc主控的Servlet,还得在web-info下提供shopfruit-servlet.xml的spring mvc配置文件 -->
<servlet>
<servlet-name>shopfruit</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<!-- spring mvc处理的url,所有.html的请求被shopfruit sevlet截获,更具请求找到相应的处理控制器-->
<servlet-mapping>
<servlet-name>shopfruit</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
2) 处理登录注册请求的控制器类
package com.shopfruit.web;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.shopfruit.domain.User;
import com.shopfruit.service.UserService;
@Controller//标注成为spring mvc 的Controller类
public class LoginRegisterController {
@Autowired
private UserService userService;
/**
* 请求login.html跳登录页面
* @return
*/
@RequestMapping(value={"/login.html"})
public String login(){
return "login";
}
/**
* 请求register.html跳注册页面
* @return
*/
@RequestMapping(value={"/register.html"})
public String register(){
return "register";
}
/**
* 检查用户名
* @param request
* @return
*/
@RequestMapping(value={"/registerCheck.html"})
public @ResponseBody StringregisterCheck(HttpServletRequest request){
String name =request.getParameter("name");
boolean b = userService.registerCheck(name);
if(!b){
// return"user error";
return "用户名重复请重新取名";
}
// return"user ok";
return "用户名可用";
}
/**
* 登录检查
* @param request
* @return
*/
@RequestMapping(value={"/loginUser.html"})
public ModelAndViewloginCheck(HttpServletRequest request){
String name =request.getParameter("name");
Stringpassword = request.getParameter("password");
boolean b = userService.getMatchCount(name,password);
if(!b){
return new ModelAndView("login","status","用户名或者密码错误");
}
UserloginUser = new User();
loginUser.setName(name);
request.getSession().setAttribute("user",loginUser);
return new ModelAndView("main","status","登录成功");
}
/**
* 用户注册
* @param request
* @param user
* @return
*/
@RequestMapping(value={"/registerUser.html"})
public ModelAndViewregisterUser(HttpServletRequest request,User user){
boolean b = userService.registerUser(user.getName(),user.getPassword());
if(!b){
return new ModelAndView("register","status","注册失败,请重新注册。");
}
request.getSession().setAttribute("user",user);
return new ModelAndView("main","status","注册成功");
}
}
写控制器类发现eclipse没有javax.servlet.http.HttpServletRequest 这个类,这个类在tomcat的lib 的servlet-aip.jar,需要我们自己在项目中引入
配置spring mvc 配置文件 shopfruit-servlet.xml
<pre name="code" class="html"><?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 解决spring mvc 乱码问题,方式一-->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class ="org.springframework.http.converter.StringHttpMessageConverter">
<property name ="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<!-- 扫描web包,应用Spring的注解 -->
<context:component-scan base-package="com.shopfruit.web"/>
<!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/jsp/"
p:suffix=".jsp"/>
</beans>
<p><span style="font-size:12px;">
7. 前台页面展示1)index.jsp 网站首页
<%@ page language="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>水果电商网站</title>
</head>
<body>
<a href='<c:url value="/login.html"/>'>登录</a>
<a href='<c:url value="/register.html"/>'>注册</a>
</body>
</html>
2) login.jsp登录界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录-水果电商网站</title>
</head>
<body>
<c:if test="${!empty status}">
<font color="red"><c:out value="${status}"></c:out> </font>
</c:if>
<form action='<c:url value="/loginUser.html"/>'>
用户名:<input name="name" type="text"/><br>
密码:<input name="password" type="text"/><br>
<input type="submit" value="登录"/> <input type="reset" value="重置"/>
</form>
</body>
</html>
3) register.jsp 注册页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册-水果电商网站</title>
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function(){
$("#userName").bind("blur",function(){
var name = $(this).val();
$.ajax({
type: "POST",
url: "registerCheck.html",
data: {name:name},
success: function(msg){
$("#message").html(msg);
}
});
});
});
</script>
</head>
<body>
<c:if test="${!empty status }">
<font color="red"><c:out value="${status }"></c:out> </font>
</c:if>
<form action="registerUser.html">
用户名:<input id="userName" name="name" type="text"/><span style="color:red;" id="message"></span><br>
密码:<input name="password" type="text"/><br>
<input type="submit" value="注册"/> <input type="reset" value="重置"/>
</form>
</body>
</html>
4) main 登录成功、或者注册成功后转向的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主页-水果电商网站</title>
</head>
<body>
${user.name}
<c:if test="${!empty status}">
<font color="red"><c:out value="${status }"></c:out> </font>
</c:if>
</body>
</html>
8. 最后发现spring mvc 返回给ajax的内容如果返回的是中文就会是乱码,原因是spring3.x
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters">
<list>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name = "supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
解决办法二:重写StringHttpMessageConverter类
</pre><pre name="code" class="java">package com.shopfruit.util;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.FileCopyUtils;
public class UTF8StringHttpMessageConverter extends StringHttpMessageConverter {
private static final MediaType utf8 = new MediaType("text", "plain",
Charset.forName("UTF-8"));
private boolean writeAcceptCharset = true;
@Override
protected MediaType getDefaultContentType(String dumy) {
return utf8;
}
protected List<Charset> getAcceptedCharsets() {
return Arrays.asList(utf8.getCharSet());
}
protected void writeInternal(String s, HttpOutputMessage outputMessage)
throws IOException {
if (this.writeAcceptCharset) {
outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
}
Charset charset = utf8.getCharSet();
FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(),
charset));
}
public boolean isWriteAcceptCharset() {
return writeAcceptCharset;
}
public void setWriteAcceptCharset(boolean writeAcceptCharset) {
this.writeAcceptCharset = writeAcceptCharset;
}
}
在spring 配置文件中添加
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean id ="utf8StringHttpMessageConverter"
class="com.shopfruit.util.UTF8StringHttpMessageConverter" />
</list>
</property>
</bean>