竞争无处不在,青春永不言败!专业撸代码,副业修bug

Talk is cheap , show me the code!



spring+spring mvc+JdbcTemplate 入门小例子

大家使用这个入门时候 最好能够去 搜一下 spring mvc 的 原理,我放一张图到这里,自己琢磨下,后面去学习就容易了
给个链接 (网上一把,千万不能懒)    https://www.cnblogs.com/chuiyuan/p/5301216.html
 
步骤:

1.发起请求到前端控制器(DispatcherServlet)
2.前端控制器请求处理器映射器(HandlerMapping)查找Handler(可根据xml配置、注解进行查找)
3.处理器映射器(HandlerMapping)向前端控制器返回Handler
4.前端控制器调用处理器适配器(HandlerAdapter)执行Handler
5.处理器适配器(HandlerAdapter)去执行Handler
6.Handler执行完,给适配器返回ModelAndView(Springmvc框架的一个底层对象)
7.处理器适配器(HandlerAdapter)向前端控制器返回ModelAndView
8.前端控制器(DispatcherServlet)请求视图解析器(ViewResolver)进行视图解析,根据逻辑视图名解析成真正的视图(jsp)
9.视图解析器(ViewResolver)向前端控制器(DispatcherServlet)返回View
10.前端控制器进行视图渲染,即将模型数据(在ModelAndView对象中)填充到request域
11.前端控制器向用户响应结果
原理图解释

 


废话不多说,下面直接开撸! talk is cheap! show me the code!

DROP DATABASE IF EXISTS sampledb;
CREATE DATABASE sampledb DEFAULT CHARACTER SET utf8;
USE sampledb;

##创建用户表
CREATE TABLE t_user (
   user_id   INT AUTO_INCREMENT PRIMARY KEY,
   user_name VARCHAR(30),
   password  VARCHAR(32),
   credits INT,
   last_visit datetime,
   last_ip  VARCHAR(23)
)ENGINE=InnoDB; 

##创建用户登录日志表
CREATE TABLE t_login_log (
   login_log_id  INT AUTO_INCREMENT PRIMARY KEY,
   user_id   INT,
   ip  VARCHAR(23),
   login_datetime datetime
)ENGINE=InnoDB; 

##插入初始化数据
INSERT INTO t_user (user_name,password) 
             VALUES('admin','123456');
COMMIT;
mysql脚本

 

