码迷,mamicode.com
首页 > 编程语言 > 详细

第一个Spring demo

时间:2016-08-24 17:28:21      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

参考Spring3.x企业实战

1.新建web工程chapter5,导入jar包。注意:cglib和commons-dbcp这两个包

技术分享

2.设计数据库

  t_login_log表结构(存放日志信息),主键递增

技术分享

 t_user表结构(存放用户信息),主键递增

技术分享

 

3.设计包结构

技术分享

技术分享

 4.domain对象

User.java

package com.baobaotao.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 lastVisit) {
        this.lastVisit = lastVisit;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
    @Override
    public String toString() {
        return "User [userId=" + userId + ", userName=" + userName
                + ", password=" + password + ", credits=" + credits
                + ", lastIp=" + lastIp + ", lastVisit=" + lastVisit + "]";
    }
}
LoginLog.java

package com.baobaotao.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;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
    @Override
    public String toString() {
        return "LoginLog [loginLogId=" + loginLogId + ", userId=" + userId
                + ", ip=" + ip + ", loginDate=" + loginDate + "]";
    }
}

 

5.dao层(访问数据库相关操作)

UserDao.java

package com.baobaotao.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

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 com.baobaotao.domain.User;

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    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.java

package com.baobaotao.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.baobaotao.domain.LoginLog;

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

 

6.service层(调用dao层操作)

UserService.java

package com.baobaotao.service;

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

import com.baobaotao.dao.LoginLogDao;
import com.baobaotao.dao.UserDao;
import com.baobaotao.domain.LoginLog;
import com.baobaotao.domain.User;

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

 

7.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:p="http://www.springframework.org/schema/p"    
    xmlns:mvc="http://www.springframework.org/schema/mvc"    
    xmlns:context="http://www.springframework.org/schema/context"    
    xmlns:util="http://www.springframework.org/schema/util"   
    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-3.0.xsd    
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd    
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <context:component-scan base-package="com.baobaotao.dao"/>
    
    <context:component-scan base-package="com.baobaotao.service"/> 
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
           destroy-method="close"  p:driverClassName="com.mysql.jdbc.Driver"
           p:url="jdbc:mysql://localhost/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.baobaotao.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>

 

8.测试

package com.baobaotao.service;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.baobaotao.domain.User;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
public class TestUserService {
    @Autowired
    private UserService userService;
    
    public static void main(String[] args) {
        ApplicationContext atx=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService=(UserService) atx.getBean("userService");
        User user=userService.findUserByUserName("admin");
        
        System.out.println(user);
    }
}

一个小问题:如果不写 private UserService userService; 也能运行,不是没有注入bean吗?怎么能获得bean?

9.使用springmvc 配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    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_2_5.xsd">
  <display-name></display-name>    
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/classes/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>

 

10.web层的控制器

package com.baobaotao.web;

import java.util.Date;

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 org.springframework.web.servlet.ModelAndView;

import com.baobaotao.domain.User;
import com.baobaotao.service.UserService;

@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.getRemoteAddr());
             user.setLastVisit(new Date());
             userService.loginSuccess(user);
             request.getSession().setAttribute("user", user);
             return new ModelAndView("main");
         }
    }
}
package com.baobaotao.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;
    }
}

 

11.配置springmvc的xml文件  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-3.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!-- 扫描web包,应用Spring的注解 -->
    <context:component-scan base-package="com.baobaotao.web"/>
    
    <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
    <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>

 

12.在WEB-INF下建立jsp文件夹

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

<%@ 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>

13.发布启动tomcat 输入 http://localhost:8080/chapter5/index.html即可进入登录界面

 

遇到的一些问题:

 1.使用mysql数据库,我没设置密码,一直报Access denied for user ‘root‘@‘localhost‘ (using password: YES)解决方法 这个错误

    解决:参考 http://blog.csdn.net/skywalker_leo/article/details/47274441

 2.把一些其他的web程序要先关掉,不然启动的时候很有可能报错。

 3.注意一些jar包的引入和jar包之间的冲突问题。

第一个Spring demo

标签:

原文地址:http://www.cnblogs.com/coderising/p/5803602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!