使用IntelliJ IDEA和Maven管理搭建Web开发环境(以Spring MVC为例)(二)

前言:在使用IntelliJ IDEA和Maven管理搭建Web开发环境(以Spring MVC为例)(一)中已经介绍了如何对web基础环境进行搭建,这里主要演示,如何对spring环境进行搭建,然后组合成一个完整的spring MVC Web项目。


Spring环境的搭建

1.通过Maven可以轻松的配置,spring环境,具体pom文件如下所示

<!--设置版本信息-->
    <properties>
        <file.encoding>UTF-8</file.encoding>
        <spring.version>4.2.1.RELEASE</spring.version>
        <mysql.version>5.1.20</mysql.version>
        <servlet.version>2.5</servlet.version>
        <commons-dbcp.version>1.4</commons-dbcp.version>
        <commons-pool.version>1.4</commons-pool.version>
        <aspectj.version>1.8.1</aspectj.version>
    </properties>
    <!--定义依赖-->
    <dependencies>
        <!--spring相关依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <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-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
        <!-- 数据库驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- 连接池依赖-->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${commons-dbcp.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>${commons-pool.version}</version>
        </dependency>
        <!-- web类库依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- 日志依赖-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>

        <plugins>
            <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>
View Code

注:pom文件中除了spring所需jar包,还对数据库驱动等相关信息,进行了依赖配置。

2.在Resource目录下创建spring配置文件,如下图所示

3.由于需演示一个相对完整的Spring MVC Web项目,因此建立如下所示的目录结构

注:这里主要演示一个登录界面,当登录成功后,进入主界面(为了简单这里就不演示日志操作了)。因此接下来需要创建一个数据库。

4.创建数据库

DROP DATABASE IF EXISTS springtestdb;
CREATE DATABASE springtestdb DEFAULT CHARACTER SET utf8;
USE springtestdb;
##建表
CREATE TABLE `t_user` (
  `user_id` int(11) NOT NULL auto_increment,
  `user_name` varchar(30) default NULL,
  `password` varchar(32) default NULL,
    PRIMARY KEY  (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

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

5.编写相应代码

User:

public class User implements Serializable
{
    private int userid;
    private String username;
    private String password;

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

    @Override
    public String toString()
    {
        return "User[" +
                "userid=" + userid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ']';
    }
}
View Code

UserDao:

@Repository("userDao")
public class UserDao
{
    private static Logger logger = Logger.getLogger(UserDao.class);
    //如果直接使用注解进行属性的修饰,可以不用set函数
    @Resource(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取匹配用户的个数
     * @param username
     * @param password
     * @return
     */
    public int getMatchCount(String username, String password)
    {
        String querysql = "select count(*) from t_user where user_name=? and password=?";

        int rows = jdbcTemplate.queryForObject(querysql, Integer.class, username, password);

        logger.info("rows=" + rows);
        return rows;
    }
}
View Code

UserService:

@Transactional
@Service("userService")
public class UserService
{
    //直接通过在属性上进行配置注入,就可以不用写set方法了
    @Resource(name = "userDao")
    private UserDao userDao;

    @Resource(name="loginlogDao")
    private LoginLogDao loginLogDao;

    /**
     * 判断用户名与密码是否正确
     * @param useranme
     * @param password
     * @return
     */
    public boolean hasMatchUser(String useranme,String password)
    {
        int matchcount=userDao.getMatchCount(useranme,password);
        return matchcount>0;
    }
}
View Code

 LoginController:

@Controller("loginController")
public class LoginController
{
    private static Logger logger=Logger.getLogger(LoginController.class);

    @Resource(name = "userService")
    private UserService userService;

    @RequestMapping(value = "/index.html") //默认会 访问index.html页面
    public String loginPage()
    {
        return "login";
    }

    @RequestMapping(value = "/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand)
    {
        String username=loginCommand.getUsername();
        String password=loginCommand.getPassword();
        boolean isvaliduser = userService.hasMatchUser(username, password);

        if (!isvaliduser)
        {
            return new ModelAndView("login", "error", "用户名或密码错误");
        }
        else
        {
            logger.info("username="+username+" password="+password);
          
        request.getSession().setAttribute("user", user);
        return new ModelAndView("main");
            
        }

    }

}
View Code

LoginCommand:

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;
    }
}
View Code

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>
View Code

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},欢迎您!
</body>
</html>
View Code

6.进行相应配置

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">
    <!-- 开启注解-->
    <context:component-scan base-package="com.springlearning"/>

    <!-- 配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close"
          p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3307/springtestdb"
          p:username="root"
          p:password=""/>

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

    <!-- 配置jdbc事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <aop:config proxy-target-class="true">
        <aop:pointcut id="serviceMethod"
                      expression="(execution(* com.springlearning.service..*(..)))" />
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

</beans>
View Code

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
         version="2.5" id="webapp_id">
   <!--配置监听器 --> <!--以便在服务器启动的时候,加载spring配置文件-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--配置spring配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springconfig.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>learning</servlet-name>
        <servlet-class>
           org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>3</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>learning</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file> <!--这里配置的默认页面和LoginController中对应名称需要一致-->
    </welcome-file-list>
    
</web-app>
View Code

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

    <!-- 开启web包的spring注解-->
    <context:component-scan base-package="com.springlearning.web"/>

    <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:viewClass="org.springframework.web.servlet.view.JstlView"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp"/>

</beans>
View Code

至此,编写和配置完所有文件,下面进行发布(不要忘记Put into Output Root,具体步骤请参看看上一篇文章)。当正确输入用户名和密码后,效果如下:

至此通过IDEA与Maven搭建Spring MVC Web项目成功。


by Shawn Chen,2018.1.11日,下午。

posted @ 2018-01-11 16:14  developer_chan  阅读(1225)  评论(2编辑  收藏  举报