noteless 头像

eclipse 创建maven 项目 动态web工程完整示例 maven 整合springmvc整合mybatis

接上一篇:

eclipse 创建maven 项目 动态web工程完整示例

 

 

eclipse maven工程自动添加依赖设置

maven工程可以在线搜索依赖的jar包,还是非常方便的

但是有的时候可能还需要设置下

60297850-9351-48a5-9e94-b049ec0caee9

f2c29927-7886-4ca4-aa06-c142ec1fef10

eclipse不能在线搜索jar包 报错

如果搜索不到内容,或者有报错信息(index downloads are disabled ,search results may be incomplete)

windows  preference   maven   勾选上

955a1439-8b33-404d-b80a-345c70e4d1be

然后  windows  show views

a8ed8784-ea10-4d58-9d8d-1897fe57c26f

7714ad98-ab6b-4363-af38-800edae03463

b458f18e-470f-4e43-b88a-d8a9c016b702

rebuild一下

c73782d2-c426-4bf9-a088-e52f0aa71f05

就可以搜索了

注意这个地方的scope,暂且不管

924b04fd-244f-40bf-8829-8a5c4d44ada2

我们输入spring-webmvc,找到我们需要的,单击一下就好了

还有就是,version只要是存在的版本,我们可以手动写的

0d8083e7-702d-4ea1-9ea6-e199a1c81430

1339b709-3cb1-40ce-88c4-5c5c934269c5

添加了之后,顺手更新了下项目(注意,不是必须要做的哈,只是我手欠了)不过你早晚或许都会需要更新下

 

01cf02ef-1df8-48a7-838e-1975c0a974cc

然后捏

尼玛,报错了....

4dd0d6f1-1e86-46bb-ab04-b73346664e43

想了一下不应该啊,都修改好了的

回头一看

我的jdk版本,还有eclipse的一些配置,都尼玛改回来了,还原了....

127a1666-03f5-4b13-825f-bff62720d8ca

c21a35f9-f23d-4a83-8b07-950e65bc1595

肿么了这是?

忘记设置了!!!!!

maven update project后版本还原,jdk还原了!

Maven 3.0 source和target的默认设置都是1.5,与运行Maven时的JDK版本无关,除非在项目的POM文件中显示的指定一个版本,否则每次更新后都会使用编译器默认的source/target版本1.5。

所以,把原来修改过的东西修改回去先......

然后pom.xml中显示的指定这一段

<build>  

    <plugins>  

        <plugin>  

            <groupId>org.apache.maven.plugins</groupId>  

            <artifactId>maven-compiler-plugin</artifactId>  

            <version>3.3</version>  

            <configuration>  

                <!-- 指定source和target的版本 -->                 

                <source>1.8</source>  

                <target>1.8</target>  

            </configuration>  

        </plugin>  

    </plugins>  

</build>

(如果有build标签了,就是plugins这一段)

然后在更新下  update project

刚才的错误就没了

ce8a8896-1c06-425c-abec-3f3444b70888

我们刚才引入了spring-context  spring-webmvc发现多了好几个

这就是maven好处,它所依赖的包,会自动下载的...

我们再继续添加一个mybatis-spring

最后的结果就是这样子

0fc58911-516c-4746-b60b-8d03f018fa88

HelloWorld.java

package springmvcMaven;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class HelloWorld {

public static void main(String[]args){

        ApplicationContext ctx = new FileSystemXmlApplicationContext("src/helloWorld.xml");

        HelloWorldSpringBean helloWorldSpringBean = (HelloWorldSpringBean)ctx.getBean("myHelloWorld");

helloWorldSpringBean.show();

    }

}

HelloWorldSpringBean.java

package springmvcMaven;

public class HelloWorldSpringBean {

private String hello;

public String getHello(){

return hello;

    }

public void setHello(String hello){

this.hello=hello;

    }

public void show(){

        System.out.println("--message--"+getHello());

    }

}

helloWorld.xml  在src的根目录下

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="myHelloWorld" class="springmvcMaven.HelloWorldSpringBean">

<property name="hello">

<value>hello World spring!</value>

</property>

</bean>

</beans>

项目的结构就是这样子

bad45664-ead9-48b5-810c-1234ab297375

右键  run as,打印信息成功

spring跑通 

40fb32d7-4693-4d7f-b94f-ff6db3c62624

现在开始测试一下springmvc的情况

为了接下来的项目的规范性,我们重新规划下项目的结构以及配置文件

fac281fa-9850-411d-939b-ccc5e8e09dc2

