spring 3.x 学习笔记_spring mvc、spring jdbc 实现网站的登录注册功能
使用spring mvc、spring jdbc 實(shí)現(xiàn)網(wǎng)站的登錄注冊功能
1.????????據(jù)業(yè)務(wù)模型 創(chuàng)建model 一般實(shí)現(xiàn)序列化
2.????????用spring 注解(@Repository)定義DAO,在該DAO中用注解(@Autowired)方式注入JdbcTemplate bean,使用JdbcTemplate api實(shí)現(xiàn)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 實(shí)現(xiàn)這個dao類* @author Administrator*/ @Repository//spring注解定義一個dao public class UserDao { 1.1 @Autowired//自動注入JdbcTemplate 的beanprivate 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;}/*** 用戶名校驗(yàn)* @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 驗(yàn)證成功 0驗(yàn)證失敗*/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目錄創(chuàng)建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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><!--解決spring mvc亂碼問題,方式二<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><propertyname="messageConverters"><list><beanid ="utf8StringHttpMessageConverter"class="com.shopfruit.util.UTF8StringHttpMessageConverter"/></list></property></bean>--><!--掃描類表,將標(biāo)注有sping注解的類自動轉(zhuǎn)換成bean,同時完成bean的注入 --><context:component-scan base-package="com.shopfruit.dao"></context:component-scan><context:component-scan base-package="com.shopfruit.service"></context:component-scan><!-- 配置數(shù)據(jù)源 --><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><!-- 配置數(shù)據(jù)源事務(wù)管理 --><bean id="dataSourceTanslationManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"p:dataSource-ref="dataSource"></bean><!-- 通過AOP配置提供事務(wù)增強(qiáng),讓service包下所有Bean的所有方法擁有事務(wù) --><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. 已完成持久層開發(fā)和配置,下面完成業(yè)務(wù)層的開發(fā)和配置,配置在上面
package com.shopfruit.service;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import com.shopfruit.dao.UserDao;@Service//標(biāo)注為服務(wù)層的bean public class UserService {@Autowiredprivate 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;}/*** 登錄校驗(yàn)* @param name* @param password* @return用戶名密碼是否匹配*/public booleangetMatchCount(String name,String password){return userDao.getMatchCount(name,password)>0;} } 5. 單元測試業(yè)務(wù)層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 {@Autowiredprivate UserService userService;@Testpublic void testRegisterUser(){boolean b1 = userService.registerUser("admin", "123456");assertTrue(b1);}@Testpublic voidtestRegisterCheck() {Boolean b1 = userService.registerCheck("admindgzv");Boolean b2 = userService.registerCheck("adminzfczv");assertTrue(b1);assertTrue(b2);}@Testpublic voidtestGetMatchCount() {boolean b1 = userService.getMatchCount("admin", "123456");boolean b2 = userService.getMatchCount("admin1", "123456");assertTrue(b1);assertTrue(b2);}}
6.展現(xiàn)層的實(shí)現(xiàn)
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關(guān)鍵字指從類路徑加載 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><!-- 負(fù)責(zé)啟動spring容器的監(jiān)聽器,通過上下參數(shù)獲取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截獲,更具請求找到相應(yīng)的處理控制器--><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//標(biāo)注成為spring mvc 的Controller類 public class LoginRegisterController {@Autowiredprivate 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 "用戶名重復(fù)請重新取名";}// 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","注冊成功");} }
寫控制器類發(fā)現(xiàn)eclipse沒有javax.servlet.http.HttpServletRequest 這個類,這個類在tomcat的lib 的servlet-aip.jar,需要我們自己在項(xiàng)目中引入
配置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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://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包,應(yīng)用Spring的注解 --><context:component-scan base-package="com.shopfruit.web"/><!-- 配置視圖解析器,將ModelAndView及字符串解析為具體的頁面 --><beanclass="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 網(wǎng)站首頁
<%@ 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>水果電商網(wǎng)站</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>登錄-水果電商網(wǎng)站</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>注冊-水果電商網(wǎng)站</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 登錄成功、或者注冊成功后轉(zhuǎn)向的頁面
<%@ 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>主頁-水果電商網(wǎng)站</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. 最后發(fā)現(xiàn)spring mvc 返回給ajax的內(nèi)容如果返回的是中文就會是亂碼,原因是spring3.x
解決辦法二:重寫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;@Overrideprotected 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>
總結(jié)
以上是生活随笔為你收集整理的spring 3.x 学习笔记_spring mvc、spring jdbc 实现网站的登录注册功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MCS锁和CLH锁
- 下一篇: C语言中二维数组名与数组地址、首行地址、