1、配置 pom.xml  添加项目需要的依赖包等。

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ghc</groupId>
  <artifactId>smart</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>smart Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <properties>

    <file.encoding>UTF-8</file.encoding>
    <spring.version>4.2.2.RELEASE</spring.version>
    <mysql.version>5.1.29</mysql.version>
    <servlet.version>3.0-alpha-1</servlet.version>
    <aspectj.version>1.8.1</aspectj.version>
    <commons-codec.version>1.9</commons-codec.version>
    <commons-dbcp.version>1.4</commons-dbcp.version>
    <hibernate.validator.version>5.0.2.Final</hibernate.validator.version>
    <jetty.version>8.1.8.v20121106</jetty.version>
    <slf4j.version>1.7.5</slf4j.version>
    <testng.version>6.8.7</testng.version>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>


    <!-- spring 依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>${commons-dbcp.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectj.version}</version>
    </dependency>


    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>${testng.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/jstl/jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.1.2</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <!-- jetty插件 -->
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.25</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8000</port>
              <maxIdleTime>60000</maxIdleTime>
            </connector>
          </connectors>
          <contextPath>/bbs</contextPath>
          <scanIntervalSeconds>0</scanIntervalSeconds>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.17</version>
        <configuration>
          <parallel>methods</parallel>
          <threadCount>10</threadCount>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>
pom.xml

2、配置 web.xml  主要是 配置 spring 容器(spring-context.xml)的 配置信息 以及 spring mvc 核心前端控制器 DispatcherServlet 的信息

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--添加 spring 容器监听器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring-context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--添加springmvc前端控制器或者说中央控制器-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:/springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>

</web-app>
web.xml

3、配置 spring-context.xml ,配置 spring 容器 (基石)

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

    <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
    <context:component-scan base-package="com.ghc.dao"/>
    <context:component-scan base-package="com.ghc.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="Mede645"
    />

    <!-- 配置Jdbc模板  -->
    <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配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
    <aop:config proxy-target-class="true">
        <aop:pointcut id="serviceMethod"
                      expression="(execution(* com.ghc.service..*(..))) and (@annotation(org.springframework.transaction.annotation.Transactional))" />
        <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-context.xml

4、配置 springmvc-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-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--配置组件扫描 应用 sprnig 注解-->
    <context:component-scan base-package="com.ghc.web"/>

    <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>
springmvc.xml

5、mvc 各层代码  由于 我认为的 controller 层 在于 DispatcherServlet(转发控制器) 就已经完成了,所以 后面不会单独说 controller, 后端controller 实际上是 handler

model 层

domain 对象:com.ghc.domain 包下

具体代码 User:

package com.ghc.domain;

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

public class User implements Serializable {
    private int userId;
    private String userName;
    private int credits;
    private String password;
    private Date lastVisit;
    private String lastIp;

    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 int getCredits() {
        return credits;
    }

    public void setCredits(int credits) {
        this.credits = credits;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getLastVisit() {
        return lastVisit;
    }

    public void setLastVisit(Date lastVisit) {
        this.lastVisit = lastVisit;
    }

    public String getLastIp() {
        return lastIp;
    }

    public void setLastIp(String lastIp) {
        this.lastIp = lastIp;
    }
}
com.ghc.domain.User
package com.ghc.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 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;
    }
}
com.ghc.domain.LoginLog

model  的 dao 层:

package com.ghc.dao;

import com.ghc.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 {
    private JdbcTemplate jdbcTemplate;
    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate=jdbcTemplate;
    }

    public final String MATCH_COUNT_SQL=" SELECT COUNT(*) FROM t_user  WHERE  user_name=? and password=? ";

    public int hasMatchCount(String userName,String password){
        return jdbcTemplate.queryForObject(MATCH_COUNT_SQL,new Object[]{userName,password},Integer.class);
    }

    public final String UPDATE_LOG_SQL = " UPDATE t_user SET credits =?,last_visit=? ,last_ip=?  ";
    public void updateLogInfo(User user){
        jdbcTemplate.update(UPDATE_LOG_SQL,new Object[]{user.getCredits(),user.getLastVisit(),user.getLastIp()});
    }

    public User findUserByName(final String userName){
        final User user = new User();
        final String FIND_USER_SQL = " SELECT user_name,credits "
                + " FROM t_user WHERE user_name =? ";
        jdbcTemplate.query(FIND_USER_SQL, new Object[]{userName},new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                user.setUserName(rs.getString("user_name"));
                user.setCredits(rs.getInt("credits"));
            }
        });

        return user;
    }
}
com.ghc.dao.UserDao
package com.ghc.dao;

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

@Repository
public class LoginLogDao {
    private JdbcTemplate jdbcTemplate;
    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate=jdbcTemplate;
    }

    public final String UPDATE_LOG_SQL = " INSERT INTO t_login_log (user_id,ip,login_datetime) VALUES (?,?,?)";

    public void updateLog(LoginLog loginLog){
        jdbcTemplate.update(UPDATE_LOG_SQL,new Object[]{loginLog.getUserId(),loginLog.getIp(),loginLog.getLoginDate()});
    }
}
com.ghc.dao.LoginLogDao

model 的 service 层:

package com.ghc.service;

