SpringMVC验证用户登录信息代码

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">    
    <title>标题</title>        
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">    
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
 </head>
 <body>
 	十分对不起,登录失败,由于:<%=request.getAttribute("msg") %>
 </body>
</html>


login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">    
    <title>标题</title>        
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">    
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
 </head>
 <body>
 	<form action="login.do" method="post">
		用户名:<input type="text" name="username"/><br>
		密码:<input type="text" name="password"/><br>
		<input type=submit value="登录"/>
	</form>
 </body>
</html>


success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">    
    <title>标题</title>        
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">    
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
 </head>
 <body>
 	恭喜:<%=request.getAttribute("username") %>,登录成功
 </body>
</html>


web.xml

<?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_3_0.xsd" 
		 id="WebApp_ID" version="3.0">
  <!-- 这里配置spring 的后台servlet-->
  <servlet>
  	<servlet-name>DispatcherServlet</servlet-name>
  	<servlet-class>
  		org.springframework.web.servlet.DispatcherServlet
  	</servlet-class>
  	
  	<!-- 指定spring配置文件的路径-->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>/WEB-INF/applicationContext.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>DispatcherServlet</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  <display-name>
  </display-name>
  <welcome-file-list>
  	<welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>


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"
	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">
	
	<bean id="urlMapping"
		class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="login.do">login</prop>
			</props>
		</property>
	</bean>
	
	<bean id="login" class="com.spring.controller.LoginController">
		<property name="errorPage">
			<value>error.jsp</value>
		</property>
		<property name="successPage">
			<value>success.jsp</value>
		</property>
	</bean>
</beans>


LoginController

package com.spring.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.spring.model.UserInfoBean;

public class LoginController implements Controller
{
	private String successPage;
	private String errorPage;
	
	
	public String getSuccessPage() 
	{
		return successPage;
	}


	public void setSuccessPage(String successPage) 
	{
		this.successPage = successPage;
	}


	public String getErrorPage() 
	{
		return errorPage;
	}


	public void setErrorPage(String errorPage) 
	{
		this.errorPage = errorPage;
	}


	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception 
	{
		// TODO Auto-generated method stub
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String message = null;
		
		if(username == null || password == null || 
				username.trim().equals("") || password.trim().equals(""))
		{
			message = "用户名或密码为空";
			Map<String, String> model = new HashMap<String,String>();
			model.put("msg", message);
			return new ModelAndView(getErrorPage(),model);
			
		}
		
		if(!UserInfoBean.exisitUser(username))
		{
			message = username + "不存在";
			Map<String, String>model = new HashMap<String, String>();
			model.put("msg", message);
			return new ModelAndView(getErrorPage(),model);
		}
		
		if(!UserInfoBean.confirmPassword(username, password))
		{
			message = username + "密码不正确";
			Map<String, String> model = new HashMap<String, String>();
			model.put("msg", message);
			
			return new ModelAndView(getErrorPage(),model);
		}
		else
		{
			Map<String, String>model = new HashMap<String, String>();
			model.put("username", username);
			return new ModelAndView(getSuccessPage(),model);
		}
		
	}

}


 


UserInfoBean

package com.spring.model;

import java.util.HashMap;
import java.util.Map;

public class UserInfoBean 
{
	private static Map<String,String>userinfo = new HashMap<String, String>();
	static
	{
		String numberOneUser = "zhangsan";
		String numberOnePassword = "123";
		
		String numberTwoUser = "lisi";
		String numberTwoPassword = "456";
		
		userinfo.put(numberTwoUser, numberTwoPassword);
		userinfo.put(numberOneUser, numberOnePassword);
	}
	public static boolean exisitUser(String username)
	{
		return userinfo.containsKey(username);
	}
	
	public static boolean confirmPassword(String username,String password)
	{
		return userinfo.get(username).equals(password);
	}
	
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以!下面是一个简单的示例代码,演示了如何使用Spring MVC和MySQL进行登录查询: 首先,您需要在项目的pom.xml文件中添加Spring MVC和MySQL的依赖: ```xml <dependencies> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.8</version> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> </dependencies> ``` 接下来,创建一个UserController类来处理用户相关的请求: ```java import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.sql.*; @Controller public class UserController { // 数据库连接配置 private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase"; private static final String DB_USER = "root"; private static final String DB_PASSWORD = "password"; @GetMapping("/login") public String showLoginForm() { return "login"; } @PostMapping("/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) { try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) { // 创建查询语句 String query = "SELECT * FROM users WHERE username = ? AND password = ?"; PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, username); statement.setString(2, password); // 执行查询 ResultSet resultSet = statement.executeQuery(); // 判断是否有匹配的用户 if (resultSet.next()) { model.addAttribute("message", "登录成功!"); return "success"; } else { model.addAttribute("message", "用户名或密码错误!"); return "login"; } } catch (SQLException e) { e.printStackTrace(); model.addAttribute("message", "数据库连接错误!"); return "login"; } } } ``` 在上述代码中,我们首先在`showLoginForm()`方法中返回登录页面的视图名(例如login.jsp),并在`login()`方法中处理用户提交的登录表单。我们使用预编译的SQL语句来防止SQL注入,并通过执行查询语句来验证用户名和密码。 最后,您需要创建一个登录页面(例如login.jsp),让用户输入用户名和密码。根据上述代码中的视图名,您可以在WEB-INF目录下创建一个名为"login.jsp"的文件,并添加相应的登录表单。 这只是一个简单的示例,供您参考。实际项目中,您可能需要添加更多的逻辑和安全性措施。希望对您有所帮助!如果您有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值