基於IntelliJ IDEA開發工具搭建SSM框架並實現頁面登陸功能詳細講解二

接:css

接下來配置類html

UserControllerjava

package com.chatRotbot.controller;
import com.chatRotbot.model.User;
import com.chatRotbot.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
@Controller
public class UserController {
    private static Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    private IUserService userService;
    @RequestMapping("/gotoLogin")
    public String gotoLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(@RequestParam(value="loginName" ,required=true) String loginName,
                        String password, Model model, HttpSession session){
        logger.info("登錄用戶名:"+loginName);
        //用redirect和forward標籤返回
        //注意:用這兩個標籤必須寫全路徑,不適應視圖解析的邏輯視圖
        if(StringUtils.isNotEmpty(loginName)&&
                StringUtils.isNotEmpty(password)){
            User user = userService.loginUser(loginName, password);
            if(user!=null){
                logger.info("登錄成功");
                session.setAttribute("user", user);
                return "redirect:/main" ;
            }else{
                model.addAttribute("loginFlag","登錄失敗,請輸入正確的用戶名和密碼");
                return "forward:/WEB-INF/pages/login.jsp";
            }
        }else{
            model.addAttribute("loginFlag","登錄失敗,請輸入正確的用戶名和密碼");
            return "forward:/WEB-INF/pages/login.jsp";
        }
    }
    @RequestMapping("/main")
    public String main(){
        return "main/main";
    }

}
 
IUserService
package com.chatRotbot.service;
import com.chatRotbot.model.User;
public interface IUserService {
    /**
     * 登錄驗證
     * @param loginName
     * @param password
     * @return
     */
    public User loginUser(String loginName,String password);

}
UserServiceImpl
package com.chatRotbot.service.impl;
import com.chatRotbot.dao.mapper.UserMapper;
import com.chatRotbot.model.User;
import com.chatRotbot.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 登陸
     * @param loginName
     * @param password
     * @return
     */

    public User loginUser(String loginName, String password) {
        User user = new User();
       user.setUserName(loginName);
        List<User> userList = userMapper.getUserList(user);
        if(userList.isEmpty()){
            return null;
        }else{//進行密碼比對
            String ecnryptPassword = userList.get(0).getPassword();
            if(ecnryptPassword.equals(password)) {
                return userList.get(0);
            }
            else {
                return null;
            }
        }
    }
}

 

 
UserMapper dao文件中的文件編碼
import com.chatRotbot.model.User;

import java.util.List;

public interface UserMapper {

/**
* 根據條件查詢用戶列表
* @param user
* @return
*/
List <User> getUserList(User user);
}

 

UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 設置爲IUserDao接口方法提供sql語句配置 -->
<mapper namespace="com.chatRotbot.dao.mapper.UserMapper">
    <sql id = "all_user_columns">
         id,email,password,username,role,status,regTime,regIp
    </sql>
    <!--將通用的sql查詢條件抽取出來,成爲sql片斷 ,給不一樣方法應用  -->
    <sql id="query_user_sql_where">
        <if test="userName!=null">
            AND username LIKE '%${userName}%'
        </if>
        <if test="password!=null">
            AND PASSWORD= #{password}
        </if>
    </sql>
    <select id="getUserList" parameterType="user" resultType="user">
        SELECT
        <include refid="all_user_columns"></include>
        FROM user
        <where>
            <include refid="query_user_sql_where"></include>
        </where>
    </select>
</mapper>

 

 
User
package com.chatRotbot.model;

 import java.util.Date;

public class User {
    public long getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    private int userId;
    private String email;
    private String password;
    private String userName;
    private String role;
    private int status;
    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;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public Date getRegTime() {
        return regTime;
    }
    public void setRegTime(Date regTime) {
        this.regTime = regTime;
    }

