程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Spring4+SpringMVC+MyBatis登錄注冊詳細,spring4mybatis

Spring4+SpringMVC+MyBatis登錄注冊詳細,spring4mybatis

編輯:JAVA綜合教程

Spring4+SpringMVC+MyBatis登錄注冊詳細,spring4mybatis


項目結構:

package com.mstf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 動態頁面跳轉控制器
 */
@Controller
public class FormController {

	@RequestMapping(value = "/{formName}")
	public String loginForm(@PathVariable String formName) {
		// 動態跳轉頁面
		return formName;
	}

}

  

package com.mstf.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.mstf.domain.User;
import com.mstf.service.UserService;

/**
 * 處理用戶請求控制器
 */
@Controller
public class UserController {
	/**
	 * 自動注入UserService
	 */
	@Autowired
	@Qualifier("userService")
	private UserService userService;

	/**
	 * 處理/login請求
	 */
	@RequestMapping(value = "/login")
	public ModelAndView login(String username, String password, ModelAndView mv, HttpSession session) {
		// 根據登錄名和密碼查找用戶,判斷用戶登錄
		User user = userService.login(username, password);
		if (user != null) {
			// 登錄成功,將user對象設置到HttpSession作用范圍域
			session.setAttribute("user", user);
			// 轉發到main請求,轉發地址
			mv.setView(new RedirectView("/Demo4/index"));
		} else {
			// 登錄失敗,設置失敗提示信息,並跳轉到登錄頁面
			mv.addObject("message", "登錄名或密碼錯誤,請重新輸入!");
			mv.setViewName("loginForm");
		}
		return mv;
	}

	/**
	 * 處理/regeist請求
	 */
	@RequestMapping(value = "/regeist")
	public String regeist(@ModelAttribute("user") User user) {
		userService.regeist(user);
		return "success";
	}
}

  

package com.mstf.domain;

import java.io.Serializable;

public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	private int id;
	private String username;
	private String password;
	private String phone;
	private String email;

	public int getId() {
		return id;
	}

	public void setId(int 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 String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public User(int id, String username, String password, String phone, String email) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.phone = phone;
		this.email = email;
	}

	public User() {
		super();
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", phone=" + phone + ", email="
				+ email + "]";
	}
}

  

package com.mstf.mapper;

import org.apache.ibatis.annotations.Select;
import com.mstf.domain.User;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

/**
 * UserMapper接口
 */
public interface UserMapper {
	/**
	 * 根據登錄名和密碼查詢用戶
	 * 
	 * @param String
	 *            username
	 * @param String
	 *            password
	 * @return 找到返回User對象,沒有找到返回null
	 */
	@Select("select * from loginuser where username = #{username} and password = #{password}")
	User findWithLoginnameAndPassword(@Param("username") String username, @Param("password") String password);

	/**
	 * 注冊
	 */
	@Insert("insert into loginuser(username,`password`,phone,email) values(#{username},#{password},#{phone},#{email})")
	int regeist(@Param("username") String username, @Param("password") String password, @Param("phone") String phone,
			@Param("email") String email);
}

  

package com.mstf.service;

import com.mstf.domain.User;

/**
 * User服務層接口
 */
public interface UserService {
	/**
	 * 判斷用戶登錄
	 * 
	 * @param String
	 *            username
	 * @param String
	 *            password
	 * @return 找到返回User對象,沒有找到返回null
	 */
	User login(String username, String password);

	/**
	 * 用戶注冊 返回的是int
	 */
	int regeist(User user);
}

  

package com.mstf.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mstf.domain.User;
import com.mstf.mapper.UserMapper;
import com.mstf.service.UserService;

/**
 * User服務層接口實現類 @Service("userService")用於將當前類注釋為一個Spring的bean,名為userService
 */
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
@Service("userService")
public class UserServiceImpl implements UserService {
	/**
	 * 自動注入UserMapper
	 */
	@Autowired
	private UserMapper userMapper;

	/**
	 * UserService接口login方法實現
	 * 
	 * @see { UserService }
	 */
	@Transactional(readOnly = true)
	@Override
	public User login(String username, String password) {
		return userMapper.findWithLoginnameAndPassword(username, password);
	}

	/**
	 * UserService接口regeist方法實現
	 * 
	 * @see { UserService }
	 */
	@Override
	public int regeist(User user) {
		System.out.println(user);
		return userMapper.regeist(user.getUsername(), user.getPassword(), user.getPhone(), user.getEmail());
	}
}

  

dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/demo4
dataSource.user=root
dataSource.password=root
dataSource.maxPoolSize=20
dataSource.maxIdleTime = 1000
dataSource.minPoolSize=6
dataSource.initialPoolSize=5

  

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.fkit.mapper.UserMapper=DEBUG
log4j.logger.org.fkit.mapper.BookMapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  index.jsp

<%@ page language="java" import="java.util.*" 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">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>
	<h1>登錄成功</h1>
	帳號:${sessionScope.user.username } 密碼:${sessionScope.user.password }
</body>
</html>

  loginForm.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>
	<h3>登錄頁面</h3>
	<form action="login" method="post">
		<font color="red">${requestScope.message }</font>
		<table>
			<tr>
				<td><label>登錄名: </label></td>
				<td><input type="text" id="username" name="username" required="required" maxlength="16">
				</td>
			</tr>
			<tr>
				<td><label>密碼: </label></td>
				<td><input type="password" id="password" name="password" required="required" maxlength="16">
				</td>
			</tr>
			<tr>
				<td><input type="submit" value="登錄"></td>
				<td><a href="regeister">沒有帳號?立即注冊</a></td>
			</tr>
		</table>
	</form>
</body>
</html>

  REGEISTER.JSP

<%@ page language="java" import="java.util.*" 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>
	<h1>注冊頁面</h1>
	<form action="regeist" method="post">
		<table>
			<tr>
				<td>帳號: <input type="text" name="username" class="username" required="required" maxlength="16">
				</td>
			</tr>
			<tr>
				<td>密碼: <input type="password" name="password" class="password" required="required" maxlength="16">
				</td>
			</tr>
			<tr>
				<td>電話: <input type="text" name="phone" class="phone" maxlength="20">
				</td>
			</tr>
			<tr>
				<td>郵箱: <input type="text" name="email" class="email" maxlength="25">
				</td>
			</tr>
			<tr>
				<td><input type="submit" value="注冊"></td>
			</tr>
		</table>
	</form>
</body>
</html>

  SUCCESS.JSP

<%@ page language="java" import="java.util.*" 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">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>
	<h1>注冊成功</h1>
</body>
</html>

  applicationContext

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" 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"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
			            http://www.springframework.org/schema/context
			            http://www.springframework.org/schema/context/spring-context-4.2.xsd
			            http://www.springframework.org/schema/mvc
			            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
			            http://www.springframework.org/schema/tx
			            http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
			            http://mybatis.org/schema/mybatis-spring 
			            http://mybatis.org/schema/mybatis-spring.xsd ">

	<!-- mybatis:scan會將com.mstf.mapper包裡的所有接口當作mapper配置,之後可以自動引入mapper類 -->
	<mybatis:scan base-package="com.mstf.mapper" />

	<!-- 掃描org.fkit包下面的java文件,有Spring的相關注解的類,則把這些類注冊為Spring的bean -->
	<context:component-scan base-package="com.mstf" />

	<!-- 使用PropertyOverrideConfigurer後處理器加載數據源參數 -->
	<context:property-override location="classpath:db.properties" />

	<!-- 配置c3p0數據源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" />

	<!-- 配置SqlSessionFactory,org.mybatis.spring.SqlSessionFactoryBean是Mybatis社區開發用於整合Spring的bean -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:dataSource-ref="dataSource" />

	<!-- JDBC事務管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		p:dataSource-ref="dataSource" />

	<!-- 啟用支持annotation注解方式事務管理 -->
	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>

  springmvc-config

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	<!-- 自動掃描該包,SpringMVC會將包下用了@controller注解的類注冊為Spring的controller -->
	<context:component-scan base-package="com.mstf.controller" />
	<!-- 設置默認配置方案 -->
	<mvc:annotation-driven />
	<!-- 使用默認的Servlet來響應靜態文件 -->
	<mvc:default-servlet-handler />
	<!-- 視圖解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前綴 -->
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<!-- 後綴 -->
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

</beans>

  WEB.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
	http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
	id="WebApp_ID" version="3.1">
	
	<!-- 配置spring核心監聽器,默認會以 /WEB-INF/applicationContext.xml作為配置文件 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- contextConfigLocation參數用來指定Spring的配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext*.xml</param-value>
	</context-param>
	
	<!-- 定義Spring MVC的前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- 讓Spring MVC的前端控制器攔截所有請求 -->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 編碼過濾器 -->
  <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>
 </filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app>

  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved