spring3.1 mvc jdbc 合成

spring3.1 mvc jdbc 合成
spring3.1 mvc jdbc 合成
代码详见:
实现用户的登录和注册功能:
package com.model;
import java.io.Serializable;
/**
 * 模型层
 * @author qiyang
 *
 */
@SuppressWarnings("serial")
public class User implements Serializable {
	//http://my.oschina.net/huangcongmin12/blog/81216
	private int id;
	private String userName;
	private String password;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	@Override
	public String toString() {
		return id+", "+userName+", "+password;
	}
}

package com.dao.implement;

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.dao.UserDao;
import com.model.User;
/**
 * 
 * @author qiyang
 * 数据层
 */
@Repository
public class UserDaoImpl implements UserDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	/**find user by username*/
	public User findUserByUserName(String userName) {
		String sqlStr = "select id,uname,pwd from user where uname=?";
		//注意此处为何如此写?
		final User user = new User();
		jdbcTemplate.query(sqlStr, new Object[]{userName},new RowCallbackHandler(){
			public void processRow(ResultSet rs) throws SQLException {
				user.setId(rs.getInt("id"));
				user.setUserName(rs.getString("uname"));
				user.setPassword(rs.getString("pwd"));
			}
		});
		return user;
	}
	/**register*/
	public void register(User user) {
		String sqlStr = "insert into user(uname,pwd) values(?,?)";
		Object [] params = new Object[]{user.getUserName(),user.getPassword()};
		jdbcTemplate.update(sqlStr,params);
	}

}

package com.service.implement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dao.UserDao;
import com.model.User;
import com.service.UserService;
/**
 * 业务层
 * @author qiyang
 *
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	
	public User loginCheck(User user) {
		//此处获得的   u 会为空吗?如果会,程序有可能跑异常哦
		User u = userDao.findUserByUserName(user.getUserName());
		System.out.println("id="+u.getId()+", userName="+u.getUserName()+", Password="+u.getPassword());
		if(user.getPassword().equals(u.getPassword())){
			return u;
		}else{
			return null;
		}
	}

	public boolean register(User user) {
		//此处先查询用户名是否已经存在
		User u = userDao.findUserByUserName(user.getUserName());
		if(u.getId()==0){
			//注册
			userDao.register(user);
			return true;
		}else{
			System.out.println("用户已经存在!");
			System.out.println("id="+u.getId()+", userName="+u.getPassword()+", Password="+u.getPassword());
			return false;
		}
	}
	
}

package com.controller;

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.model.User;
import com.service.UserService;
/**
 * 表示层--控制器
 * @author qiyang
 *
 */
@Controller
public class UserController {
	@Autowired
	private UserService userService;
	@RequestMapping("/user/loginView")
	public String loginView(){
		return "login";
	}
	
	@RequestMapping("/user/registView")
	public String registView(){
		return "register";
	}
	
	@RequestMapping("/user/login")
	public ModelAndView login(User user){
		System.out.println("用户登录!!!");
		ModelAndView mav = new ModelAndView();
		User u = userService.loginCheck(user);
		System.out.println(u);
		if(null==u){
			System.out.println("登录失败了........");
			//登录失败
			mav.setViewName("login");
			mav.addObject("errorMsg", "用户名或密码错误!");
			return mav;
		}else{
			//登录成功
			System.out.println("登录成功了........");
			mav.setViewName("success");
			mav.addObject("user",u);
			return mav;
		}
	}
	
	@RequestMapping("/user/register")
	public ModelAndView register(User user){
		ModelAndView mav = new ModelAndView();
		if(userService.register(user)){
			//注册成功
			mav.setViewName("register_succ");
			return mav;
		}else{
			//注册失败
			mav.setViewName("register");
			mav.addObject("errorMsg","用户名已经被占用");
			return mav;
		}
	}
	
}

