上一篇的简单登录,只是对用户名进行了下判断,是为了演示Spring的使用。在实际应用中是不会这样做的,而是把用户信息存储在数据库中,通过用户名密码进行验证。本篇就演示下通过数据库进行登录的开发过程。
1、创建用户表
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`uname` varchar(100) NOT NULL COMMENT '用户名',
`pwd` varchar(100) NOT NULL COMMENT '密码',
`email` varchar(100) DEFAULT NULL COMMENT '注册邮箱',
`nickname` varchar(100) DEFAULT NULL COMMENT '昵称',
`createTime` datetime DEFAULT NULL COMMENT '创建时间',
`modifyTime` datetime DEFAULT NULL COMMENT '最后修改时间',
`role` int(1) NOT NULL COMMENT '角色',
`avatar` varchar(100) DEFAULT NULL COMMENT '头像,只存储middle大小的,large和small通过字符串替换获得',
PRIMARY KEY (`id`),
UNIQUE KEY `uname` (`uname`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `nickname` (`nickname`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='用户表';
2、创建DAO
package cn.tsingyu.spring.example.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 cn.tsingyu.spring.example.entity.User;
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public User getUser(final String username,String password){
String sql = " select user_id,user_name from t_user where user_name=? ";
final User user = new User();
jdbcTemplate.query(sql, new Object[]{username},
new RowCallbackHandler(){
public void processRow(ResultSet rs) throws SQLException{
user.setUserId(rs.getInt("user_id"));
user.setUsername(username);
}
});
return user;
}
}
这里使用了JdbcTemplate,暂时觉得没有必要引入其他框架。
3、创建Service
package cn.tsingyu.spring.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.tsingyu.spring.example.dao.UserDao;
import cn.tsingyu.spring.example.entity.User;
@Service
public class UserService {
@Autowired
private UserDao userDao;
public User getUser(final String username,String password){
return userDao.getUser(username, password);
}
}
如果没有加@Autowired注解,userDao就不能通过容器实例化,就会报错空指针异常
严重: Servlet.service() for servlet [tsingyu] in context with path [/spring-example] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at cn.tsingyu.spring.example.controller.LoginController.doLogin(LoginController.java:18)
4、Controller里调用service
package cn.tsingyu.spring.example.controller;
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 cn.tsingyu.spring.example.entity.User;
import cn.tsingyu.spring.example.service.UserService;
@Controller
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping(value="doLogin.html")
public String doLogin(HttpServletRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.getUser(username, password);
if(user.getUserId()!=0){
return "hello";
}else{
return "login";
}
}
}
5、配置文件也需要做相应修改
修改web.xml,添加Listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
如果忘了添加这个配置,会报错
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.tsingyu.spring.example.service.UserService cn.tsingyu.spring.example.controller.LoginController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [cn.tsingyu.spring.example.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
修改web.xml,加载指定的配置文件。如果不指定,会加载WEB-INF下面的默认配置文件,有点不方便管理
<servlet>
<servlet-name>tsingyu</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
指定servlet配置文件:ApplicationContext-mvc.xml,并在这里配置controller的自动扫描和配置视图解析器。
指定上下文的配置文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
数据源的配置在这里,service和dao的自动扫描也在这里。
源码地址:
http://git.oschina.net/smilease/spring-example/tree/v0.2.1