您的位置:首页 > 编程语言 > Java开发

Spring 3.x 企业应用开发实战第二章 快速入门

2015-01-15 13:58 726 查看
1,登录demo
-1,建表

CREATETABLET_USER(USER_IDNUMBER(16),
USER_NAMEVARCHAR2(30),
CREDITSNUMBER(16),
PASSWORDVARCHAR2(32),
LAST_VISITDATE,
LAST_IPVARCHAR2(32));
CREATETABLET_LOGIN_LOG(LOGIN_LOG_IDNUMBER(16),
USER_IDNUMBER(16),
IPVARCHAR2(32),
LOGIN_DATETIMEDATE);
[/code]

-2,建立对应package,如下图:



-3,新建model,dao并配置

/**
*类描述:用户类
*
*@author:JingHistory:Jan14,20153:09:40PMJingCreated.
*
*/
publicclassUserimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
privateintuserId;
privateStringuserName;
privateStringpassword;
privateintcredits;
privateStringlastIp;
privateDatelastVisit;
[/code]

/**
*类描述:登录日志
*
*@author:JingHistory:Jan14,20153:11:28PMJingCreated.
*
*/
publicclassLoginLogimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
privateintloginLogId;
privateintuserId;
privateStringip;
privateDateloginDate;
[/code]

