程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 學習《Spring 3.x 企業應用開發實戰》Day-1,spring企業開發實戰

學習《Spring 3.x 企業應用開發實戰》Day-1,spring企業開發實戰

編輯:JAVA綜合教程

學習《Spring 3.x 企業應用開發實戰》Day-1,spring企業開發實戰


Day-1 記錄自己學習spring的筆記

提要:根據《Spring 3.x 企業應用開發實戰》開頭一個用戶登錄的例子,按照上面敲的。

1.項目分層

 

dao:持久層

domain:領域對象(個人理解為數據表映射成一個Java類)

service:業務層

web:展現層

2.構建數據表

 2.1 數據庫采用MySql 5.x 版本

 2.2 建立兩個數據表 user 和 user_log 表 user 用來存放用戶信息,user_log用來存放user登錄信息

 2.3 user:

   

     user_log:

   

3.編寫UserDao、LoginLogDao類

    3.1 UserDao

    

 1 package com.zwy.dao;
 2 
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.jdbc.core.JdbcTemplate;
 8 import org.springframework.jdbc.core.RowCallbackHandler;
 9 import org.springframework.stereotype.Repository;
10 
11 import com.zwy.domain.User;
12 
13 /**
14  * 通過@Repository注解定義一個DAO
15  * */
16 @Repository
17 public class UserDao {
18     @Autowired//自動注入JdbcTemplate
19     private JdbcTemplate jdbcTemplate;
20     
21     /**
22      * 查詢用戶是否存在
23      * */
24     public int getMacthCount(String username,String password){
25         String sql="SELECT COUNT(*) FROM user WHERE user_name=? and password=? ";
26         return jdbcTemplate.queryForInt(sql, username,password);
27     }
28     /**
29      * 根據username找到相應的user 記錄(對象)
30      * */
31     public User findUserByUserName(final String username){
32         String sql="SELECT id,user_name,credits FROM user WHERE user_name=?";
33         final User user=new User();
34         jdbcTemplate.query(sql, new Object[]{username}, new RowCallbackHandler() {
35                     public void processRow(ResultSet reSet) throws SQLException {
36                         user.setId(reSet.getInt("id"));
37                         user.setUserName(reSet.getString("user_name"));
38                         user.setCredits(reSet.getInt("credits"));
39                     }
40         });
41         return user;
42     }
43     /**
44      * 根據useid更新相應的user (對象)在數據庫中的記錄
45      * 更新積分,登錄IP,登錄時間
46      * */
47     public void updateLoginInfo(User user){
48         String sql="UPDATE user  SET      credits=?,last_ip=?,last_time=?"
49             +"  WHERE id=?";
50         jdbcTemplate.update(sql, user.getCredits(),user.getLastIp(),user.getLastTime(),user.getId());
51     }
52 }

  3.2 LoginLogDao類

package com.zwy.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;


import com.zwy.domain.UserLog;

@Repository
public class LoginLogDao {
    @Autowired    
    private JdbcTemplate jdbcTemplate;
    
    /**
     * 插入一條登錄記錄
     * */
    public void insertLoginLog(UserLog user){
        String sql="INSERT INTO user_log(user_id,ip,log_time)"
            +" VALUES (?,?,?)";
        jdbcTemplate.update(sql,user.getUserId(),user.getIp(),user.getLogTime());
    }
}

  省略了domain 實體類的代碼

4.業務層UserService的代碼

  通過業務層組織持久化層的DAO完成業務邏輯操作

package com.zwy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zwy.dao.LoginLogDao;
import com.zwy.dao.UserDao;
import com.zwy.domain.User;
import com.zwy.domain.UserLog;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private LoginLogDao loginLogDao;
    /**
     * 登錄業務
     * */
    public boolean userLogin(String username,String password){
        int count=userDao.getMacthCount(username, password);
        return count>0;
    }
    /**
     * 根據username找到User對象
     * */
    public User finUserByUserName(String username){
        User user=userDao.findUserByUserName(username);
        return user;
    }
    /**
     * 成功登錄,更新user的積分並添加到user_log
     * */
    public void successLoginLog(User user){
        if(user!=null){
            user.setCredits(5+user.getCredits());
            UserLog userLog=new UserLog();
            userLog.setUserId(user.getId());
            userLog.setIp(user.getLastIp());
            userLog.setLogTime(user.getLastTime());
            userDao.updateLoginInfo(user);
            loginLogDao.insertLoginLog(userLog);
        }
    }
}

5.配置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" 
 xmlns:aop="http://www.springframework.org/schema/aop" 
  xmlns:tx="http://www.springframework.org/schema/tx" 
 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 
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
 ">
         <!--1. 掃描類包,把標注spring注解的類自動轉化成bean,同時完成bean的注入 -->
        <context:component-scan base-package="com.zwy.dao"/>
        <context:component-scan base-package="com.zwy.service" />
        <!-- 2.定義一個使用DBCP的數據源 -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
            destroy-method="close"
            p:driverClassName="com.mysql.jdbc.Driver"
            p:url="jdbc:mysql://192.168.1.106:3306/spring"
            p:username="root"
            p:password="123456"
        />
        <!-- 3.定義Spring-JDBC模板bean-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource" />
        <!--4.配置事務管理器-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
            p:dataSource-ref="dataSource"
        />
        <!--5.配置AOP,讓service包下的方法處於增強事務中-->
        <aop:config proxy-target-class="true">
                <aop:pointcut expression=" execution(* com.zwy.service..*(..))" id="serviceMethod"/>
                <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
        </aop:config>
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                    <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
</beans>