这个是最新的结构

说白了新建了几个包,用于区分不同的功能划分,controller用于控制跳转,domain用于存放JavaBean,dao用于操作数据库相关,service用于相关接口的实现

mapper用于mybatis的xml文件

另外还有两个配置文件

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-4.2.xsd

        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd

        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

<!--扫描类包,标注spring注解的类自动转换成bean,同时完成bean的注入  (这样类中定义的spring注解  比如@repository @autowired等才能起作用)  -->

<context:component-scan base-package="com.noteless.bbs.domain" />

</beans>

springmvc.xml设置了自动扫描的controller的类包,并且设置了视图解析

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:mvc="http://www.springframework.org/schema/mvc"

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-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">

<!-- 自动扫描带有@Controller注解的控制层,注入为bean -->

<context:component-scan base-package="com.noteless.bbs.controller" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/views/" />

<property name="suffix" value=".jsp" />

</bean>

</beans>

web.xml 中指定了配置文件的路径,以及配置了servlet

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0"

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">

<!--   <display-name>Archetype Created Web Application</display-name> -->

<!-- 1,从类路径下加载spring的配置文件,classpath关键字特指类路径下加载 -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

<!--2,负责启动spring容器的监听器,它将引用1处的上下文参数,获得spring配置文件的地址  -->

<listener>

<listener-class>

    org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

<servlet>

<servlet-name>bbs</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:springmvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>bbs</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

</web-app>

controller里面新建一个LoginController.java

package com.noteless.bbs.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class LoginController {

@RequestMapping(value="/welcome")

public String toLoginPage(HttpServletRequest request){

return "welcome";

}

}

在views下面新建了一个欢迎页面

welcome.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>标题</title>

</head>

<body>

欢迎光临!

<br>

欢迎光临!

</body>

</html>

我们启动server,然后运行项目

2eab3490-cccf-446c-baa9-5a45e4b63782

可以看到springmvc的配置也没有问题

接下来是链接数据库,以及配置mybatis

刚才引用了一些包但是还远远不够,此处不再一一介绍没一个引用的包的作用以及何时引入了,贴出来我用到的包,

f382984f-d527-4062-8b9c-5b516b2541fa

1d2e934f-51f1-451c-afdb-6804030ed16d

有了这些包就可以开始我们后续的项目了

注意;如果是项目搭建初期,如果有报错,我建议,先看看常用的或者必须要用到的一些包是不是缺失,都弄过来

如果还有报错,再去看具体的原因

当然如果你非常熟悉的话,看一眼报错就知道缺什么包那就最好了,估计你要是还在看我的文章,说明你不牛...

配置数据库以及配置mybatis

这个工程示例,是接着我的之前的文章中的示例写的,功能一样,结构不一样(之前的没用maven)

一些javaBean类以及service 都直接拿过来用了

有兴趣的翻一下其他的文章

现在的结构为:

9f1c169b-6e0e-4c75-959d-459967397875

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-4.2.xsd

        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd

        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

<!--扫描类包,标注spring注解的类自动转换成bean,同时完成bean的注入  (这样类中定义的spring注解  比如@repository @autowired等才能起作用)  -->

<context:component-scan base-package="com.noteless.bbs.domain" />

<!--扫描service包,应用spring注解配置  -->

<context:component-scan base-package="com.noteless.bbs.service" />

<!-- 定义一个使用DBCP实现的数据源 -->

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"

destroy-method="close"

p:driverClassName="com.mysql.jdbc.Driver"

p:url="jdbc:mysql://localhost:3306/sampledb"

p:username="root"

p:password="123456"/>

<!-- myBatis文件 -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<!-- 自动扫描映射文件 -->

<property name="mapperLocations">

<array>

