Spring學習實例3-數據庫登陸

上一篇的簡單登陸,只是對用戶名進行了下判斷,是爲了演示Spring的使用。在實際應用中是不會這樣作的,而是把用戶信息存儲在數據庫中,經過用戶名密碼進行驗證。本篇就演示下經過數據庫進行登陸的開發過程。html

一、建立用戶表java

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='用戶表';

二、建立DAOgit

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,暫時以爲沒有必要引入其餘框架。web

三、建立Servicespring

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就不能經過容器實例化,就會報錯空指針異常sql

嚴重: 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)

四、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";
		}
		
	}
}

五、配置文件也須要作相應修改mvc

修改web.xml,添加Listenerapp

<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

相關文章
相關標籤/搜索