SpringMVC_开天辟地

来源:互联网 发布:好人卡 知乎 编辑:程序博客网 时间:2024/04/28 10:27

SpringMVC的优点太多,这里暂且不详细说明,就给大家分享一下如何搭建我们的第一个SpringMVC


一、新建我们的项目

在myelipse下新建Web Project创建我们的项目,然后在src里面分别创建四个包,分别是dao、domain、service、web(具体名字可以自己起)和一个beans.xml文件,这是spring最关键的一个文件,里面将来是要管理几乎项目里所有的东西beans.xml内容如下

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

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-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/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">

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

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-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/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">

</beans>


在写好了beans.xml之后,咱们可以开始冲上一杯茶慢慢等待,因为咱们下一步要下载一些东西

二、搭配环境

这可以说是最麻烦的一步,搭配SpringMVC环境,先把Spring以及SpringMVC相关包和jdbc包下载好(这里会存在很多问题,比如Jar包冲突或者缺失,博主在这里花了几天时间才弄好,呜呜。为了防止有人重蹈覆辙,我已将源代码和相关jar文件上传了http://download.csdn.net/detail/linchonghui888/9804739 供大家参考)

相关jar包有Spring以及SpringMVC和JDBC(因为该项目涉及到了数据库调用)


在你配置好环境以后,不要急着写代码,这是新人容易忽略的一个重要点(测试框架)本博主在忽略这个点之后写了不少代码,运行报错后不知道是框架问题还是代码问题...

在src下随便一个地方新建一个类并且带有主函数,然后在里面敲上

public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    }

}

然后就运行,如果没有报错的话,说明你jar包们大体上是比较和谐的

三、新建数据库

就博主所知,一般开发的流程是:数据库->dao->service->web  故博主也遵守这一约定

这里我们使用的是mysql

创建两张表:一张是记录用户信息,一张是记录日志信息

CREATE TABLE `t_user` (
  `user_id` int(20) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `credits` int(11) NOT NULL,
  `lastIp` varchar(255) NOT NULL,
  `lastVisit` date NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `t_login_log` (
  `loginLog_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `ip` varchar(255) NOT NULL,
  `login_datetime` date NOT NULL,
  PRIMARY KEY (`loginLog_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

在新建完数据库时,恭喜你,离成功又近了一步


四、写domain

domain就是所谓的javabean、pojo,就我的使用的感触,我觉得这应该就是Java用来传值的对象类

在这里我们也新建两个类

public class LoginLog implements Serializable{
    
    private int loginLogId;
    private int userId;
    private String ip;
    private Date loginDate;

/....以及setter和getter方法../

}

public class User implements Serializable{

    private int userId;
    private String userName;
    private String password;
    private int credits;
    private String lastIp;
    private Date lastVisit;

/....以及setter和getter方法../

}



五、写dao层

在dao包下新建两个类

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


@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 lastVisit=?,lastIp=?,credits=? "
                + " WHERE user_id =?";
        jdbcTemplate.update(sqlStr, new Object[] { user.getLastVisit(),
                user.getLastIp(),user.getCredits(),user.getUserId()});
    }
}


@Repository是注解,告诉Spring这个是dao的bean

@Autowired  是自动装配,将bean和bean关联到一起


六、service层

@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.setLoginLogId(user.getUserId());
        loginLog.setIp(user.getLastIp());
        loginLog.setLoginDate(user.getLastVisit());
    
        userDao.updateLoginInfo(user);
        loginLogDao.insertLoginLog(loginLog);  
    }
}

七、完善beans.xml

让beans自动去扫描我们的注解,所以咱们要在beans.xml里面告诉Spring那些文件里面是有注解的

 <context:component-scan base-package="lin.dao"/>

<context:component-scan base-package="lin.service"/>
<context:component-scan base-package="lin.domain"/>


Spring还对jdbc做了简单的封装,因此咱们要使用就先配置数据源

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
         destroy-method="close"
         p:driverClassName="com.mysql.jdbc.Driver"
         p:url="jdbc:mysql://localhost:3306/test"
         p:username="root"
         p:password="123456"
     />

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
             p:dataSource-ref="dataSource"/>

对数据库操作要添加事务,但是对每个操作数据库文件添加事务是繁琐并且枯燥的,因此咱们使用spring推荐的AOP编程,自动对service包里面所有的方法添加事务


<!-- 配置事务管理器 -->
       <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(* lin.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>


八、写web.xml和JSP以及*-servlet.xml

这个没什么好说的,并且怕空间不够。因此大家可以自己查看源码,不懂的地方可以留言,我会给你们详细的解答


心得:

一、在导入包的时候要花时间看看有没有重复的包,这个花不了多少时间,但是可能会给你省很多时间

二、当编译器告知你某个包查找不到时,你首先要做的是查看一下你是否真的不存在那个包(可能是编译器问题),如果你有该包而编译器没有找到,那你直接把jar包手动复制到服务器里你项目WEB-INF/lib包里面,重启服务器就好了。如果你确实不存在那个包,再去下载(最好下和你大部分包版本一样的jar包)

强烈建议新手搭建前看别人的项目(本博主就是自恃清高才导致了花了好几天时间才搭建好第一个SpringMVC,其中jar包冲突、服务器缓存什么的把博主折磨的不要不要的,差点抑郁)

补充:本博主表达能力和水平有限,故文中如果有错误的地方请大方指出,大家一起成长,一起进步!


2 0
原创粉丝点击