<value>classpath:mapper/*.xml</value>

</array>

</property>

</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

<property name="basePackage" value="com.noteless.bbs.dao" />

<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />

</bean>

</beans>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:mvc="http://www.springframework.org/schema/mvc"

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-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">

<!-- 自动扫描带有@Controller注解的控制层,注入为bean -->

<context:component-scan base-package="com.noteless.bbs.controller" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/views/" />

<property name="suffix" value=".jsp" />

</bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0"

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">

<!--   <display-name>Archetype Created Web Application</display-name> -->

<!-- 1,从类路径下加载spring的配置文件,classpath关键字特指类路径下加载 -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

<!--2,负责启动spring容器的监听器,它将引用1处的上下文参数,获得spring配置文件的地址  -->

<listener>

<listener-class>

    org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

<servlet>

<servlet-name>bbs</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:springmvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>bbs</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

</web-app>

   其实,这几个文件是最重要的哈,还有jar包..

2d3f0dfc-0dbf-467e-b0e8-e598b9bc1d2d

把接口  javaBean挪过来之后,配置处理好之后,测试一下,可以执行通过

这样一个完整的springmvc+mybatis+maven的项目就搭建完成了

999a8dbf-681c-4444-a47b-cc0776ed79a1

哦,对了,还有一个log4j,它的使用也很简单

应用jar包

并且配置下配置文件即可

具体的可以参考我的工程直接eclipse导入即可了

springmvcmybatisMaven-002.rar      http://pan.baidu.com/s/1sknL8rb

防止链接失效,代码都贴出来吧..

一下就是所有的代码,建议下载我的工程,导入eclipse慢慢研究

 

spring原理 实践解析-简单的helloworld

spring原理案例-基本项目搭建 01 spring framework 下载 官网下载spring jar包

spring原理案例-基本项目搭建 02 spring jar包详解 spring jar包的用途

spring原理案例-基本项目搭建 03 创建工程运行测试 spring ioc原理实例示例

springmvc整合mybatis完整项目示例

springmvc 项目完整示例01 需求与数据库表设计 简单的springmvc应用实例 web项目

springmvc 项目完整示例02 项目创建-eclipse创建动态web项目 配置文件 junit单元测试

springmvc 项目完整示例03 小结

springmvc 项目完整示例04 整合mybatis mybatis所需要的jar包 mybatis配置文件 sql语句 mybatis应用

springmvc 项目完整示例05  日志 --log4j整合 配置 log4j属性设置 log4j 配置文件 log4j应用

springmvc 项目完整示例06 日志–log4j 参数详细解析 log4j如何配置

springmvc 项目完整示例07 设置配置整合springmvc springmvc所需jar包springmvc web.xml文件配置

springmvc 项目完整示例08 前台页面以及知识点总结

maven项目整合springmvc整合mybatis

eclipse 创建maven 项目 动态web工程完整示例

eclipse 创建maven 项目 动态web工程完整示例 maven 整合springmvc整合

 

 

工程项目:

image

 

 

image

 

 

用到的jar包

image

 

主要的配置文件:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    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">
    
<!--   <display-name>Archetype Created Web Application</display-name> -->
  
  <!-- 1,从类路径下加载spring的配置文件,classpath关键字特指类路径下加载 -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
    
    </context-param>
    <!--2,负责启动spring容器的监听器,它将引用1处的上下文参数,获得spring配置文件的地址  -->
    <listener>
    <listener-class>
    org.springframework.web.context.ContextLoaderListener
    </listener-class>
    </listener>
    
    <servlet>
        <servlet-name>bbs</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>bbs</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
  
  
  
  
</web-app>

 

 

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    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-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">

    <!-- 自动扫描带有@Controller注解的控制层,注入为bean -->
    <context:component-scan base-package="com.noteless.bbs.controller" />
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
    


    
</beans>

appliacationContext.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-4.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">



    <!--扫描类包,标注spring注解的类自动转换成bean,同时完成bean的注入  (这样类中定义的spring注解  比如@repository @autowired等才能起作用)  -->
    <context:component-scan base-package="com.noteless.bbs.domain" />
    
        <!--扫描service包,应用spring注解配置  -->
    <context:component-scan base-package="com.noteless.bbs.service" />
    
    
<!-- 定义一个使用DBCP实现的数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
    destroy-method="close"
    p:driverClassName="com.mysql.jdbc.Driver"
    p:url="jdbc:mysql://localhost:3306/sampledb"
    p:username="root"
    p:password="123456"/>
    
    
    <!-- myBatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描映射文件 -->
        <property name="mapperLocations">
            <array>
                <value>classpath:mapper/*.xml</value>
            </array>
        </property>

    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.noteless.bbs.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
    

</beans>

 

log4j.properties

### set log levels ###
log4j.rootLogger = DEBUG,stdout,D


### 输出到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n


### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = C://Users/joy/\Desktop/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### sql ###
log4j.logger.java.sql.Connection=DEBUG 
log4j.logger.java.sql.PreparedStatement=DEBUG  
log4j.logger.java.sql.ResultSet=DEBUG

 

LoginController.java

package com.noteless.bbs.controller;

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 com.noteless.bbs.domain.User;
import com.noteless.bbs.service.UserService;



@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    
    @RequestMapping(value="/welcome")
    public String toLoginWelconenPage(HttpServletRequest request){

        return "welcome";
    }
    

    
    @RequestMapping(value="/login")
    public String toLoginPage(HttpServletRequest request){

        return "login";
    }
    
    
    @RequestMapping(value="/checkLogin")
    public String loginPage(HttpServletRequest request,User user){
        
        Boolean loginSucess = userService.hasMatchUser(user);
        if(loginSucess){
            userService.loginSucess(userService.findUserByUserName(user));
            request.getSession().setAttribute("Info","");
            return "welcome";
        }else{
            request.getSession().setAttribute("Info","请重新输入!!");
            return "redirect:/login.do";
        }
        
    }
}

 

 

LoginLogMapper.java

package com.noteless.bbs.dao;

import com.noteless.bbs.domain.LoginLog;

public interface LoginLogMapper {

    public void insertLoginLog(LoginLog loginLog);
}

 

UserMapper.java

package com.noteless.bbs.dao;

import com.noteless.bbs.domain.User;

public interface UserMapper {
    
    public Integer getMatchCount(User user);

    
    public User findUserByUserName(User user);

    
    public void updateLoginInfo(User user);
    
    public void insertUser(User user);
    
    public void updateUserInfo(User user);
}

 

 

LoginLog.java

package com.noteless.bbs.domain;

import java.io.Serializable;
import java.util.Date;

public class LoginLog implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private int loginLogId;
    private int userId;
    private String ip;
    private Date loginDate;
    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;
    }
    
    
}

 


User.java

package com.noteless.bbs.domain;

import java.io.Serializable;
import java.util.Date;


public class User implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private int userId;
    private String userName;
    private String password;
    private int credits;
    private String lastIp;
    private Date lastVisit;
    
    
    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 date) {
        this.lastVisit = date;
    }
    
    
}


 

 

LoginLogService.java

package com.noteless.bbs.service;

import com.noteless.bbs.domain.LoginLog;

public interface LoginLogService {

    public void insertLoginLog(LoginLog loginLog);
}

 

 

LoginLogServiceImpl.java

package com.noteless.bbs.service;

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

import com.noteless.bbs.dao.LoginLogMapper;
import com.noteless.bbs.domain.LoginLog;

@Service
public class LoginLogServiceImpl implements LoginLogService {

    @Autowired
    private LoginLogMapper loginLogMapper;
    @Override
    public void insertLoginLog(LoginLog loginLog) {
        loginLogMapper.insertLoginLog(loginLog);
        
    }

}

 


UserService.java

package com.noteless.bbs.service;

import com.noteless.bbs.domain.User;

public interface UserService {

    public Boolean hasMatchUser(User user);
    
    
    public User findUserByUserName(User user);
    
    
    public void loginSucess(User user);
    
    public void insertUser(User user);


    public void UpdateUser(User user);

}

 

 

UserServiceImpl.java

package com.noteless.bbs.service;

import java.util.Date;

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

import com.noteless.bbs.dao.UserMapper;
import com.noteless.bbs.domain.LoginLog;
import com.noteless.bbs.domain.User;



@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginLogService loginLogService;
    
    @Override
    public Boolean hasMatchUser(User user) {
        
        Integer matchCount = userMapper.getMatchCount(user);
        if(matchCount > 0){
            return true;
        }else{
            return false;
        }


    }

    @Override
    public User findUserByUserName(User user) {
        return userMapper.findUserByUserName(user);
    }

    @Override
    public void loginSucess(User user) {

        user.setCredits(5+user.getCredits());
        user.setLastVisit(new Date());
        
        LoginLog loginLog = new LoginLog();
        
        loginLog.setUserId(user.getUserId());
        loginLog.setIp(user.getLastIp());
        loginLog.setLoginDate(new Date());
        
        
        userMapper.updateLoginInfo(user);
        loginLogService.insertLoginLog(loginLog);
    }

    @Override
    public void insertUser(User user) {
        userMapper.insertUser(user);
    }
    
    @Override
    public void UpdateUser(User user) {
        userMapper.updateUserInfo(user);
    }
    

}

 

 

LoginLogMapper.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" >
<mapper namespace="com.noteless.bbs.dao.LoginLogMapper">

   <insert id="insertLoginLog" parameterType="com.noteless.bbs.domain.LoginLog">
        insert into t_login_log(
            user_id,
            ip,
            login_datetime
        ) 
        values(
            #{userId},
            #{ip},
            #{loginDate}
        )
    </insert>
    
</mapper>

 

 

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" >
<mapper namespace="com.noteless.bbs.dao.UserMapper">

    <select id="getMatchCount" parameterType="com.noteless.bbs.domain.User"
        resultType="java.lang.Integer">
        SELECT count(*)
        FROM
        t_user
        WHERE
        user_name=#{userName}
        and password=#{password}
    </select>

    <select id="findUserByUserName" parameterType="com.noteless.bbs.domain.User"
        resultType="com.noteless.bbs.domain.User">
        SELECT
        t_user.user_id as userId,
        t_user.user_name as userName,
        t_user.credits as credits,
        t_user.password as password,
        t_user.last_ip as lastIp,
        t_user.last_visit as lastVisit


        FROM
        t_user
        WHERE
        user_name=#{userName}
    </select>


    <update id="updateLoginInfo" parameterType="com.noteless.bbs.domain.User">

        UPDATE t_user
        <set>
            <if test="lastVisit !=null">
                last_visit = #{lastVisit},
            </if>
            <if test="lastIp !=null and lastIp !=''">
                last_ip = #{lastIp},
            </if>
            <if test="credits !=null and credits !=''">
                credits = #{credits},
            </if>

        </set>
        where user_id=#{userId}
    </update>

    <insert id="insertUser" parameterType="com.noteless.bbs.domain.User">
        insert into t_user(
        user_name,
        credits,
        password,
        last_ip,
        last_visit
        )
        values(
        #{userName},
        #{credits},
        #{password},
        #{lastIp},
        #{lastVisit}

        )
    </insert>



    <update id="updateUserInfo" parameterType="com.noteless.bbs.domain.User">

        UPDATE t_user

        <set>
            <if test="lastVisit !=null">
                last_visit = #{lastVisit},
            </if>
            <if test="lastIp !=null and lastIp !=''">
                last_ip = #{lastIp},
            </if>
            <if test="credits !=null and credits !=''">
                credits = #{credits},
            </if>

        </set>
        where user_id=#{userId}
    </update>


</mapper>

 

TestUserService.java

package com.noteless.bbs;

import static org.junit.Assert.*;

import java.util.Date;

import org.apache.log4j.Logger;
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.noteless.bbs.domain.User;
import com.noteless.bbs.service.UserService;



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})

public class TestUserService {

    @Autowired
    private UserService userService;
    

    
    private static Logger logger = Logger.getLogger(Test.class);  
    
    @Test
    public void testLog(){
        
        logger.debug("this is a debug info");
        
    }
    
    @Test 
    public void hasMAtchUser(){
        User user1 = new User();
        User user2 = new User();
        
        user1.setUserName("admin");
        user1.setPassword("123456");
        
        user2.setUserName("admin");
        user2.setPassword("11111");
        
        
        boolean b1 = userService.hasMatchUser(user1);
        //boolean b2 = userService.hasMatchUser(user2);
        
        assertTrue(b1);
        //assertTrue(b2);
        
        
        
    }
    
    @Test
    public void findUserByUserName(){
        User user = new User();
        
        user.setUserName("admin");

        
        User user1 = userService.findUserByUserName(user);
        System.out.println(user1.getUserName());
        assertEquals(user1.getUserName(),"admin");
    }

    @Test
    public void loginSucess(){
        
        User user = new User();
        user.setUserName("admin");
        user= userService.findUserByUserName(user);
        userService.loginSucess(user);
    
    }
    
    @Test
    public void insertUser(){
        
        User user = new User();
        user.setUserName("user1");
        user.setPassword("123456");
        user.setCredits(0);
        user.setLastIp("255.255.255.255");
        user.setLastVisit(new Date(0) );
        
        userService.insertUser(user);
        

    
    }
    @Test
    public void updateUserInfo(){
        
        User user = new User();
        user.setUserId(2);
        user.setLastVisit(new Date() );
        user.setCredits(5+user.getCredits());

        
        userService.UpdateUser(user);
        

    
    }
    
}

 

login.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>标题</title>
</head>
<body>

${Info}


请输入用户名,密码登陆:
<form action="/springmvcMaven/checkLogin.do" meathod="post">
用户名:
<input type="text" name="userName">
<br>
密码:
<input type="password" name="password">
<br>

<input type="submit" value="登陆">
<input type="reset" value="重置">
</form>
</body>
</html>

 

welcome.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>标题</title>
</head>
<body>
欢迎光临!
<br>
欢迎光临!
</body>
</html>
posted @ 2016-02-29 17:02  noteless  阅读(...)  评论(...编辑  收藏