1. 程式人生 > >spring+springmvc+mybatis實現簡單使用者註冊和登入

spring+springmvc+mybatis實現簡單使用者註冊和登入

一.建立Dynamic Web Project 專案結構: 在這裡插入圖片描述 mysql建立: 在這裡插入圖片描述 二.程式碼

首先配置web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
					http://www.springmodules.org/schema/cache/springmodules-cache.xsd
					http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd" 
		 xmlns="http://java.sun.com/xml/ns/javaee"
		 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
		 id="WebApp_ID" version="2.5">
		 
	<display-name>mybatis06-spring-springmvc</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

<!-- 對spring的支援   -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:beans.xml</param-value>
  </context-param>
    	<!-- 過濾器 -->
  <filter> 
       <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> 
       <url-pattern>/*</url-pattern> 
   </filter-mapping> 
   
  	<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
  
<!-- 對springmvc的支援   -->
    <servlet>
  	<servlet-name >springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  	
  	<load-on-startup>1</load-on-startup>
  	<async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

提供spring支援的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:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <!-- 自動掃描 -->
    <context:component-scan base-package="com.java.dao"></context:component-scan>  
    <context:component-scan base-package="com.java.service"></context:component-scan>  
    <context:component-scan base-package="com.java.serviceimpl"></context:component-scan>
    
  <!--   配置mysql連線 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <context:property-placeholder location="classpath:/jdbc.properties"/>
    
   <!--  配置mybatis的SQLSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource"></property>
    	<!-- 自動掃描mappers.xml檔案 -->
    	<property name="mapperLocations" value="classpath:com/java/mappers/*.xml"></property>
    	<!-- mybatis配置檔案 -->
    	<property name="configLocation" value="classpath:mybatis-config.xml "></property>
    </bean>
	
	<!-- spring自動查詢其下的類 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.java.dao"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>  
	
</beans>

提供springmvc支援的springmvc.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:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
    	<!-- 使用註解的包,包括子集    --> 
	<context:component-scan base-package="com.java.controller"/>
	
		<!-- 檢視解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
	</bean>
	
</beans>

簡化包名的mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
		<!-- 對entity下的實體類起個別名,起到簡化的作用 -->
		<typeAliases>
			<package name="com.java.entity"></package>
		</typeAliases>
</configuration>

資料庫連線jdbc.properties:

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_student?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

在這裡插入圖片描述 User基礎類:

package com.java.entity;

public class User {

	private Integer id;
	private String userName;
	private String passWord;
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer 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;
	}
	public User(String userName, String passWord) {
		super();
		this.userName = userName;
		this.passWord = passWord;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", passWord=" + passWord + "]";
	}
}

UserDao:

package com.java.dao;

import com.java.entity.User;

public interface UserDao {
	public User login(User user);
	public User add(User user);
}

UserService:

package com.java.service;

import com.java.entity.User;
public interface UserService {
	public User login(User user);
	public User add(User user);
}

ServiceImpl:

package com.java.serviceimpl;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.java.dao.UserDao;
import com.java.entity.User;
import com.java.service.UserService;

@Service("userService")
public class ServiceImpl implements UserService{

	@Resource
	private UserDao userDao;
	public User login(User user) {
		// TODO Auto-generated method stub
		return userDao.login(user);
	}
	public User add(User user) {
		// TODO Auto-generated method stub
		return userDao.add(user);
	}
}

UserController:

package com.java.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.java.entity.User;
import com.java.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;
	
	@RequestMapping("/login")
	public String login(User user,HttpServletRequest request) {
		User resultUser=userService.login(user);
		System.out.println(resultUser);
		if(resultUser==null) {
			request.setAttribute("user", user);
			request.setAttribute("errorMsg", "使用者名稱或密碼錯誤!");
			return "index";
		}else {
			HttpSession session=request.getSession();
			session.setAttribute("currentUser", resultUser);
			return "welcome";
		}
	}
	
	@RequestMapping("/add")
	public String add(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		String username=request.getParameter("userName");
		String password=request.getParameter("passWord");
		User users=new User(username, password);
		userService.add(users);
		return "reback";
	}		
}

user.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  
<mapper namespace="com.java.dao.UserDao">
	
 	<resultMap type="com.java.entity.User" id="UserResult">
 		<id property="id" column="id"></id>
 		<result property="userName" column="userName"></result>
 		<result property="passWord" column="passWord"></result>
 	</resultMap>
 	
 	<select id="login" parameterType="com.java.entity.User" resultMap="UserResult">
 		select * from user where userName=#{userName} and passWord=#{passWord}
 	</select>
 	
 	<select id="add" parameterType="com.java.entity.User" resultMap="UserResult">
 		insert into user (userName,passWord) values(#{userName},#{passWord})
 	</select>
</mapper>  

index.jsp:

<%@ 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>使用者登入頁面</title>
</head>
<body>
<a href="add.jsp">註冊</a>&nbsp;<br/>
<form action="${pageContext.request.contextPath}/user/login.do" method="post">
	userName:<input type="text" name="userName" value="${userName}"/><br/>
	passWord:<input type="password" name="passWord" value="${passWord}"/><br/>
	<input type="submit" value="登入"/><br/>
	<font color="red">${errorMsg}</font>
</form>
</body>
</html>

add.jsp:

<%@ 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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
	userName:<input type="text" name="userName"/>
	passWord:<input type="password" name="passWord"><br/>
	<input type="submit" value="註冊" />
</form>
</body>
</html>

reback.jsp:

<%@ 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>登入成功</title>
<script>
	function fun(){
		alert("確認返回登入頁面");
/* 		location.href ="http://localhost:8080/mybatis06-spring-springmvc/index.jsp";
 */		
 		window.history.go(-2);
	}
	
</script>
</head>
<body>
<input type="button" value="註冊成功,返回登入頁面" onclick="fun()"/>

</body>
</html>

welcome.jsp:

<%@ 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>登入成功</title>
</head>
<body>
歡迎   ${currentUser.userName} 來到我們的世界!
</body>
</html>

jar包: 在這裡插入圖片描述 以上+standard.jar+spring全jar (怎麼這麼多,累死)

看到這的也是很執著了…