spring3.0通过注解实现登录简单实例

部分代码(可下载附件浏览全部)

UserDao

package com.spring.dao.impl;

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.spring.dao.IUserDao;
import com.spring.pojo.User;


@Repository	//通过spring注解定义一个DAO
public class UserDao implements IUserDao{
	
	@Autowired	//自动注入JdbcTemplate的Bean
	private JdbcTemplate jdbcTemplate;

	public int getMatchCount(String userName, String password) {
		// TODO Auto-generated method stub
		String sql="select count(*) from t_user where user_name=? and password=?";
		int count=jdbcTemplate.queryForInt(sql, new Object[]{userName,password});
		return count;
	}

	public User findUserByUserName(final String userName) {
		// TODO Auto-generated method stub
		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 {
				// TODO Auto-generated method stub
				user.setUserId(rs.getInt("user_id"));
				user.setUserName(userName);
			}
		});
		return user;
	}

	public void updateLoginInfo(User user) {
		// TODO Auto-generated method stub
		String sql="update t_user set last_visit=?,last_ip=? where user_id=?";
		jdbcTemplate.update(sql, new Object[]{user.getLastVisit(),user.getLastIp(),user.getUserId()});
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}

 Controller

package com.spring.controller;

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.spring.biz.IUserBiz;
import com.spring.command.LoginCommand;
import com.spring.pojo.User;

@Controller	//标注成为一个Spring MVC的Controller
@RequestMapping(value="/admin")
public class LoginController {
	
	@Autowired
	private IUserBiz userBiz;
	
	@RequestMapping(value="/login.html")//负责处理/login.html的请求
	public String loginPage(){
		return "login";
	}
	
	@RequestMapping(value="/loginCheck.html")
	public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){//loginCommand一个简单的pojo类属性名与表单相同
		
		boolean isValidUser=userBiz.hasMatchUser(loginCommand.getUserName(), loginCommand.getPassword());
		if (!isValidUser) {
			return new ModelAndView("login","error","用户名/密码错误..!");
		}else {
			User user=userBiz.findUserByUserName(loginCommand.getUserName());
			user.setLastIp(request.getRemoteAddr());
			user.setLastVisit(new Date());
			userBiz.loginSuccess(user);
			request.getSession().setAttribute("user", user);
			return new ModelAndView("index");
		}
	}
	
	
	

	public void setUserBiz(IUserBiz userBiz) {
		this.userBiz = userBiz;
	}

	public IUserBiz getUserBiz() {
		return userBiz;
	}

}

 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.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
		
	<!--扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入-->
	<context:component-scan base-package="com.spring.dao.impl"/>
	<context:component-scan base-package="com.spring.biz.impl"/>

	<!-- 定义一个使用DBCP实现的数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close"
		p:driverClassName="com.mysql.jdbc.Driver"
		p:url="jdbc:mysql://localhost:3306/sample_db?useUnicode=true&amp;characterEncoding=utf-8"
		p:username="root"
		p:password=""/>
	
	<!-- 定义JDBC模板Bean -->
	<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配置提供事务增强,让biz包下所有Bean的所有方法拥有事务 -->
	<aop:config proxy-target-class="true">
		<aop:pointcut id="serviceMethod" expression=" execution(* com.spring.biz.impl..*(..))" />
		<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>

 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">
  <display-name></display-name>	
  
  <!-- 1 从类路径下加载Spring配置文件,classpath关键字特指在类路径下加载 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!-- 负责启动Spring容器的监听器,它将引用1处的上下文参数获得Spring配置文件地址 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- Spring MVC的主控Servlet -->
  
  <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>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 启动服务:访问时得加上LoginController 控制器前的@RequestMapping(value="/admin"),即

http://localhost:8080/spring1/admin/login.html

附件中有详细注释

你可能感兴趣的:(Spring3)