Spring4+SpringMVC+MyBatis登录注册详细
项目结构:
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>
我们有两个方法来进行软件设计:一个是让其足够的简单以至于让BUG无法藏身;另一个就是让其足够的复杂,让人找不到BUG。前者更难一些。