实现步骤
- 初始化MySQL数据库 建立库表并初始化数据
- 编码domain、dao、service包下class
- applicationContext.xml 配置(配置数据源、注册Bean、事务控制)
- 测试业务层逻辑
- POJO 控制层业务编码
- web.xml 配置(初始化applicationContext.xml、监听请求、处理MVC url)
demo目录
- src
- com
- baobaotao
- dao
- domain
- service
- web
- applicationContext.xml
- log4j.properties
- baobaotao
- com
- test
- com
- baobaotao
- service
- baobaotao
- com
初始化MySQL数据库 建立库表并初始化数据
创建用户表
CREATE TABLE `t_user` (
`user_id` bigint(22) NOT NULL COMMENT '用户主键',
`user_name` varchar(30) DEFAULT NULL COMMENT '用户名称',
`credits` int(11) DEFAULT NULL,
`password` varchar(32) DEFAULT NULL COMMENT '密码',
`last_visit` datetime DEFAULT NULL,
`last_ip` varchar(23) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
登录记录表
CREATE TABLE `t_login_log` (
`login_log_id` bigint(22) NOT NULL COMMENT '日志主键',
`user_id` bigint(22) DEFAULT NULL COMMENT '用户主键',
`ip` varchar(23) DEFAULT NULL,
`login_datetime` datetime DEFAULT NULL,
PRIMARY KEY (`login_log_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
初始化数据
insert into t_user (user_name,password) values("amdin","123456");
编码domain、dao、service包下class
- domain 领域对象
package com.baobaotao.domain;
import java.io.Serializable;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
/**
*用户领域对象
*/
@Getter
@Setter
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private Long userId;
private String userName;
private String password;
private int credits;
private String lastIp;
private Date lastVisit;
}
package com.baobaotao.domain;
import java.io.Serializable;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
/**
*登录日志领域对象
*/
@Getter
@Setter
public class LoginLog implements Serializable{
private static final long serialVersionUID = 1L;
private Long loginLogId;
private Long userId;
private String ip;
private Date loginDate;
}
- dao 数据操作
package com.baobaotao.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import com.baobaotao.domain.User;
/**
*用户信息操作
*/
@Repository//通过Spring注解定义一个Dao
public class UserDao {
@Autowired//自动注入jdbcTemplate的Bean
private JdbcTemplate jdbcTemplate;
public int getMatchCount(String userName, String password) {
String sqlStr = "SELECT COUNT(*) FROM t_user WHERE user_name=? AND PASSWORD=?";
return jdbcTemplate.queryForObject(sqlStr, new Object[] {userName,password}, Integer.class);
}
public User findUserByUserName(final String userName) {
String sqlStr = "SELECT user_id,user_name,credits FROM t_user WHERE user_name=?";
final User user = new User();
jdbcTemplate.query(sqlStr, new Object[] { userName }, new RowCallbackHandler(){
public void processRow(ResultSet rs) throws SQLException {
user.setUserId(rs.getLong("user_id"));
user.setUserName(userName);
user.setCredits(rs.getInt("credits"));
}
});
return user;
}
public void updateLoginInfo(User user) {
String sqlStr = "UPDATE t_user SET last_visit=?,last_ip=?,credits=? WHERE user_id=?";
jdbcTemplate.update(sqlStr, new Object[] {
user.getLastVisit(), user.getLastIp(), user.getCredits(), user.getUserId()
});
}
}
package com.baobaotao.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.baobaotao.domain.LoginLog;
/**
*用户信息操作
*/
@Repository
public class LoginLogDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void insertLoginLog(LoginLog loginLog) {
String sqlStr = "INSERT INTO t_login_log(login_log_id,user_id,ip,login_datetime) VALUES (?,?,?,?)";
Object[] args = { loginLog.getLoginLogId(), loginLog.getUserId(), loginLog.getIp(), loginLog.getLoginDate()};
jdbcTemplate.update(sqlStr, args);
}
}
- UserService 业务层
package com.baobaotao.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baobaotao.dao.LoginLogDao;
import com.baobaotao.dao.UserDao;
import com.baobaotao.domain.LoginLog;
import com.baobaotao.domain.User;
@Service //将UserService标注为一个服务层的Bean
public class UserService {
@Autowired
private UserDao userDao;
@Autowired
private LoginLogDao loginLogDao;
public boolean hasMatchUser(String userName, String password) {
int matchCount = userDao.getMatchCount(userName, password);
return matchCount > 0;
}
public User findUserByUserName(String userName) {
return userDao.findUserByUserName(userName);
}
public void loginSuccess(User user) {
user.setCredits(5 + user.getCredits());
LoginLog loginLog = new LoginLog();
loginLog.setLoginLogId(8L);
loginLog.setUserId(user.getUserId());
loginLog.setIp(user.getLastIp());
loginLog.setLoginDate(user.getLastVisit());
userDao.updateLoginInfo(user);
loginLogDao.insertLoginLog(loginLog);
}
}
applicationContext.xml 配置(配置数据源、注册Bean、事务控制)
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<!-- @1 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<context:component-scan base-package="com.baobaotao.dao" />
<context:component-scan base-package="com.baobaotao.service" />
<!-- @2 定义一个使用DBCP实现的数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/hm_dream?characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="hm123" />
</bean>
<!-- @3 定义jdbc模板Bean -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- @4 通过aop配置提供事务增强,让service包下所有Bean的方法用有事务 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod" expression="execution(* *..*Service.*(..))"/>
<!-- 第一个* 表示任意返回值类型
第二个* 表示以任意名字开头的package. 如 com.xx.
第三个* 表示以任意名字开头的class的类名 如TestService
第四个* 表示 通配 *service下的任意class
最后二个.. 表示通配 方法可以有0个或多个参数 -->
<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>
</beans>
单元测试 测试业务层逻辑
package com.baobaotao.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
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;
import com.baobaotao.domain.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"/applicationContext.xml"})
public class TestUserService {
@Autowired
private UserService userService;
@Test
public void hasMatchUser() {
boolean b1 = userService.hasMatchUser("admin", "123456");
boolean b2 = userService.hasMatchUser("admin", "111111");
System.err.println("==================" + b1 + " & "+ b2);
assertTrue(b1);
assertTrue(b2);
}
@Test
public void findUserByUserName() {
User user = userService.findUserByUserName("admin");
System.err.println(user);
userService.loginSuccess(user);
assertEquals(user.getUserName(), "admin");
}
}
POJO 控制层业务编码
package com.baobaotao.web;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class LoginCommand {
private String userName;
private String password;
}
package com.baobaotao.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.baobaotao.domain.User;
import com.baobaotao.service.UserService;
//@1 表主成为一个Spring MVC的Controller
@Controller
public class LoginController {
@Autowired
private UserService userService;
//@2 负责处理/index.html的请求
@RequestMapping(value="/index.html")
public String loginPage() {
return "login";
}
//@3 负责处理/loginCheck.html
@RequestMapping(value="/loginCheck.html")
public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand) {
boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(), loginCommand.getPassword());
if(!isValidUser) {
return new ModelAndView("login","error","用户名或密码错吗");
}else {
User user = userService.findUserByUserName(loginCommand.getUserName());
user.setLastIp(request.getRemoteAddr());
user.setLastVisit(new Date());
userService.loginSuccess(user);
request.getSession().setAttribute("user", user);
return new ModelAndView("main");
}
}
}
web.xml 配置(初始化applicationContext.xml、监听请求、处理MVC url)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>chapter</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- @1 从路径下加载Spring配置文件,classpath关键子特指类路径下加载 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<!-- @2 负责启动Spring容器的监听器,它将应用@1出的上下文参数获取Spring配置文件地址 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Spring Mvc 的主控Servlet -->
<servlet>
<servlet-name>baobaotao</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Spring MVC处理的URL -->
<servlet-mapping>
<servlet-name>baobaotao</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
- baobaotao-servlet.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<!-- @1 扫描web包,应用Spring注解 -->
<context:component-scan base-package="com.baobaotao.web" />
<!-- @2 配置试图解析器,将ModelAndView及字符串解析为具体的页面 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
页面
- 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' %>
<html>
<head>
<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="登录">
<input type="reset" value="重置">
</form>
</body>
</html>
- main.jsp 登录成功主要
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix='c' %>
<html>
<head>
<title>宝宝淘论坛登录</title>
</head>
<body>
${user.userName },欢迎您进入宝宝淘论坛,您当前积分为${user.credits };
</body>
</html>