今天学了一个简单的示例,在此贴出来,以便知识的更新和积累。 Spring采用版本为3.0.5
用户领域对象:
1 package com.baobaotao.domain;
2
3 import java.io.Serializable;
4 import java.util.Date;
5
6 // 领域对象一般要实现Serializable接口, 以便可以序列化
7 public class User implements Serializable {
8
9 private static final long serialVersionUID = 1L;
10
11 private int userId;
12 private String userName;
13 private String password;
14 private int credits;
15 private String lastIp;
16 private Date lastVisit;
17
18 public User() {
19 super();
20 }
21
22 public User(int userId, String userName, String password, int credits,
23 String lastIp, Date lastVisit) {
24 super();
25 this.userId = userId;
26 this.userName = userName;
27 this.password = password;
28 this.credits = credits;
29 this.lastIp = lastIp;
30 this.lastVisit = lastVisit;
31 }
32
33 public int getUserId() {
34 return userId;
35 }
36
37 public void setUserId(int userId) {
38 this.userId = userId;
39 }
40
41 public String getUserName() {
42 return userName;
43 }
44
45 public void setUserName(String userName) {
46 this.userName = userName;
47 }
48
49 public String getPassword() {
50 return password;
51 }
52
53 public void setPassword(String password) {
54 this.password = password;
55 }
56
57 public int getCredits() {
58 return credits;
59 }
60
61 public void setCredits(int credits) {
62 this.credits = credits;
63 }
64
65 public String getLastIp() {
66 return lastIp;
67 }
68
69 public void setLastIp(String lastIp) {
70 this.lastIp = lastIp;
71 }
72
73 public Date getLastVisit() {
74 return lastVisit;
75 }
76
77 public void setLastVisit(Date lastVisit) {
78 this.lastVisit = lastVisit;
79 }
80 }
登录日志领域对象:
1 package com.baobaotao.domain;
2
3 import java.io.Serializable;
4 import java.util.Date;
5
6 // 领域对象一般要实现Serializable接口, 以便可以序列化
7 public class LoginLog implements Serializable {
8
9 private static final long serialVersionUID = 1L;
10
11 private int userId;
12 private String ip;
13 private Date loginDate;
14
15 public LoginLog() {
16 super();
17 }
18
19 public LoginLog(int userId, String ip, Date loginDate) {
20 super();
21 this.userId = userId;
22 this.ip = ip;
23 this.loginDate = loginDate;
24 }
25
26 public int getUserId() {
27 return userId;
28 }
29
30 public void setUserId(int userId) {
31 this.userId = userId;
32 }
33
34 public String getIp() {
35 return ip;
36 }
37
38 public void setIp(String ip) {
39 this.ip = ip;
40 }
41
42 public Date getLoginDate() {
43 return loginDate;
44 }
45
46 public void setLoginDate(Date loginDate) {
47 this.loginDate = loginDate;
48 }
49 }
UserDao层实现:
1 package com.baobaotao.dao.impl;
2
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.jdbc.core.JdbcTemplate;
8 import org.springframework.jdbc.core.RowCallbackHandler;
9 import org.springframework.stereotype.Repository;
10
11 import com.baobaotao.dao.UserDao;
12 import com.baobaotao.domain.User;
13
14 @Repository // 通过Spring注解定义一个DAO
15 public class UserDaoImpl implements UserDao {
16
17 @Autowired // 自动注入JdbcTemplate的Bean
18 private JdbcTemplate jdbcTemplate;
19
20 public int getMatchCount(String userName, String password){
21 String sqlStr = " SELECT COUNT(*) FROM t_user WHERE user_name=? and password=? ";
22 return jdbcTemplate.queryForInt(sqlStr, new Object[]{userName, password});
23 }
24
25 public User findUserByUserName(final String userName){
26 final User user = new User();
27 String sqlStr = " SELECT user_id, user_name, credits FROM t_user WHERE user_name=? ";
28 jdbcTemplate.query(sqlStr, new Object[]{userName}, new RowCallbackHandler() {
29
30 @Override
31 public void processRow(ResultSet rs) throws SQLException {
32 user.setUserId(rs.getInt("user_id"));
33 user.setUserName(userName);
34 user.setCredits(rs.getInt("credits"));
35 }
36 });
37 return user;
38 }
39
40 public void updateLoginInfo(User user){
41 String sqlStr = " UPDATE t_user SET last_visit=?, last_ip=?, credits=? WHERE user_id=? ";
42 jdbcTemplate.update(sqlStr, new Object[]{user.getLastVisit(), user.getLastIp(), user.getCredits(), user.getUserId()});
43 }
44 }
LoginLogDao层实现:
1 package com.baobaotao.dao.impl;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.jdbc.core.JdbcTemplate;
5 import org.springframework.stereotype.Repository;
6
7 import com.baobaotao.domain.LoginLog;
8
9 @Repository
10 public class LoginLogDaoImpl {
11
12 @Autowired
13 private JdbcTemplate jdbcTemplate;
14
15 public void insertLoginLog(LoginLog loginLog){
16 String sqlStr = " INSERT INTO t_login_log(user_id,ip,login_datetime) VALUES(?,?,?) ";
17 Object[] args = {loginLog.getUserId(), loginLog.getIp(), loginLog.getLoginDate()};
18 jdbcTemplate.update(sqlStr, args);
19 }
20 }
LoginController控制器:
1 package com.baobaotao.web;
2
3 import java.util.Date;
4
5 import javax.servlet.http.HttpServletRequest;
6
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.stereotype.Controller;
9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.servlet.ModelAndView;
11
12 import com.baobaotao.domain.User;
13 import com.baobaotao.service.impl.UserServiceImpl;
14
15 @Controller // 标注成为一个Spring MVC的Controller
16 public class LoginController {
17
18 @Autowired
19 private UserServiceImpl userService;
20
21 @RequestMapping(value="/index.html") // 负责处理/index.html的请求
22 public String loginPage(){
23 return "login";
24 }
25
26 @RequestMapping(value="/loginCheck.html") // 负责处理/loginCheck.html的请求
27 public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){
28 boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(), loginCommand.getPassword());
29 if(!isValidUser){
30 return new ModelAndView("login", "error", "用户名或密码错误");
31 } else {
32 User user = userService.findUserByUserName(loginCommand.getUserName());
33 user.setLastIp(request.getLocalAddr());
34 user.setLastVisit(new Date());
35 userService.loginSuccess(user);
36
37 request.getSession().setAttribute("user", user);
38 return new ModelAndView("main");
39 }
40 }
41 }
LoginCommand:
1 package com.baobaotao.web;
2
3 // 控制器所用的POJO类
4 public class LoginCommand {
5 private String userName;
6 private String password;
7
8 public String getUserName() {
9 return userName;
10 }
11
12 public void setUserName(String userName) {
13 this.userName = userName;
14 }
15
16 public String getPassword() {
17 return password;
18 }
19
20 public void setPassword(String password) {
21 this.password = password;
22 }
23 }
web.xml配置:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
6 <display-name></display-name>
7 <!-- 从指定路径下加载Spring配置文件 -->
8 <!-- 从类路径下加载Spring配置文件, classpath关键字特指类路径下加载 -->
9 <!-- 示例:classpath:applicationContext.xml -->
10 <context-param>
11 <param-name>contextConfigLocation</param-name>
12 <param-value>/WEB-INF/applicationContext.xml</param-value>
13 </context-param>
14 <!-- 负责启动Spring容器的监听器, 它将引用上下文参数获得Spring配置文件地址 -->
15 <listener>
16 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
17 </listener>
18 <!-- Spring MVC的主控Servlet -->
19 <servlet>
20 <servlet-name>baobaotao</servlet-name>
21 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
22 <load-on-startup>2</load-on-startup>
23 </servlet>
24 <servlet-mapping>
25 <servlet-name>baobaotao</servlet-name>
26 <url-pattern>*.html</url-pattern>
27 </servlet-mapping>
28 <!-- welcome page -->
29 <welcome-file-list>
30 <welcome-file>index.jsp</welcome-file>
31 </welcome-file-list>
32 </web-app>
baobaotao-servlet.xml:
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
4 xmlns:context="http://www.springframework.org/schema/context"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7 http://www.springframework.org/schema/context
8 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
9 <!-- 扫描web包,应用Spring的注解 -->
10 <context:component-scan base-package="com.baobaotao.web"/>
11
12 <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
13 <bean
14 class="org.springframework.web.servlet.view.InternalResourceViewResolver"
15 p:viewClass="org.springframework.web.servlet.view.JstlView"
16 p:prefix="/WEB-INF/jsp/"
17 p:suffix=".jsp" />
18 </beans>
applicationContext.xml配置文件:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:p="http://www.springframework.org/schema/p"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
10 <context:component-scan base-package="com.baobaotao"/>
11
12 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
13 destroy-method="close"
14 p:driverClassName="com.mysql.jdbc.Driver"
15 p:url="jdbc:mysql://localhost:3306/sampledb"
16 p:username="root"
17 p:password="tiger"/>
18
19 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
20 p:dataSource-ref="dataSource"/>
21
22 </beans>
login.jsp页面文件:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
6 %>
7
8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
9 <html>
10 <head>
11 <base href="<%=basePath%>">
12
13 <title>宝宝淘论坛登录</title>
14
15 <meta http-equiv="pragma" content="no-cache">
16 <meta http-equiv="cache-control" content="no-cache">
17 <meta http-equiv="expires" content="0">
18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19 <meta http-equiv="description" content="This is my page">
20 <!--
21 <link rel="stylesheet" type="text/css" href="styles.css">
22 -->
23 <style type="text/css">
24 body{
25 background-color: #EEEEEE;
26 }
27 #userName, #password {
28 width: 150px;
29 }
30 </style>
31 <script type="text/javascript" src="js/jquery-1.8.0.js"></script>
32 <script type="text/javascript">
33 $(function () {
34 $("#userName").focus();
35 });
36 </script>
37 </head>
38
39 <body>
40 <center>
41 <table>
42 <form action='<c:url value="loginCheck.html"/>' method="post">
43 <tr>
44 <td>用户名:</td>
45 <td><input type="text" name="userName" id="userName" maxlength="10" title="请输入用户名"></td>
46 </tr>
47 <tr>
48 <td>密 码:</td>
49 <td><input type="password" name="password" id="password" maxlength="10" title="请输入密码"></td>
50 </tr>
51 <tr align="center">
52 <td colspan="2" align="center">
53 <input type="submit" value="登录"/>
54 <input type="reset" value="重置"/>
55 </td>
56 </tr>
57 </form>
58 <tr align="center">
59 <td colspan="2">
60 <c:if test="${!empty error }">
61 <font color="red"><c:out value="${error }"/> </font>
62 </c:if>
63 </td>
64 </tr>
65 </table>
66 </center>
67 </body>
68 </html>
main.jsp页面文件:
1 <body>
2 ${user.userName}, 欢迎您进入宝宝淘论坛, 您当前的积分是:${user.credits}
3 </body>
index.jsp页面文件:
1 <body>
2 <jsp:forward page="/WEB-INF/jsp/login.jsp"/>
3 </body>