主要配置文件:
beans.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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
		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.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<!-- jdbc.properties配置信息 文件路径 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 扫描类包 将标注Spring 注解的类自动转换成bean ,同时完成注入 -->
	<context:component-scan base-package="com.controller"/>
	<context:component-scan base-package="com.service"/>
	<context:component-scan base-package="com.dao"/>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" destroy-method="close" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass">
			<value>${jdbc.driverClassName}</value>
		</property>
		<property name="jdbcUrl">
			<value>${jdbc.url}</value>
		</property>
		<property name="user">
			<value>${jdbc.username}</value>
		</property>
		<property name="password">
			<value>${jdbc.password}</value>
		</property>
		<!-- 连接池中保留的最小连接 -->
		<property name="minPoolSize">
			<value>5</value>
		</property>
		<!-- 连接池中保留最大连接数(default 15) -->
		<property name="maxPoolSize">
			<value>30</value>
		</property>
		<!-- 初始化时,获取的连接数 应该在minPoolSize and maxPoolSize之间 default 3 -->
		<property name="initialPoolSize">
			<value>10</value>
		</property>
		<!-- 最大空闲时间,n妙内未使用则丢弃,0则永远不丢弃 default0 -->
		<property name="maxIdleTime">
			<value>60</value>
		</property>
		<!-- 连接池中连接耗尽时 c3p0一次获得的连接数 default 3-->
		<property name="acquireIncrement">
			<value>5</value>
		</property>
		<!-- JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。
		但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这
		个参数需要考虑到多方面的因素,如果maxStatements与maxStatementsPerC
		onnection均为0,则缓存被关闭。Default: 0-->
		<property name="maxStatements">
			<value>0</value>
		</property>
		<!-- 每隔n妙检查连接初中的空闲数 default:0 -->
		<property name="idleConnectionTestPeriod">
			<value>60</value>
		</property>
		<!-- 获取新连接失败后,尝试的次数 30 -->
		<property name="acquireRetryAttempts">
			<value>30</value>
		</property>
	</bean>
	<!-- 配置jdbc模板 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	<!-- 配置事物管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- 通过aop配置提供事务增强 让 service包下所有bean 的方法拥有事务 -->
	<!-- expression="execution(* *..*Service.*(..))" 
	 	第一个* 表示任意返回值类型
		第二个* 表示以任意名字开头的package. 如 com.xx.
		第三个* 表示以任意名字开头的class的类名 如TestService
		第四个* 表示 通配 *service下的任意class
		最后二个.. 表示通配 方法可以有0个或多个参数
	 -->
	<aop:config proxy-target-class="true" >
		<aop:pointcut id="serviceMethod" expression="execution(* com.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>
	<!-- 启动spring mvc的注解功能 完成请求和注解pojo的映射-->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
	<!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>

jdbc.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=*****

页面部分:
登录:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
</head>
<body>
	<form action="login.do" method="post">
		<h1 align="center">Login</h1>
		<table border="1" width="400" align="center">
		<tr>
			<td  colspan="2"><c:if test="${!empty errorMsg}">
    			<font size="2" color="red">${errorMsg}</font>
    			</c:if>
    		</td>
		</tr>
		<tr>
			<td>uname:</td><td><input type="text" name="userName"></td>
		</tr>
		<tr>
			<td>pwd:</td><td><input type="password" name="password"><br/></td>
		</tr>
		<tr>
			<td></td><td><input type="submit" value="login">
				<a href="registView.do">register</a>
			</td>
		</tr>
		</table>
	</form>
	
</body>
</html>

注册页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
</head>
<body>
	<form action="register.do" method="post">
		<h1 align="center">Register</h1>
		<table border="1" width="400" align="center">
		<tr>
			<td  colspan="2"><c:if test="${!empty errorMsg}">
    			<font size="2" color="red">${errorMsg}</font>
    			</c:if>
    		</td>
		</tr>
		<tr>
			<td>uname:</td><td><input type="text" name="userName"></td>
		</tr>
		<tr>
			<td>pwd:</td><td><input type="password" name="password"><br/></td>
		</tr>
		<tr>
			<td></td><td><input type="submit" value="register" /></td>
		</tr>
		</table>
	</form>
</body>
</html>
成功页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
</head>
<body>
	<h1>亲爱的${user.userName },登录成功!</h1>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
</head>
<body>
	<h1>注册成功!</h1>
	<a href="loginView.do">返回登录页面</a>
</body>
</html>

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">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- 装载spring组件  -->
  <listener>
  	<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <!-- 装载spring mvc -->
  <servlet>
  	<servlet-name>spring</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:applicationContext.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>spring</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- 编码过滤器 -->
  <filter>
  	<filter-name>setcharacter</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>setcharacter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

你可能感兴趣的:(spring,mvc,jdbc)