欢迎与我联系   

smm框架整合实现登录功能

一、准备所需的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>
复制代码
posted @ 2017-03-26 14:18  小珍珠在河里敲代码  阅读(2408)  评论(0编辑  收藏  举报