天天看點

Spring的jdbcTemplate完成登入使用者登入功能

小白起步,從零開始,力求詳細。

1.建立一個webx項目

Spring的jdbcTemplate完成登入使用者登入功能

2.将以下jar包放入web-inf/lib目錄(網上當的jar包,有備援,)

Spring的jdbcTemplate完成登入使用者登入功能
Spring的jdbcTemplate完成登入使用者登入功能

3.配置web.xml檔案

<span style="background-color: rgb(51, 255, 255);"><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 部署項目時,加載配置檔案, 其中dispatcher-servlet.xml放在web-inf目錄下預設加載,但名字格式為:項目名servlet.xml-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/dispatcher-servlet.xml,/WEB-INF/beans.xml</param-value>
	</context-param>
	<!--攔截請求  -->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
	
	<filter>
		<filter-name>encodingFilter</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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app></span>
           

4.建立目錄的結構,個人習慣,喜歡把大緻目錄搞出來,往裡邊填東西。

Spring的jdbcTemplate完成登入使用者登入功能
Spring的jdbcTemplate完成登入使用者登入功能

5.建立資料庫表,并插入資料,使用的oracle

Spring的jdbcTemplate完成登入使用者登入功能

6.至此,各個結構都出來了,讓我們愉快的填充内容吧。

6.1建立實體類

(注意屬性名稱與資料庫中相同,否則會報空指針)

package com.entry;

import javax.persistence.Entity;

@Entity
public class User {

	private int u_id;
	private String u_name;
	private String u_pwd;
	public User() {
		super();
	}
	public User(int u_id, String u_name, String u_pwd) {
		super();
		this.u_id = u_id;
		this.u_name = u_name;
		this.u_pwd = u_pwd;
	}
	public int getU_id() {
		return u_id;
	}
	public void setU_id(int u_id) {
		this.u_id = u_id;
	}
	public String getU_name() {
		return u_name;
	}
	public void setU_name(String u_name) {
		this.u_name = u_name;
	}
	public String getU_pwd() {
		return u_pwd;
	}
	public void setU_pwd(String u_pwd) {
		this.u_pwd = u_pwd;
	}
	
	
}
           

6.2建立DAO與DAO的實作類

UserDao.java

package com.dao;

import java.util.List;

import com.entry.User;

public interface UserDao {
	public List<User> getUsers();
}
           

UserDaoImpl.java

package com.daoImpl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.dao.UserDao;
import com.entry.User;

@Repository
public class UserDaoImpl implements UserDao{
	@Resource
	private JdbcTemplate jdbcTemplate;
		//UUID.randomUUID().toString(),
	public List<User> getUsers() {
		String sql = "select * from  t_user";
		List<User> list = this.jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class));
		return list;
	}
}
           

6.3 Service與service的實作類

UserService.java

package com.service;

import java.util.List;

import com.entry.User;

public interface UserService {
	public List<User> getUsers();
}
           

UserServiceImpl.java

package com.serviceImpl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.dao.UserDao;
import com.entry.User;
import com.service.UserService;

@Service
public class UserServiceImpl implements UserService{
	@Resource
	private UserDao userDao;
	@Override
	public List<User> getUsers() {
		return userDao.getUsers();
	}

}
           

6.4controller

UserController.java

package com.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.entry.User;
import com.service.UserService;

@Controller
public class UserController {
	@Resource
	private UserService userService;

	// tologin
	@RequestMapping("/login")
	public String login() throws Exception {

		return "login1";

	}

	// 登陸
	@RequestMapping(value = "/loginsubmit", method = { RequestMethod.POST })
	public String login(HttpSession session, Model model, String loginname,
			String loginpass) throws Exception {
		// 調用service進行使用者身份驗證
		List<User> list = userService.getUsers();

		int size = list.size();
		if (size == 0) {
			model.addAttribute("msg", "使用者不存在");
			return "fail";
		}
		String name = list.get(0).getU_name();
		String pass = list.get(0).getU_pwd();
		if (name.equals(loginname) && pass.equals(loginpass)) {
			// 在session中儲存使用者身份資訊
			session.setAttribute("admin", loginname);
			return "success";
		}
		model.addAttribute("msg", "密碼錯誤");
		return "fail";

	}

}
           

6.5 至此java部分代碼已完成,為什麼dao層可以操作資料庫,spring是如何起作用的?

重點就在以下兩個配置檔案。

data.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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms"
	xmlns: xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
		http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
	<context:property-placeholder location="classpath:jdbc.properties"/> 
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	<!-- 連接配接池中的conn數量的控制 -->
		<property name="maxActive" value="50"></property>
		<property name="minIdle" value="5"></property>
		<property name="initialSize"  value="10"></property>
		<property name="maxWait" value="5000"></property>
		<property name="maxIdle" value="10"></property>
	</bean>
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<tx:advice id="myAdvice" transaction-manager="transactionManager">
		<tx:attributes>
		<!-- 給get開頭的方法配置事務,不是必須有 -->
			<tx:method name="get*" propagation="SUPPORTS"  read-only="true"/>
			
		</tx:attributes>
	</tx:advice>
	<aop:config>
	<!-- 定義攔截切口 -->
		<aop:pointcut id="curd"  expression="execution (* com.service..*.*(..))"/>
		<aop:advisor advice-ref="myAdvice" pointcut-ref="curd"/>
	</aop:config>
	
	
</beans>
           

dispatcher-servlet.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:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:jms="http://www.springframework.org/schema/jms" xmlns:
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
		http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

	<!-- 預設的注解映射的支援 -->
	<mvc:annotation-driven />
	<!-- 自動掃描的包名 -->
	<context:component-scan base-package="com.*" />
	<!-- 視圖解析器 解析jsp解析,預設使用jstl标簽,classpath下的得有jstl的包 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置jsp路徑的字首 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!-- 配置jsp路徑的字尾 -->
		<property name="suffix" value=".jsp" />
	</bean>

</beans>
           

6.6頁面部分

login1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>登入</title>
<link rel="stylesheet"
	href="${pageContext.request.contextPath }/css/style1.css" target="_blank" rel="external nofollow" 
	type="text/css"></link>
<script type="text/javascript"
	src="<c:url value='/js/jquery-1.5.1.js'/>"></script>
<script type="text/javascript" src="<c:url value='/js/common.js'/>"></script>
</head>
<body>
	<div>
		<div id="divTitle">
			<span id="spanTitle"> 歡迎登陸 </span>
		</div>
		<div id="divBody">
			<form action="${pageContext.request.contextPath }/loginsubmit.action" method="post"
				id="loginForm">
				<div class="div1">
					<label class="lableshow">使用者名</label> <input class="inputClass"
						type="text" name="loginname" id="loginname"
						value="${form.loginname }" /> <label class="errorClass"
						id="loginnameError">${errors.loginname }</label>
				</div>
				<div class="div1">
					<label class="lableshow">密   碼</label> <input
						class="inputClass" type="password" name="loginpass" id="loginpass"
						value="${form.loginpass }" />
						<label class="errorClass"
						id="loginpassError">${errors.loginpass }</label>
				</div>
				<div class="div1">
					<div style="float: left; margin-right: 71px">
						<input style="width: 100px; height: 33px" type="image"
							src="${pageContext.request.contextPath }/images/login_btn.png"
							id="loginBtn" οnclick="this.form.submit()"  />
					</div>
					<div>
						<input style="width: 100px; height: 33px" type="image"
							src="${pageContext.request.contextPath }/images/reset.jpg"
							id="restBtn" />
					</div>
				</div>
			</form>
		</div>
	</div>

</body>
</html>
           

fail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>
</head>
<body>
<font color="red" size="30px">${msg }</font>

</body>
</html>
           

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>
</head>
<body>

<font  size="30px">使用者:${admin}   登陸成功 </font>


</body>
</html>
           

style.css

#divTitle {
	margin: auto;
	height: 100px;
	margin-top: 30px;
	padding-top: 30px;
	background-color: #a3bfe9;
	margin-bottom: 10px;
}

#spanTitle {
	margin-left: 39%;
	font-size: 40px;
	font-style: italic;
	font-weight: 900;
}

.div1 {
	padding-left: 30%;
	margin-bottom: 20px;
	height: 43px;
}
.lableshow{
	margin-right: 100px;
}
input{
	height: 33px;
	width: 200px;
}
           

common.jsp

$(function() {
	/*
	 * 重置功能
	 */
	$("#restBtn").click(function() {
		//alert("11");
		$("#loginname").val("");
		$("#loginpass").val("");
		return;
	});

	/*
	 * 輸入框失去焦點進行校驗
	 */
	$(".inputClass").blur(
			function() {
				var id = $(this).attr("id");
				// alert(id+"**");
				var funName = "validate" + id.substring(0, 1).toUpperCase()
						+ id.substring(1) + "()";
				eval(funName);
			});
	/*
	 * 輸入框得到焦點隐藏錯誤資訊
	 */
	$(".inputClass").focus(function() {
		var labelId = $(this).attr("id") + "Error";
		$("#" + labelId).text("");
		showError($("#" + labelId));
	});

	/*
	 * 表單送出時進行校驗
	 */
	$("#loginForm").submit(function() {
		var bool = true;// 表示校驗通過
		if (!validateLoginname()) {
			bool = false;
		}
		if (!validateLoginpass()) {
			bool = false;
		}
		return bool;
	});

});

/*
 * 登入名校驗方法
 */
function validateLoginname() {
	var id = "loginname";
	var value = $("#" + id).val();
	// alert(value);
	/*
	 * 1. 非空校驗
	 */
	if (!value) {

		$("#" + id + "Error").text("使用者名不能為空!");
		showError($("#" + id + "Error"));
		return false;
	}
	/*
	 * 2. 長度校驗
	 */
	if (value.length < 2 || value.length > 20) {
		$("#" + id + "Error").text("使用者名長度必須在2 ~ 20之間!");
		showError($("#" + id + "Error"));
		false;
	}
	
	});
	return true;
}
/*
 * 校驗密碼
 */
function validateLoginpass() {
	// alert("**");
	var id = "loginpass";
	var value = $("#" + id).val();
	/*
	 * 1. 非空校驗
	 */
	if (!value) {
		$("#" + id + "Error").text("密碼不能為空!");
		showError($("#" + id + "Error"));
		return false;
	}

}

/*
 * 判斷目前元素是否存在内容,如果存在顯示,不頁面不顯示!
 */
function showError(ele) {
	var text = ele.text();
	if (!text) {
		ele.css("display", "none");
	} else {
		ele.css("display", "");
	}
}
           

最後,不要忘記啊加入

Spring的jdbcTemplate完成登入使用者登入功能

至此,登入功能完成,運作。。。。

Spring的jdbcTemplate完成登入使用者登入功能
Spring的jdbcTemplate完成登入使用者登入功能
Spring的jdbcTemplate完成登入使用者登入功能