/**
*
*@(#)UserDao.java
*@Packagecom.jing.dao
*
*Copyright©JINGCorporation.Allrightsreserved.
*
*/
packagecom.jing.dao;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.jdbc.core.JdbcTemplate;
importorg.springframework.stereotype.Repository;
importcom.jing.domain.User;
/**
*类描述:用户查询类
*
*@author:JingHistory:Jan14,20153:13:56PMJingCreated.
*
*/
@Repository
publicclassUserDao{
@Autowired
privateJdbcTemplatejdbcTemplate;
/**
*
*方法说明:根据用户名和密码获取匹配用户数
*
*Author:JingCreateDate:Jan14,20153:21:20PM
*/
@SuppressWarnings("deprecation")
publicintgetMatchCount(StringuserName,Stringpassword){
StringsqlStr="selectCOUNT(1)FROMT_USERWHEREuser_name=?ANDPASSWORD=?";
returnjdbcTemplate.queryForInt(sqlStr,newObject[]{userName,
password});
}
/**
*
*方法说明:通过用户名获取用户信息
*
*Author:JingCreateDate:Jan14,20153:27:16PM
*/
publicUserfindUserByUserName(finalStringuserName){
Useruser=newUser();
StringsqlStr="SELECTa.user_id,a.user_name,a.creditsFROMt_useraWHEREa.user_name=?";
user=jdbcTemplate.queryForObject(sqlStr,user.getClass(),
newObject[]{userName});
returnuser;
}
/**
*
*方法说明:更新用户信息
*
*Author:JingCreateDate:Jan14,20153:35:08PM
*/
publicvoidupdateLoginInfo(Useruser){
Stringsql="UPDATEt_userSETlast_visit=?,last_ip=?,credits=?WHEREuser_id=?";
jdbcTemplate.update(sql,newObject[]{user.getLastVisit(),
user.getLastIp(),user.getCredits(),user.getUserId()});
}
publicJdbcTemplategetJdbcTemplate(){
returnjdbcTemplate;
}
publicvoidsetJdbcTemplate(JdbcTemplatejdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
}
[/code]

/**
*
*@(#)LoginLogDao.java
*@Packagecom.jing.dao
*
*Copyright©JINGCorporation.Allrightsreserved.
*
*/
packagecom.jing.dao;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.jdbc.core.JdbcTemplate;
importorg.springframework.stereotype.Repository;
importcom.jing.domain.LoginLog;
/**
*类描述:登录日志Dao
*
*@author:JingHistory:Jan14,20153:40:28PMJingCreated.
*
*/
@Repository
publicclassLoginLogDao{
@Autowired
privateJdbcTemplatejdbcTemplate;
/**
*
*方法说明:插入用户登录日志
*
*Author:JingCreateDate:Jan14,20153:46:01PM
*/
publicvoidinsertLoginLog(LoginLoglog){
Stringsql="INSERTINTOt_login_log(LOGIN_LOG_ID,user_id,ip,LOGIN_DATETIME)VALUES(?,?,?,?)";
jdbcTemplate.update(sql,newObject[]{log.getLoginLogId(),
log.getUserId(),log.getIp(),log.getLoginDate()});
}
publicJdbcTemplategetJdbcTemplate(){
returnjdbcTemplate;
}
publicvoidsetJdbcTemplate(JdbcTemplatejdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
}
[/code]

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
'target='_blank'>http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
'target='_blank'>http://www.springframework.org/schema/context
'target='_blank'>http://www.springframework.org/schema/context/spring-context-4.0.xsd
'target='_blank'>http://www.springframework.org/schema/aop
'target='_blank'>http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
'target='_blank'>http://www.springframework.org/schema/tx
'target='_blank'>http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
'target='_blank'>http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--标注注解类的自动扫描-->
<context:component-scanbase-package="com.jing.dao"/>
<!--定义数据源-->
<beanid="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName"
value="oracle.jdbc.driver.OracleDriver"/>
<propertyname="url"
value="jdbc:oracle:thin:@xxxxxxx:1521:xxxx"/>
<propertyname="username"value="xxxx"/>
<propertyname="password"value="xxxxx"/>
</bean>

<!--定义Jdbc模板类实例-->
<beanid="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<propertyname="dataSource"ref="dataSource"></property>
</bean>

</beans>
[/code]

-4,业务层

/**
*
*@(#)UserService.java
*@Packagecom.jing.service
*
*Copyright©JINGCorporation.Allrightsreserved.
*
*/
packagecom.jing.service;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Service;
importcom.jing.dao.LoginLogDao;
importcom.jing.dao.UserDao;
importcom.jing.domain.User;
/**
*类描述:用户业务类
*
*@author:JingHistory:Jan14,20154:03:57PMJingCreated.
*
*/
@Service
publicclassUserService{
@Autowired
privateUserDaouserDao;
@Autowired
privateLoginLogDaologinLogDao;
publicUserDaogetUserDao(){
returnuserDao;
}
publicvoidsetUserDao(UserDaouserDao){
this.userDao=userDao;
}
publicLoginLogDaogetLoginLogDao(){
returnloginLogDao;
}
publicvoidsetLoginLogDao(LoginLogDaologinLogDao){
this.loginLogDao=loginLogDao;
}
/**
*
*方法说明:判断是否存在重复的用户名和密码,存在返回true
*
*Author:Jing
*CreateDate:Jan14,20154:06:09PM
*/
publicbooleanhasMatchUsers(StringuserName,Stringpassword){
intmatchCounts=userDao.getMatchCount(userName,password);
returnmatchCounts>0;
}
/**
*
*方法说明:通过用户名查找用户
*
*Author:Jing
*CreateDate:Jan14,20154:10:17PM
*/
publicUserfinUserByName(StringuserName){
returnuserDao.findUserByUserName(userName);
}
/**
*
*方法说明:用户登录成功,记录日志
*
*Author:Jing
*CreateDate:Jan14,20154:11:12PM
*/
publicvoidloginSuccess(Useruser){
}
}
[/code]

<!--标注SERVICE注解类的自动扫描-->
<context:component-scanbase-package="com.jing.service"/>
[/code]

<!--配置事务管理器-->
<beanid="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource"ref="dataSource"></property>
</bean>
<!--AOP配置提供增强事务,让Service下所有Bean的所有方法拥有事务-->
<aop:configproxy-target-class="true">
<aop:pointcutid="serviceMethod"
expression="execution(*com.jing.service..*(..))"/>
<aop:advisorpointcut-ref="serviceMethod"advice-ref="txAdvice"/>
</aop:config>
<tx:adviceid="txAdvice"transaction-manager="transactionManager">
<tx:attributes>
<tx:methodname="*"/>
</tx:attributes>
</tx:advice>
[/code]

单元测试:

packagecom.jing.service;
importjunit.framework.Assert;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.test.context.ContextConfiguration;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*类描述:
*
*@author:JingHistory:Jan14,20154:22:38PMJingCreated.
*
*/
//基于JUnit4的Spring测试框架,使用JUNIT4.5以上的jar包,否则会报错
@RunWith(SpringJUnit4ClassRunner.class)
//启动Spring容器
@ContextConfiguration(locations={"/applicationContext.xml"})
publicclassTestUserService{
@Autowired
privateUserServiceuserService;
@Test
publicvoidtestHasMatchUsers(){
booleanhasUser=userService.hasMatchUsers("lisi","lisi123");
Assert.assertEquals(false,hasUser);
}
publicUserServicegetUserService(){
returnuserService;
}
publicvoidsetUserService(UserServiceuserService){
this.userService=userService;
}
}
[/code]

-5,展现层

配置web.xml文件:

<!--配置从类路径下加载Spring配置文件-->
<context-param>
<param-name>contextConfiglocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--加载监听器,获取Spring的配置文件参数-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<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>.html</url-pattern><!--以.html为后缀,可以隐藏服务器端的具体技术而正真的HTML可以使用.htm来实现-->
</servlet-mapping>
[/code]

新增spring-servlet文件:

<!--扫描web包,应用Spring注解-->
<context:component-scanbase-package="com.jing.web"/>
<!--配置视图解析器-->
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"></property>
<propertyname="prefix"value="/WEB-INF/jsp/"></property>
<propertyname="suffix"value=".jsp"></property>
</bean>
[/code]

packagecom.jing.web;
/**
*类描述:用户登录
*
*@author:JingHistory:Jan15,20159:50:53AMJingCreated.
*
*/
publicclassLoginCommand{
privateStringuserName;
privateStringpassword;
[/code]

/**
*
*@(#)LoginController.java
*@Packagecom.jing.web
*
*Copyright©JINGCorporation.Allrightsreserved.
*
*/
packagecom.jing.web;
importjava.util.Date;
importjavax.servlet.http.HttpServletRequest;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.servlet.ModelAndView;
importcom.jing.domain.User;
importcom.jing.service.UserService;
/**
*类描述:用户登录
*
*@author:JingHistory:Jan15,20159:47:43AMJingCreated.
*
*/
@Controller
publicclassLoginController{
@Autowired
privateUserServiceuserService;
/**
*
*方法说明:处理index.html请求
*
*Author:JingCreateDate:Jan15,201510:11:28AM
*/
@RequestMapping(value="/index.html")
publicStringloginPage(){
return"login";
}
/**
*
*方法说明:处理loginCheck.html请求,负责登录检查
*
*Author:JingCreateDate:Jan15,201510:13:10AM
*/
@RequestMapping(value="/loginCheck.html")
publicModelAndViewloginCheck(HttpServletRequestrequest,
LoginCommandloginCommand){
booleanisValidUser=userService.hasMatchUsers(loginCommand
.getUserName(),loginCommand.getPassword());
if(!isValidUser){
returnnewModelAndView("login","error","用户名或密码错误");
}else{
Useruser=userService.finUserByName(loginCommand.getUserName());
user.setLastIp(request.getRemoteAddr());
user.setLastVisit(newDate());
userService.loginSuccess(user);
request.getSession().setAttribute("user",user);
returnnewModelAndView("main");
}
}
}
[/code]

<%@pagelanguage="java"pageEncoding="utf-8"%>
<%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>登录测试</title>
</head>
<body>
<c:iftest="${!emptyerror}">
<fontcolor="red"><c:outvalue="${error}"/>
</font>
</c:if>
<formaction="<c:urlvalue="loginCheck.html"/>"method="post">
用户名:
<inputtype="text"name="userName"/>
<br/>
密码:
<inputtype="password"name="password"/>
<br/>
<inputtype="submit"value="登录"/>
</form>
</body>
</html>
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: