Spring的jdbcTemplate完成登录用户登录功能

来源:互联网 发布:淘宝怎么搜爱奇艺会员 编辑:程序博客网 时间:2024/06/07 22:08

小白起步,从零开始,力求详细。

1.创建一个webx项目


2.将以下jar包放入web-inf/lib目录(网上当的jar包,有冗余,)



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.建立目录的结构,个人习惯,喜欢把大致目录搞出来,往里边填东西。


5.建立数据库表,并插入数据,使用的oracle


6.至此,各个结构都出来了,让我们愉快的填充内容吧。

6.1创建实体类

(注意属性名称与数据库中相同,否则会报空指针)

package com.entry;import javax.persistence.Entity;@Entitypublic 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;@Repositorypublic class UserDaoImpl implements UserDao{@Resourceprivate 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;@Servicepublic class UserServiceImpl implements UserService{@Resourceprivate UserDao userDao;@Overridepublic 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;@Controllerpublic class UserController {@Resourceprivate 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:lang="http://www.springframework.org/schema/lang" 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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsdhttp://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://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:lang="http://www.springframework.org/schema/lang"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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsdhttp://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://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的包 --><beanclass="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"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> <inputclass="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" onclick="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", "");}}
最后,不要忘记啊加入

至此,登录功能完成,运行。。。。
































































































































0 0