6.在Junit4下測試Service的方法

package com.zwy.service;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.zwy.domain.User;

@RunWith(SpringJUnit4ClassRunner.class)//1.基於junit4的spring測試框架
@ContextConfiguration(locations={"/applicationContext.xml"})//2.啟動spring容器
public class TestService {

    @Autowired
    private UserService userService;
    
    @org.junit.Test
    public void userLogin(){
        boolean b1=userService.userLogin("admin", "123456");
        boolean b2=userService.userLogin("admin", "1111");
        System.out.println(b1+","+b2);
    }
    @org.junit.Test
    public void findUser(){
        User user=userService.finUserByUserName("admin");
        System.out.println(user);
    }
    @Test
    public void successLog(){
        User user=userService.finUserByUserName("admin");
        user.setLastIp("192.168.1.101");
        user.setLastTime(new Date());
        userService.successLoginLog(user);
    }
}

7.編寫Web層,用到SpringMVC框架

ModelAndView 是這個包下的org.springframework.web.servlet.ModelAndView;不要搞成其他包下相同名字的類

package com.zwy.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

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

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

//標注成為springMVC controller
@Controller
public class LoginController {
    
    @Autowired
    private UserService userService;
    //來自處理index.html
    @RequestMapping(value="/index.html")
    public String loginPage(){
        return "login";
    }
    //來自處理loginCheck.html的請求
    @RequestMapping(value="/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request,LoginCommod loginCommod){
        boolean isLogin=userService.userLogin(loginCommod.getUsername(), loginCommod.getPassword());
        if(isLogin){
            User user=userService.finUserByUserName(loginCommod.getUsername());
            user.setLastIp(request.getRemoteAddr());
            user.setLastTime(new Date());
            userService.successLoginLog(user);
            request.getSession().setAttribute("user", user);
            return new ModelAndView("main");
        }else {
            //參數1:邏輯視圖名 參數2:數據模型 ---參數3:數據對象  
            //request會以(數據模型,數據對象)的形勢返回。
            return new ModelAndView("login", "error", "用戶名或者密碼錯誤!");
        }
    }
    
}
 1 package com.zwy.web;
 2 //封裝了form表單提交的信息
 3 public class LoginCommod {
 4     private String username;
 5     private String password;
 6     public String getUsername() {
 7         return username;
 8     }
 9     public void setUsername(String username) {
10         this.username = username;
11     }
12     public String getPassword() {
13         return password;
14     }
15     public void setPassword(String password) {
16         this.password = password;
17     }
18     
19 }

8配置web.xml

web容器自動啟動Spring容器

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 3   <!--1. 從類路徑下加載spring配置文件,classpath關鍵字特指類路徑下加載 -->
 4   <context-param>
 5           <param-name>contextConfigLocation</param-name>
 6           <param-value>classpath:applicationContext.xml</param-value>
 7   </context-param>
 8     <!-- 2.負責啟動spring容器監聽器,它將引用1處的上下文參數獲得spring配置文件地址 -->
 9   <listener>
10               <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
11   </listener>
12   <!-- spring MVC主控制的servlet  -->
13   <servlet>
14                   <!-- spring MVC的配置文件的名字 serviletName-servlet.xml -->
15                   <servlet-name>zwy</servlet-name>
16                   <servlet-class>    org.springframework.web.servlet.DispatcherServlet</servlet-class>
17                   <!-- 
18                       1)load-on-startup元素標記容器是否在啟動的時候就加載這個servlet(實例化並調用其init()方法)。
19                       2)正數的值越小,該servlet的優先級越高,應用啟動時就越先加載。
20                   -->
21                   <load-on-startup>2</load-on-startup>
22   </servlet>
23   <!-- spring MVC處理的URL  -->
24   <servlet-mapping>
25                   <servlet-name>zwy</servlet-name>
26                 <url-pattern>*.html</url-pattern> 
27  </servlet-mapping>
28   <welcome-file-list>
29     <welcome-file>index.jsp</welcome-file>
30   </welcome-file-list>
31 </web-app>

9.配置zwy-servlet.xml

放在WEB-INF目錄下,放在src目錄下報錯

<?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 
 ">
 <!-- 1.掃描web包,應用Spring注解 -->
 <context:component-scan base-package="com.zwy.web" />
 <!-- 
     2.配置視圖解析器,將ModelAndView及字符串解析為具體的頁面
       prefix指定在視圖名所添加的前綴
       suffix指定在視圖名後添加的後綴
       InternalResourceViewResolver:通過在邏輯視圖名前後加後綴
  -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
         p:viewClass="org.springframework.web.servlet.view.JstlView"
         p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp"
 />
 </beans>

**注意 加入log4j日志框架,否則Spring框架會報錯

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