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

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

2015-01-15 13:58 330 查看
原文链接:http://www.cnblogs.com/jingLongJun/p/4491056.html 1,登录demo     -1,建表
CREATE TABLE T_USER(USER_ID NUMBER(16),
USER_NAME VARCHAR2(30),
CREDITS NUMBER(16),
PASSWORD VARCHAR2(32),
LAST_VISIT DATE,
LAST_IP VARCHAR2(32));
 
CREATE TABLE T_LOGIN_LOG(LOGIN_LOG_ID NUMBER(16),
USER_ID NUMBER(16),
IP VARCHAR2(32),
LOGIN_DATETIME DATE);
    -2,建立对应package,如下图:
    -3,新建model,dao并配置
/**
* 类描述:用户类
*
*@author: Jing History: Jan 14, 2015 3:09:40 PM Jing Created.
*
*/
public class User implements Serializable {
 
private static final long serialVersionUID = 1L;
 
private int userId;
private String userName;
private String password;
private int credits;
private String lastIp;
private Date lastVisit;
/**
*类描述:登录日志
*
*@author: Jing History: Jan 14, 2015 3:11:28 PM Jing Created.
*
*/
public class LoginLog implements Serializable {
 
private static final long serialVersionUID = 1L;
 
private int loginLogId;
private int userId;
private String ip;
private Date loginDate;
/**
*
*@(#) UserDao.java
*@Package com.jing.dao
*
*Copyright © JING Corporation. All rights reserved.
*
*/
 
package com.jing.dao;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
 
import com.jing.domain.User;
 
/**
*类描述:用户查询类
*
*@author: Jing History: Jan 14, 2015 3:13:56 PM Jing Created.
*
*/
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
 
/**
*
*方法说明:根据用户名和密码获取匹配用户数
*
*Author: Jing Create Date: Jan 14, 2015 3:21:20 PM
*/
@SuppressWarnings("deprecation")
public int getMatchCount(String userName, String password) {
 
String sqlStr = "select COUNT(1) FROM T_USER WHERE user_name = ? AND PASSWORD = ?";
 
return jdbcTemplate.queryForInt(sqlStr, new Object[] { userName,
password });
}
 
/**
*
*方法说明:通过用户名获取用户信息
*
*Author: Jing Create Date: Jan 14, 2015 3:27:16 PM
*/
public User findUserByUserName(final String userName) {
User user = new User();
String sqlStr = "SELECT a.user_id, a.user_name, a.credits FROM t_user a WHERE a.user_name = ? ";
user = jdbcTemplate.queryForObject(sqlStr, user.getClass(),
new Object[] { userName });
return user;
}
 
/**
*
*方法说明:更新用户信息
*
*Author: Jing Create Date: Jan 14, 2015 3:35:08 PM
*/
public void updateLoginInfo(User user) {
 
String sql = "UPDATE t_user SET last_visit = ?, last_ip = ?, credits = ? WHERE user_id = ?";
jdbcTemplate.update(sql, new Object[] { user.getLastVisit(),
user.getLastIp(), user.getCredits(), user.getUserId() });
}
 
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
 
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
 
}
/**
*
*@(#) LoginLogDao.java
*@Package com.jing.dao
*
*Copyright © JING Corporation. All rights reserved.
*
*/
 
package com.jing.dao;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
 
import com.jing.domain.LoginLog;
 
/**
*类描述:登录日志Dao
*
*@author: Jing History: Jan 14, 2015 3:40:28 PM Jing Created.
*
*/
@Repository
public class LoginLogDao {
 
@Autowired
private JdbcTemplate jdbcTemplate;
 
/**
*
*方法说明:插入用户登录日志
*
*Author: Jing Create Date: Jan 14, 2015 3:46:01 PM
*/
public void insertLoginLog(LoginLog log) {
 
String sql = "INSERT INTO t_login_log(LOGIN_LOG_ID, user_id, ip,LOGIN_DATETIME ) VALUES (?, ?,?,?)";
jdbcTemplate.update(sql, new Object[] { log.getLoginLogId(),
log.getUserId(), log.getIp(), log.getLoginDate() });
}
 
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
 
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
 
}
<?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: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
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ">
 
<!-- 标注注解类的自动扫描 -->
<context:component-scan base-package="com.jing.dao" />
 
<!-- 定义数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:@xxxxxxx:1521:xxxx" />
<property name="username" value="xxxx" />
<property name="password" value="xxxxx" />
</bean>
 
<!-- 定义Jdbc模板类实例-->     <bean id="jdbcTemplate"         class="org.springframework.jdbc.core.JdbcTemplate">         <property name="dataSource" ref="dataSource"></property>     </bean>
</beans>
-4,业务层
/**
*
*@(#) UserService.java
*@Package com.jing.service
*
*Copyright © JING Corporation. All rights reserved.
*
*/
 
package com.jing.service;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.jing.dao.LoginLogDao;
import com.jing.dao.UserDao;
import com.jing.domain.User;
 
/**
*类描述:用户业务类
*
*@author: Jing History: Jan 14, 2015 4:03:57 PM Jing Created.
*
*/
@Service
public class UserService {
 
@Autowired
private UserDao userDao;
 
@Autowired
private LoginLogDao loginLogDao;
 
public UserDao getUserDao() {
return userDao;
}
 
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
 
public LoginLogDao getLoginLogDao() {
return loginLogDao;
}
 
public void setLoginLogDao(LoginLogDao loginLogDao) {
this.loginLogDao = loginLogDao;
}
/**
*
*方法说明:判断是否存在重复的用户名和密码,存在返回true
*
*Author:       Jing                
*Create Date:   Jan 14, 2015 4:06:09 PM
*/
public boolean hasMatchUsers(String userName, String password) {
 
int matchCounts = userDao.getMatchCount(userName, password);
return matchCounts > 0;
}
/**
*
*方法说明:通过用户名查找用户
*
*Author:       Jing                
*Create Date:   Jan 14, 2015 4:10:17 PM
*/
public User finUserByName(String userName){
return userDao.findUserByUserName(userName);
}
/**
*
*方法说明:用户登录成功,记录日志
*
*Author:       Jing                
*Create Date:   Jan 14, 2015 4:11:12 PM
*/
public void loginSuccess(User user){
}
 
}
 
<!-- 标注SERVICE注解类的自动扫描 -->
<context:component-scan base-package="com.jing.service" />
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
 
<!-- AOP配置提供增强事务,让Service下所有Bean的所有方法拥有事务 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod"
expression="execution(*com.jing.service..*(..))" />
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" />
</tx:attributes>
</tx:advice>
单元测试:
package com.jing.service;
 
import junit.framework.Assert;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
/**
*类描述:
*
*@author: Jing History: Jan 14, 2015 4:22:38 PM Jing Created.
*
*/
// 基于JUnit4的Spring测试框架,使用JUNIT4.5以上的jar包,否则会报错
@RunWith(SpringJUnit4ClassRunner.class)
// 启动Spring容器
@ContextConfiguration(locations = { "/applicationContext.xml" })
public class TestUserService {
@Autowired
private UserService userService;
 
@Test
public void testHasMatchUsers() {
 
boolean hasUser = userService.hasMatchUsers("lisi", "lisi123");
Assert.assertEquals(false, hasUser);
}
 
public UserService getUserService() {
return userService;
}
 
public void setUserService(UserService userService) {
this.userService = userService;
}
 
}
-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>
新增spring-servlet文件:
<!-- 扫描web包,应用Spring注解 -->
<context:component-scan base-package="com.jing.web"/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
package com.jing.web;
 
/**
*类描述:用户登录
*
*@author: Jing History: Jan 15, 2015 9:50:53 AM Jing Created.
*
*/
public class LoginCommand {
 
private String userName;
private String password;
/**
*
*@(#) LoginController.java
*@Package com.jing.web
*
*Copyright © JING Corporation. All rights reserved.
*
*/
 
package com.jing.web;
 
import java.util.Date;
 
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.servlet.ModelAndView;
 
import com.jing.domain.User;
import com.jing.service.UserService;
 
/**
*类描述:用户登录
*
*@author: Jing History: Jan 15, 2015 9:47:43 AM Jing Created.
*
*/
@Controller
public class LoginController {
 
@Autowired
private UserService userService;
 
/**
*
*方法说明:处理index.html请求
*
*Author: Jing Create Date: Jan 15, 2015 10:11:28 AM
*/
@RequestMapping(value = "/index.html")
public String loginPage() {
 
return "login";
}
 
/**
*
*方法说明:处理loginCheck.html请求,负责登录检查
*
*Author: Jing Create Date: Jan 15, 2015 10:13:10 AM
*/
@RequestMapping(value = "/loginCheck.html")
public ModelAndView loginCheck(HttpServletRequest request,
LoginCommand loginCommand) {
 
boolean isValidUser = userService.hasMatchUsers(loginCommand
.getUserName(), loginCommand.getPassword());
if(!isValidUser){
return new ModelAndView("login", "error", "用户名或密码错误");
}else{
User user = userService.finUserByName(loginCommand.getUserName());
user.setLastIp(request.getRemoteAddr());
user.setLastVisit(new Date());
userService.loginSuccess(user);
request.getSession().setAttribute("user", user);
return new ModelAndView("main");
}
}
}
<%@ page language="java" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
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>登录测试</title>
</head>
<body>
<c:if test="${!empty error}">
<font color="red"><c:out value="${error}" />
</font>
</c:if>
<form action="<c:url value="loginCheck.html"/> " method="post">
用户名:
<input type="text" name="userName" />
<br />
密 码:
<input type="password" name="password" />
<br />
<input type="submit" value="登录" />
</form>
</body>
</html>







转载于:https://www.cnblogs.com/jingLongJun/p/4491056.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: