《Spring3.0就这么简单》第1章快速入门
问题
【问题】java.lang.ClassNotFoundException: org.objectweb.asm.Type
添加依赖:
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
代码路径
创建库表
DROP DATABASE IF EXISTS sampledb31;
CREATE DATABASE sampledb31 DEFAULT CHARACTER SET utf8;
USE sampledb31;
##创建用户表
CREATE TABLE t_user (
user_id INT AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(30),
password VARCHAR(32),
last_visit datetime,
last_ip VARCHAR(23)
)ENGINE=InnoDB;
##创建用户登录日志表
CREATE TABLE t_login_log (
login_log_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
ip VARCHAR(23),
login_datetime datetime
)ENGINE=InnoDB;
##插入初始化数据
INSERT INTO t_user (user_name,password)
VALUES('admin','123456');
COMMIT;
##查询
select * from t_user;
select * from t_login_log;
pom.xml
<dependency><!--①依赖的Spring模块类库 -->
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
Maven仓库规则
<dependency>下面这个是hibernate的Dependency配置
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.6.ga</version>
</dependency>
它被下载后将会被存放至
%repository%\org\hibernate\hibernate\3.2.6.ga\hibernate-3.2.6.ga.jar
其中%repository%就是你本地的repository目录!
不知大家看出来了没有,它是按你的Dependency的groupid + artifactid + version,然后以点号作分隔,来建立文件夹的,最后建立的文件夹如下
|--org
|--hibernate
|--hibernate
|--3.2.6.ga
|--hibernate-3.2.6.ga.jar
可能会有些人会问那个jar包的名字是怎么来的,细心的人或许早己观察出来了,没错,就是artifactId + "-" + version + ".jar"。
好了,下面我们按这个规则去找一下另外一个Dependency放在哪吧
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-servlet</artifactId>
<version>1.4.61</version>
</dependency>
持久层领域对象:User.java + LoginLog.java
package com.smart.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private int userId;
private String userName;
private String password;
private String lastIp;
private Date lastVisit;
//省略一系列set/get方法
}
UserDao
import java.sql.ResultSet;package com.smart.dao;
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.smart.domain.User;
//通过Spring注解定义一个DAO
@Repository
public class UserDao {
//自动注入JdbcTemplate的Bean
@Autowired
private JdbcTemplate jdbcTemplate;
public int getMatchCount(String userName, String password) {
String sqlStr = " SELECT count(*) FROM t_user "
+ " WHERE user_name =? and password=? ";
return jdbcTemplate.queryForInt(sqlStr, new Object[]{userName, password});
}
public User findUserByUserName(final String userName) {
String sqlStr = " SELECT user_id,user_name "
+ " 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.getInt("user_id"));
user.setUserName(userName);
}
});
return user;
}
public void updateLoginInfo(User user) {
String sqlStr = " UPDATE t_user SET last_visit=?,last_ip=?"
+ " WHERE user_id =?";
jdbcTemplate.update(sqlStr, new Object[]{user.getLastVisit(),
user.getLastIp(), user.getUserId()});
}
}
LoginLogDao
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.smart.domain.LoginLog;
@Repository
public class LoginLogDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void insertLoginLog(LoginLog loginLog) {
String sqlStr = "INSERT INTO t_login_log(user_id,ip,login_datetime) "
+ "VALUES(?,?,?)";
Object[] args = {loginLog.getUserId(), loginLog.getIp(),
loginLog.getLoginDate()};
jdbcTemplate.update(sqlStr, args);
}
}
在Spring中装配DAO: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/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<context:component-scan base-package="com.smart.dao"/>
<context:component-scan base-package="com.smart.service"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/sampledb31"
p:username="root"
p:password="123" />
<!-- 配置Jdbc模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" />
<!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod"
expression=" execution(* com.smart.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>
</beans>
业务层:UserService
import org.springframework.beans.factory.annotation.Autowired;package com.smart.service;
import org.springframework.stereotype.Service;
import com.smart.dao.LoginLogDao;
import com.smart.dao.UserDao;
import com.smart.domain.LoginLog;
import com.smart.domain.User;
//将一个UserService标注为一个服务层的Bean。
@Service
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) {
LoginLog loginLog = new LoginLog();
loginLog.setUserId(user.getUserId());
loginLog.setIp(user.getLastIp());
loginLog.setLoginDate(user.getLastVisit());
loginLogDao.insertLoginLog(loginLog);
}
}
展现层(Spring MVC配置)
自动启动Spring容器的配置:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
从类路径下加载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>
Spring MVC地址映射:web.xml(servlet截获URL请求)
<servlet>
<servlet-name>viewspace</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>viewspace</servlet-name>
<url-pattern>*.html</url-pattern> 让所有以.html为后缀的URL都能被viewspace Servlet截获。转由Spring MVC框架进行处理。
</servlet-mapping>
</web-app>
请求被Spring MVC截获后,首先根据请求的URL查找目标的处理控制器。
并将请求参数封装成一个“命令”对象一起传给控制器处理。
控制器调用Spring容器中的业务Bean完成业务处理工作并返回结果视图。
LoginController 处理登陆请求
1.6.2 处理控制器 |
package com.smart.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.smart.domain.User;
import com.smart.service.UserService;
//标记为Spring MVC的控制器
@Controller
@RequestMapping(value = "/admin") 【指定方法如何映射请求路径】
public class LoginController {
@Autowired
private UserService userService;
//负责处理/login.html请求
@RequestMapping(value = "/login.html")
public String loginPage() {
//System.out.println("LoginController loginPage()");
return "login";
}
//负责处理/loginCheck.html请求
@RequestMapping(value = "/loginCheck.html")
public ModelAndView loginCheck(HttpServletRequest request, LoginCommand 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.getLocalAddr());
user.setLastVisit(new Date());
userService.loginSuccess(user);
request.getSession().setAttribute("user", user);
return new ModelAndView("main");
}
}
}
viewspace-servlet.xml
Spring MVC配置文件 |
在viewspace-servlet.xml中声明LoginCommand控制器。
<?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/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- 扫描web包,应用Spring的注解 -->
<context:component-scan base-package="com.smart.web"/>
<bean id="defaultAnnotationHandlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean id="annotationMethodHandlerAdapter"
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"/>
</beans>
ModelAndView的解析配置 - viewspace-servlet.xml
第二个和第三个参数分别为数据模型名称,数据模型对象。
ModelAndView第一个参数代表视图的逻辑名。(login....main...)
数据模型对象将以数据模型名称为参数名,放置到request的属性中。
定义解析规则的bean,将视图逻辑名解析为具体的视图页面。
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"/>
</beans>
【视图逻辑名mian解析为:/WEB-INF/jsp/main.jsp】
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>
//JSTL标签库对登陆错误返回的信息进行处理。
引用的error变量。这个变量是 return new ModelAndView("login", "error", "用户名或密码错误"); 中的error参数。
<c:if test="${!empty error}">
<font color="red"><c:out value="${error}"/></font>
</c:if>
<form action="<c:url value="/admin/loginCheck.html"/>" method="post"> 自动加上应用程序部署根目录。<c:url>标签将输出/admin/loginController.html。
用户名:
<input type="text" name="userName">
<br>
密码:
<input type="password" name="password">
<br>
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
</form>
</body>
</html>