一、準備所需的jar包 1.1所需jar包 1.Spring框架jar包 2.Mybatis框架jar包 3.Spring的AOP事務jar包 4.Mybatis整合Spring中間件jar包 5.aspectj框架jar包 6.aop聯盟jar包 7.資料庫驅動jar包 8.數據源c3p0所需ja ...
一、準備所需的jar包
1.1所需jar包
1.Spring框架jar包
2.Mybatis框架jar包
3.Spring的AOP事務jar包
4.Mybatis整合Spring中間件jar包
5.aspectj框架jar包
6.aop聯盟jar包
7.資料庫驅動jar包
8.數據源c3p0所需jar包
9.JSTL標簽庫jar包
如圖
共45個jar包放入lib目錄下。然後Build Path→Add to Build Path
二、準備資料庫資源
2.1在smmbook資料庫中創建表user
插入數據:
三、完成配置文件
3.1 編寫db.properties文件
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/smmbook
dataSource.user=root
dataSource.password=
dataSource.maxPoolSize=20
dataSource.maxIdleTime = 1000
dataSource.minPoolSize=6
dataSource.initialPoolSize=5
3.2編寫applicationContext.xml
<?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會將codeRose.mapper包里的所有介面當作mapper配置,之後可以自動引入mapper類--> <mybatis:scan base-package="codeRose.mapper"/> <!-- 掃描codeRose包下麵的java文件,有Spring的相關註解的類,則把這些類註冊為Spring的bean --> <context:component-scan base-package="codeRose"/> <!-- 使用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>
3.3編寫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="codeRose.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/content/</value> </property> <!-- 尾碼 --> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
3.4編寫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>
四、MVC模塊解析
controller為控制層,主要用於對業務模塊的流程式控制制。
domain為實體層,存放實體類。
mapper層為數據接入層,主要用於與資料庫進行連接,訪問資料庫進行操作,這裡定義了各種操作資料庫的介面。
service層為業務層, 我們的各種業務都定義在此,由controller調用不同業務實現不同的操作。
五、持久層功能實現
User.java
package codeRose.domain; public class User { private Integer id; private String loginname; private String password; private String username; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
UserMapper.java
package codeRose.mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import codeRose.domain.User; //持久層包括資料庫表映射的User.java的JavaBean對象,並使用了MyBatis的註解映射了對應的SQL語句 public interface UserMapper { @Select("select * from user where loginname=#{loginname} and password=#{password}") User findWithLoginAndPassword(@Param("loginname")String loginname,@Param("password")String password); }
六、服務層功能實現
UserService.java
package codeRose.service; import codeRose.domain.User; public interface UserService { /** * 判斷用戶登錄 * @param String loginname * @param String password * @return 找到返回User對象,沒有找到返回null * */ User login(String loginname,String password); }
UserServiceImpl.java
package codeRose.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import codeRose.domain.User; import codeRose.mapper.UserMapper; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User login(String loginname, String password) { // TODO Auto-generated method stub return userMapper.findWithLoginAndPassword(loginname, password); } }
七、控制層功能實現
FormController.java
package codeRose.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; } }
UserController.java
package codeRose.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.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import codeRose.domain.User; import codeRose.service.UserService; @Controller public class UserController { @Autowired @Qualifier("userService") private UserService userService; /** * 處理/login請求 */ @RequestMapping(value="/login") public ModelAndView login(String loginname,String password,ModelAndView mv,HttpSession session){ User user=userService.login(loginname, password); if(user!=null){ //登錄成功,將user對象設置到HttpSession作用範圍域中 session.setAttribute("user", user); //轉發到main請求 mv.setView(new RedirectView("/smmbookapp/main")); }else { //登錄失敗,設置失敗信息,並調轉到登錄頁面 mv.addObject("message","登錄名和密碼錯誤,請重新輸入"); mv.setViewName("loginForm"); } return mv; } }
八、JSP頁面實現
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"> <link href="css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"> <link href="css/templatemo_style.css" rel="stylesheet" type="text/css"> </head> <body class="templatemo-bg-gray"> <div class="container"> <div class="col-md-12"> <h1 class="margin-bottom-15">ssmbookapp</h1> <font color="red">${requestScope.message }</font> <form class="form-horizontal templatemo-container templatemo-login-form-1 margin-bottom-30" role="form" action="login" method="post"> <div class="form-group"> <div class="col-xs-12"> <div class="control-wrapper"> <label for="username" class="control-label fa-label"><i class="fa fa-user fa-medium"></i></label> <input type="text" class="form-control" id="loginname" placeholder="管理員用戶名" name="loginname"> </div> </div> </div> <div class="form-group"> <div class="col-md-12"> <div class="control-wrapper"> <label for="password" class="control-label fa-label"><i class="fa fa-lock fa-medium"></i></label> <input type="password" class="form-control" id="password" placeholder="登錄密碼" name="password"> </div> </div> </div> <div class="form-group"> <div class="col-md-12"> <div class="control-wrapper"> <input type="submit" value="Log in" class="btn btn-info"> </div> </div> </div> <hr> </form> </div> </div> </body> </html>
登錄成功跳轉到主頁main.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> 歡迎[${sessionScope.user.username }]訪問 </body> </html>