import com.ghc.dao.LoginLogDao;
import com.ghc.dao.UserDao;
import com.ghc.domain.LoginLog;
import com.ghc.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    private UserDao userDao;
    private LoginLogDao loginLogDao;

    @Autowired
    public void setUserDao(UserDao userDao){
        this.userDao =userDao;
    }
    @Autowired
    public void setLoginLogDao(LoginLogDao loginLogDao){
        this.loginLogDao =loginLogDao;
    }

    public int hasMatchCount(String userName,String password){
        return userDao.hasMatchCount(userName,password);
    }
    public User findUserByName(String userName){
        return userDao.findUserByName(userName);
    }

    @Transactional
    public void loginSuccess(User user){
        //一旦登录成功则积分+5
        user.setCredits(user.getCredits()+5);;
        //并且保留日志记录
        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(user.getUserId());
        loginLog.setIp(user.getLastIp());
        loginLog.setLoginDate(user.getLastVisit());

        userDao.updateLogInfo(user);
        loginLogDao.updateLog(loginLog);
    }
}
com.ghc.service.UserService

view  web 层:

package com.ghc.web;

public class LoginCommand {
    private String userName;
    private String password;

    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;
    }
}
LoginCommand
package com.ghc.web;

import com.ghc.domain.User;
import com.ghc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
public class LoginController {
    private UserService userService;
    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }
    @RequestMapping(value = "/index.html")
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){
        boolean isValid = userService.hasMatchCount(loginCommand.getUserName(),loginCommand.getPassword()) > 0;
        if(!isValid){
            return new ModelAndView("login", "error", "用户名或密码错误。");
        }
        else {
            User user = userService.findUserByName(loginCommand.getUserName());
            user.setLastIp(request.getLocalAddr());
            user.setLastVisit(new Date());

            System.out.println("local addr: "+request.getLocalAddr());
            //修改日志那些
            userService.loginSuccess(user);
            request.getSession().setAttribute("user",user);
            return new ModelAndView("main");
        }
    }
}
LoginController

 

配合 上面 controller 返回 model and view 的 jsp 页面 配置在 /WEB-INF/jsp/下, 这个 前缀, 后缀 都是 配置在 springmvc-servlet 中的,为了方便比照,我也放一张图

 

<%@ 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>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>小春论坛</title>
</head>
<body>
    ${user.userName},欢迎您进入小春论坛,您当前积分为${user.credits};
</body>
</html>
main.jsp

 至此, spring + spring mvc + jdbcTemplate 一个 简单的 登录验证小模块就手动撸完啦! 启动 maven project 管理栏,找到 如图所示的 jetty 插件就可以跑一个小 demo 啦

打开浏览器 手动 敲入 应用 的 url 地址:

http://localhost:8000/bbs/index.html 就会访问到 登录页面了,解释下 这里的 bbs 是在 pom.xml 中对于 jetty 插件 手动指定的 contexpath, 而 index.html 是 LoginController 中的 @RequestMapping 映射指定的  index  传入 视图解析器(springmvc-servlet.xml 中配置的 上面有图), 然后 定位到 /WEB-INF/jsp/index.jsp  这时候就会发现整个项目串起来了! 还是要多做!

 如果 想让 局域网内的 其他人员访问的话, 可以吧 localhost 替换为 192.168.0.xxx 这种 ip 地址,如果告知不能访问,请自行百度或谷歌关闭防火墙

 

输入mysql 数据库中定义好的 t_user 用户表里的 用户名,密码 既可以完成登录,这里我不知道 为啥 , taglib 没有 解析出 request --》 session -》 中携带过来的 uer 对象

所以,你会看到 $   这种 怪异的 玩意儿,懒得去理了 ,网上说差  jstl 的 包,但是我 添加到pom 里 还是不行,还是以后再来理会吧!

 

posted @ 2018-04-13 16:41  云雾散人  阅读(4123)  评论(2编辑  收藏  举报

Your attitude not your aptitude will determine your altitude!

如果有来生,一个人去远行,看不同的风景,感受生命的活力!