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

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

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;

@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: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.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: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.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"
	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", "");
	}
}
最后,不要忘记啊加入

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
































































































































  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用Spring MVC和MySQL完成登录连接数据库,你可以按照以下步骤进行操作: 1. 创建一个实体类来封装用户数据。这个实体类可以包含用户名和密码等属性。\[2\] 2. 创建一个DAO类来处理数据库操作。在DAO类中,你可以使用JdbcTemplate来执行SQL语句。在登录验证的方法中,你可以使用queryForObject方法来查询数据库中是否存在匹配的用户名和密码。\[1\] 3. 在Spring MVC的配置文件中,配置数据源和JdbcTemplate。你可以使用Spring的注解来自动注入JdbcTemplate。\[1\] 4. 在控制器中,接收用户输入的用户名和密码,并调用DAO类中的验证方法来进行登录验证。如果验证通过,可以进行相应的操作,比如跳转到登录成功页面;如果验证失败,可以返回错误信息给用户。\[1\] 5. 在登录页面中,使用表单来接收用户输入的用户名和密码,并将其提交给控制器进行处理。\[3\] 通过以上步骤,你可以使用Spring MVC和MySQL完成登录连接数据库的功能。 #### 引用[.reference_title] - *1* *2* [Idea Maven SpringMVC+Mysql 登录](https://blog.csdn.net/ck784101777/article/details/82973011)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [SpringMVC与mysql进行登录验证](https://blog.csdn.net/weixin_26820341/article/details/113649302)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值