Intellij IDEA 構建Spring Web項目 — 用戶登陸功能

相關軟件:
一、Intellij IDEA14: http://pan.baidu.com/s/1nu16VyD
三、Tomcat(apache-tomcat-6.0.43): http://pan.baidu.com/s/1kUwReQF
四、MySQL(mysql-essential-5.1.68-winx64):http://pan.baidu.com/s/1gdZZgMB
五、Spring 3.x :  http://pan.baidu.com/s/1o7i8daM
6:相關Lib打包:http://pan.baidu.com/s/1slSmWqx
 
案例來自於《Spring 3.X 企業應用開發實戰》 Chapter2 :  http://pan.baidu.com/s/1qWXEE3E
 
一、建立一個普通的Java Web項目
Intellij IDEA建立一個普通的Java Web項目可參考: http://www.cnblogs.com/yangyquin/p/5285272.html
項目名稱爲:SpringProject,Module名稱爲SpringCh2LoginModule。
二、手動建立如下目錄
在Module下先建立一個文件夾爲test,與src同級,而後右鍵,選擇Mark Directory As,再選擇Test Sources Root便可。  
三、導入相關的jar包
我把Spring開發要用到的jar包都弄成一個文件夾了,把裏面全部的jar包複製而後黏貼到項目裏面的lib目錄下便可。
四、配置項目結構
打開Project Structure(Ctrl+Alt+Shift+S),選擇Modules,選擇Paths,選擇Use module compile output path,兩個都選擇爲剛剛建立的classes文件夾。
接着看一下Modules下的Dependencies是否已經加入lib文件夾,若是沒有,點擊右邊的「+」號,選擇「Jars or Directories 」,選擇剛剛建立的lib文件夾。若是已經加入則提個勾,表示選中。最後OK便可。
五、建立庫表
個人數據庫用戶名爲root,密碼爲123456。
建立庫表的SQL語句可參見:\chapter2\schema。
建立數據庫sampledb:
建立表t_user:
 
 建立表t_login_log:
 
插入數據:
 
 
六、構建主體層
用戶領域對象:User
package com.yyq.domain;
import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private int userId;
    private String userName;
    private String password;
    private int credits;
    private String lastIp;
    private Date lastVisit;
    public User() {
    }
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    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 int getCredits() {
        return credits;
    }
    public void setCredits(int credits) {
        this.credits = credits;
    }
    public String getLastIp() {
        return lastIp;
    }
    public void setLastIp(String lastIp) {
        this.lastIp = lastIp;
    }
    public Date getLastVisit() {
        return lastVisit;
    }
    public void setLastVisit(Date lastVisit) {
        this.lastVisit = lastVisit;
    }
}

登陸日誌領域對象:LoginLog.javahtml

package com.yyq.domain;
import java.io.Serializable;
import java.util.Date;

public class LoginLog implements Serializable {
    private int loginLogId;
    private int userId;
    private String ip;
    private Date loginDate;
    public LoginLog() {
    }
    public int getLoginLogId() {
        return loginLogId;
    }
    public void setLoginLogId(int loginLogId) {
        this.loginLogId = loginLogId;
    }
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getIp() {
        return ip;
    }
    public void setIp(String ip) {
        this.ip = ip;
    }
    public Date getLoginDate() {
        return loginDate;
    }
    public void setLoginDate(Date loginDate) {
        this.loginDate = loginDate;
    }
}

七、構建持久層java

UserDao:
package com.yyq.dao;
import com.yyq.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public UserDao() {
        System.out.println("UserDao");
    }
    public int getMatchCount(String userName, String password) {
        String sqlStr = "select count(*) from t_user where user_name = ? and password = ?";
        return jdbcTemplate.queryForInt(sqlStr, new Object[]{userName, password});
    }
    public User findUserByUserName(final String userName) {
        String sqlStr = " SELECT user_id,user_name,credits "
                + " FROM t_user WHERE user_name =? ";
        final User user = new User();
        jdbcTemplate.query(sqlStr, new Object[]{userName},
                new RowCallbackHandler() {
                    public void processRow(ResultSet rs) throws SQLException {
                        user.setUserId(rs.getInt("user_id"));
                        user.setUserName(userName);
                        user.setCredits(rs.getInt("credits"));
                    }
                });
        return user;
    }
    public void updateLoginInfo(User user) {
        String sqlStr = " UPDATE t_user SET last_visit=?,last_ip=?,credits=? "
                + " WHERE user_id =?";
        jdbcTemplate.update(sqlStr, new Object[]{user.getLastVisit(),
                user.getLastIp(), user.getCredits(), user.getUserId()});
    }
}

LoginLogDao:mysql

package com.yyq.dao;
import com.yyq.domain.LoginLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class LoginLogDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void insertLoginLog(LoginLog loginLog) {
        String sqlStr = "INSERT INTO t_login_log(user_id,ip,login_datetime) "
                + "VALUES(?,?,?)";
        Object[] args = {loginLog.getUserId(), loginLog.getIp(),
                loginLog.getLoginDate()};
        jdbcTemplate.update(sqlStr, args);
    }
}

八、業務層web