    public String getRegIp() {
        return regIp;
    }
    public void setRegIp(String regIp) {
        this.regIp = regIp;
    }
    private Date regTime;
    private String regIp;
}

 

 login.jsp 登陸界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>登陸</title>
    <style type="text/css">
        html,body{height:100%;}
        /*canvas開始*/
        #canvas {position: absolute;z-index: -1;display: block;}
        /*canvas結束*/
        #login {
            width: 400px;
            height: 320px;
            background: #fff;
            position: absolute; /*絕對定位*/
            margin:auto;
            top:0px;
            left:0px;
            right:0px;
            bottom:0px;
            box-shadow: 0px 0px 10px #666;
            border-radius: 4px; /*圓角*/
        }
        .well{background-color: #062A36;}
        h2{font-family:"微軟雅黑";font-size:24px;color:#B94846;margin-bottom:28px;}
        #loginForm{color:#fff}
    </style>
</head>
<body style = "border-radius: 10px;background-size:100% 100% ">
<div class="row" id="login" >
    <div class="well col-md-12 center">
        <div class="title" style="padding: 5px;text-align:center;">
            <h2>登陸系統</h2>
        </div>
        <div id="messageBoxLogin" class="alert alert-error ${empty loginFlag ? 'hide' :''} ">
            <label id="loginFlag" class="error">${loginFlag}</label>
        </div>
        <form id="loginForm"  action="login" method="post">
            <label class="input-label" for="loginName">登陸名</label>
            <input type="text" id="loginName" name="loginName"  value="">
            <label class="input-label" for="password">密碼</label>
            <input type="password" id="password" name="password" >
            <input class="btn  btn-primary" type="submit" value="登 錄" />&nbsp;&nbsp;
        </form>
    </div>
</div>
</body>
</html>
main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>項目搭建</head>
<body>
<h1>恭喜您,ssm框架搭建成功</h1>

</body>
</html>
 


新建完成後配置項目運行環境,點擊Run-Edit Configurations...mysql

點擊加號新建運行環境,選擇Tomcat Server-Localweb

選中新建好的服務器,右邊選擇Deployment,點擊加號-Atifact...spring

選擇第二項sql

war和war exploded 這裏看一下他們兩個的區別:apache

war模式:將WEB工程以包的形式上傳到服務器 ;
war exploded模式:將WEB工程以當前文件夾的位置關係上傳到服務器;

(1)war模式這種能夠稱之爲是發佈模式,看名字也知道,這是先打成war包,再發布;canvas

(2)war exploded模式是直接把文件夾、jsp頁面 、classes等等移到Tomcat 部署文件夾裏面,進行加載部署。所以這種方式支持熱部署,通常在開發的時候也是用這種方式。api

(3)在平時開發的時候,使用熱部署的話,應該對Tomcat進行相應的設置,這樣的話修改的jsp界面什麼的東西才能夠及時的顯示出來。

而後在右邊Application context配置你的項目名

終於配置完了,運行Tomcat咱們看一下效果吧。

咱們啓動之後會自動彈出登陸界面,這裏登陸界面有點難看,勿噴啊。

當咱們輸入密碼錯誤時出現如下界面

當咱們輸入正確的密碼時,界面跳轉到 主界面

 

 

 

 如今項目算是告一段落了。

打印日誌:

2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:861) - DispatcherServlet with name 'springmvc' processing POST request for [/ChatRobot/login]
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:319) - Looking up handler method for path /login
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:326) - Returning handler method [public java.lang.String com.chatRotbot.controller.UserController.login(java.lang.String,java.lang.String,org.springframework.ui.Model,javax.servlet.http.HttpSession)]
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:250) - Returning cached instance of singleton bean 'userController'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.cors.DefaultCorsProcessor.processRequest(DefaultCorsProcessor.java:72) - Skip CORS processing, request is a same-origin one
2018/09/13/17:43:04 INFO  [http-bio-8081-exec-2] com.chatRotbot.controller.UserController.login(UserController.java:30) - 登錄用戶名:chenyaping
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.debug(JakartaCommonsLoggingImpl.java:54) - Creating a new SqlSession
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.debug(JakartaCommonsLoggingImpl.java:54) - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@167558b0] was not registered for synchronization because synchronization is not active
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.debug(JakartaCommonsLoggingImpl.java:54) - JDBC Connection [com.mysql.jdbc.Connection@5407451a] will not be managed by Spring
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.debug(JakartaCommonsLoggingImpl.java:54) - ==>  Preparing: SELECT id,email,password,username,role,status,regTime,regIp FROM user WHERE username LIKE '%chenyaping%' 
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.debug(JakartaCommonsLoggingImpl.java:54) - ==> Parameters: 
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.debug(JakartaCommonsLoggingImpl.java:54) - <==      Total: 2
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.debug(JakartaCommonsLoggingImpl.java:54) - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@167558b0]
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.jdbc.datasource.DataSourceUtils.doReleaseConnection(DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
2018/09/13/17:43:04 INFO  [http-bio-8081-exec-2] com.chatRotbot.controller.UserController.login(UserController.java:38) - 登錄成功
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1620) - Invoking afterPropertiesSet() on bean with name 'redirect:/main'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:250) - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1241) - Rendering view [org.springframework.web.servlet.view.RedirectView: name 'redirect:/main'; URL [/main]] in DispatcherServlet with name 'springmvc'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1000) - Successfully completed request
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:861) - DispatcherServlet with name 'springmvc' processing GET request for [/ChatRobot/main]
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:319) - Looking up handler method for path /main
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:326) - Returning handler method [public java.lang.String com.chatRotbot.controller.UserController.main()]
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:250) - Returning cached instance of singleton bean 'userController'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:947) - Last-Modified value for [/ChatRobot/main] is: -1
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1620) - Invoking afterPropertiesSet() on bean with name 'main/main'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:250) - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1241) - Rendering view [org.springframework.web.servlet.view.JstlView: name 'main/main'; URL [/WEB-INF/pages/main/main.jsp]] in DispatcherServlet with name 'springmvc'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:166) - Forwarding to resource [/WEB-INF/pages/main/main.jsp] in InternalResourceView 'main/main'
2018/09/13/17:43:04 DEBUG [http-bio-8081-exec-2] org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1000) - Successfully completed request

 

總結:

  我這裏只是簡單的搭建了一個 ssm框架,實現頁面的登陸功能,這纔是項目開始冰山一角而且還有不少地方的不足,這裏在搭建這個登陸功能時也遇到了不少的問題,好比剛開始搭建環境時,Maven版本下的最新版本致使

IntelliJ IDEA一直沒法讀取,最後下載了低一點版本,還遇到mapper文件一直沒法讀取,最終參考http://www.javashuo.com/article/p-nfhpyylu-mv.html,但願這個簡單的搭建能給你們一些幫助和啓發。

相關文章
相關標籤/搜索