package com.yyq.service;
import com.yyq.dao.LoginLogDao;
import com.yyq.dao.UserDao;
import com.yyq.domain.LoginLog;
import com.yyq.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private LoginLogDao loginLogDao;
    public boolean hasMatchUser(String userName, String password){
        int matchCount = userDao.getMatchCount(userName,password);
        return matchCount > 0;
    }
    public User findUserByUserName(String userName) {
        return userDao.findUserByUserName(userName);
    }
    public void loginSuccess(User user) {
        user.setCredits( 5 + user.getCredits());
        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(user.getUserId());
        loginLog.setIp(user.getLastIp());
        loginLog.setLoginDate(user.getLastVisit());
        userDao.updateLoginInfo(user);
        loginLogDao.insertLoginLog(loginLog);
    }
}
九、配置applicationContext.xml文件
在src目錄下建立一個applicationContext.xml文件,點中src,右鍵,選擇New -> File  ->輸入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:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <context:component-scan base-package="com.yyq.dao"/>
    <context:component-scan base-package="com.yyq.service"/>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close"
          p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/sampledb"
          p:username="root"
          p:password="123456"/>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
          p:dataSource-ref="dataSource"/>
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>
    
    <aop:config proxy-target-class="true">
        <aop:pointcut id="serviceMethod" expression="execution( * com.yyq.service..*(..))"/>
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
            
</beans>

十、編寫單元測試spring

這裏使用Junit4編寫單元測試,在test文件夾下建立類com.yyq.TestUserService。
package com.yyq;
import com.yyq.domain.User;
import com.yyq.service.UserService;
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 java.util.Date;
import static org.junit.Assert.*;
/**
 * Created by gao on 16-4-28.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
public class TestUserService {
    @Autowired
    private UserService userService;
    @Test
    public void hasMatchUser(){
        boolean b1 = userService.hasMatchUser("admin","123456");
        boolean b2 = userService.hasMatchUser("admin","1111");
        assertTrue(b1);
        assertTrue(!b2);
    }
    @Test
    public void testFindUserByUserName() {
        User user = userService.findUserByUserName("admin");
        assertEquals(user.getUserName(), "admin");
    }
    @Test
    public void testAddLoginLog() {
        User user = userService.findUserByUserName("admin");
        user.setUserId(1);
        user.setUserName("admin");
        user.setLastIp("192.168.12.7");
        user.setLastVisit(new Date());
        userService.loginSuccess(user);
    }
}

十一、運行測試用例sql

把鼠標放在某個測試方法,好比hasMatchUser()方法,右鍵,選擇Run 'hasMatchUser()',便可運行特定的方法。固然,也能夠把鼠標放在類名那裏,右鍵,選擇「TestUserService」,即將類裏面的全部方法都運行一遍。
 
看到」All Tests Passed「,表示所有經過啦~~~
 
十二、控制層
在src目錄下建立包com.yyq.service,在該包下建立類LoginCommand和類LoginController。
LoginCommand:
package com.yyq.controller;

/**
 * Created by gao on 16-4-28.
 */
public class LoginCommand {
    private String userName;
    private String password;

    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;
    }
}

LoginController:數據庫

package com.yyq.controller;

import com.yyq.domain.User;
import com.yyq.service.UserService;
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 javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/index.html")
    public String loginPage(){
        return "login";
    }
    @RequestMapping(value = "/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request,LoginCommand loginCommand){
        boolean isValidUser =
                userService.hasMatchUser(loginCommand.getUserName(),
                        loginCommand.getPassword());
        if (!isValidUser) {
            return new ModelAndView("login", "error", "用戶名或密碼錯誤。");
        } else {
            User user = userService.findUserByUserName(loginCommand
                    .getUserName());
            user.setLastIp(request.getLocalAddr());
            user.setLastVisit(new Date());
            userService.loginSuccess(user);
            request.getSession().setAttribute("user", user);
            return new ModelAndView("main");
        }
    }
}

1三、編寫JSP視圖頁面express

login.jsp:apache

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>寶寶淘論壇登陸</title>
</head>
<body>
<c:if test="${!empty error}">
    <font color="red"><c:out value="${error}" /></font>
</c:if>
<form action="<c:url value="/loginCheck.html"/>" method="post">
    用戶名:
    <input type="text" name="userName">
    <br>
    密 碼:
    <input type="password" name="password">
    <br>
    <input type="submit" value="登陸" />
    <input type="reset" value="重置" />
</form>
</body>
</html>

main.jsp:tomcat

<%--
  Created by IntelliJ IDEA.
  User: gao
  Date: 16-3-17
  Time: 下午8:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>寶寶淘論壇</title>
</head>
<body>
${user.userName},歡迎您進入寶寶淘論壇,您當前積分爲${user.credits};
</body>
</html>
1四、配置Spring MVC框架
1)修改web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>baobaotao</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>baobaotao</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

2)在WEB-INF下建立一個文件baobaotao-servlet.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 掃描web包,應用Spring的註解 -->
    <context:component-scan base-package="com.yyq.controller"/>
    <!-- 配置視圖解析器,將ModelAndView及字符串解析爲具體的頁面 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:viewClass="org.springframework.web.servlet.view.JstlView"
          p:prefix="/"
          p:suffix=".jsp"/>
</beans>

 

1五、配置Tomcat容器,運行程序

Run -> Edit Configuration -> Run/Debug Configurations -> 點擊"+"號 -> 選擇Tomcat -> 選擇Local -> 點擊Deployment -> 點擊「+」 號 -> 選擇SpringCh2LoginModule:war exploded->OK
界面顯示:
用戶名:admin,密碼:123456

 

登陸成功進入主界面。

1六、項目結構圖
相關文章
相關標籤/搜索