demo,2

1.开立一个动态的web工程

遵照全注明的SpringMVC+Spring4.2+hibernate4.3框架搭建,

2.导入springMvc所待的jar包(那里可以错过网上搜,资源来不少)

概述

从0到1使得你搭建spring+springMVC+hibernate整合框架,基于注脚。
本教程框架为按照全表明的SpringMVC+Spring4.2+hibernate4.3,开发工具为myEclipse.

前少管辖就是不详细描述了,前面才是体面代码~

详细

先是发出一个web.xml文件,这多少个属于万分布局文件,由于要写login,里面大概布置一下核心条件就是足以

代码下载:http://www.demodashi.com/demo/10217.html

随课程框架为依照全评释的SpringMVC+Spring4.2+hibernate4.3,开发工具为myEclipse.

一体化目录结构要下图:

图片 1

日前在挑SpringMVC框架,现将成果都记录下来,免得前学后忘。在此之前用的框架一向是S2SH,一直苦于要安排一堆的配置文件,自从接触SpringMVC,发现顿时才是自己一贯怀想要的框架,基于全声明,开发过程遭到零安排,实在快哉。此教程非凡适合零基础的口上回归正题,基于全注明驱动之SpringMVC+Spring4.2+hibernate4.3框架搭建(整合)过程如下,:

开发工具为myEclipse

 

率先步:新建一个web项目

在eclipse中初修一个web项目,略。

 

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
     <servlet-name>springmvc</servlet-name>
     <url-pattern>/</url-pattern>
  </servlet-mapping>

仲步:出席所用的jar包

 

图片 2

jar包下载地址:http://download.csdn.net/detail/qq\_33556185/9472726

在的这么些被Dispatcher
Servlet,可以按照servlet-name找到相应之粗布置文件,也虽然是布spring
MVC的公文

老三步:接下大家初始SpringMVC容器的配置

 

为分工明确,我们以SpringMVC的部署单独写在spring-servlet.xml里,Spring的布局写于spring-common.xml(事务、数据源、sessionFactory等等)里。

spring-common.xml和spring-servlet.xml先参与如下schemal

<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:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:util="http://www.springframework.org/schema/util"  
    xmlns:websocket="http://www.springframework.org/schema/websocket"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
                    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd  
                    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
                    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  
                    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd  
                    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

 

然后spring容器的安排优先拖,先来安排springMVC(spring-servlet.xml)的部署

每当schemal的结尾处参与这同词:default-autowire=”byName”
,依赖注入将因name自动装配。

联网下启动讲明驱动的SpringMVC效率:

<mvc:annotation-driven />

 

举目四望注解包(在SpringMVC的器皿里,只扫描Controller注明就推行了)

<context:component-scan base-package="com.mvc.rest"  
        use-default-filters="false">  
        <context:include-filter type="annotation"  
            expression="org.springframework.stereotype.Controller" />  
</context:component-scan>

use-default-filters默认为true,默认会扫描@Component、@Controller、@Repository、@Service的讲明,在这里只扫描@Controller表明是为,SpringMVC的容器没有事情之力,所以扫描@Repository、@Service(Service)的注释只好放在Spring的容器。也正好以这么,事务的配备要描绘于Spring的容器。

然后是本着范视图名称的分析,在呼吁时模型视图名称添加前后缀(前缀是起控制器里重返的视图的父目录,此处配置的凡为容器在WEB-INF/view/下找寻对应之视图;后缀是给视图名称追加后缀名,此处配置的是jsp后缀)

<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver"  p:prefix="/WEB-INF/view/" p:suffix=".jsp" />

配备Commons(Commons)MultpartResolver,上传文件的当儿如果用到康芒斯(Commons)MultpartResolver,maxUploadSize设置及污染文书的深浅限制,上传文件要事先安排是解析器。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
     <property name="maxUploadSize" value="10485760" />  
</bean>

布login视图解析,在登录拦截器里,校验不登录的话,要过反到登录页面,然后由login页面在WEB-INF目录下,所以设置过反至login.jsp会跳转然则去,在这里安装如下,在回来此view-name的地方,容器便不会师作Controller的门道,当作视图的路线跳转,在拦截器里虽可超越反到login页面(此布局告诉容器,这不是一个controller的措施的途径,而是一个视图的名称,请当作视图处理)。

<mvc:view-controller path="/" view-name="login" />

拦截器的布为是放在SpringMVC的容器里,拦截器将来的稿子里还详尽解释。

至此spring-servlet.xml的布置就结束了,spring-servlet.xml的全文如下:

<?xml version="1.0" encoding="UTF-8"?>  
<!--suppress ALL -->  
<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:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:util="http://www.springframework.org/schema/util"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd  
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"  
    default-autowire="byName">  
    <mvc:annotation-driven />  
    <!-- controller包(自动注入) -->  
    <context:component-scan base-package="com.mvc.rest" use-default-filters="false">  
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />  
    </context:component-scan>  
    <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
        p:prefix="/WEB-INF/view/" p:suffix=".jsp" />  
    <mvc:view-controller path="/" view-name="login" />  
    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="maxUploadSize" value="10485760" />  
    </bean>  
    <!-- 配置拦截器, 多个拦截器,顺序执行  
        <mvc:interceptors>  
           <mvc:interceptor>  
            <mvc:mapping path="/*" />  
           <bean class="com.mvc.rest.interceptor.CommonInterceptor"></bean>   
     </mvc:interceptor> </mvc:interceptors> -->  
</beans>

 

当web.xml文件同级目录下新建springmvc-servlet.xml文件,上边是springmvc-servlet.xml文件被的情

季步:我们配备web.xml

 

优先安排CharacterEncodingFilter编码过滤器,此过滤器必须在配置文件的无限下面,有差不六只过滤器的时节,也当放在第一各。encoding目标编码,forceEncoding设为true,会忽略请求来源之编码,强制行使encoding设置的编码。

<filter>  
       <filter-name>CharacterEncodingFilter</filter-name>  
       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
       <init-param>  
           <param-name>encoding</param-name>  
           <param-value>utf-8</param-value>  
       </init-param>  
       <init-param>  
           <param-name>forceEncoding</param-name>  
           <param-value>true</param-value>  
       </init-param>  
</filter>  
<filter-mapping>  
       <filter-name>CharacterEncodingFilter</filter-name>  
       <url-pattern>/*</url-pattern>  
</filter-mapping>

下一场配置ContextLoaderListener,此监听用来加载大家形容的安排文件

<listener>  
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener>

下一场加载Spring配置文件

<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>  
        classpath*:/spring/spring-common.xml  
    </param-value>  
</context-param>

对接下去就是安排SpringMVC的中坚Servlet,所有请求都设优先经DispatcherServlet,然后举办分发到对应之控制器。该Servlet须首先单被加载,且当起头化的上去加载SpringMVC的布局文件——spring-servlet.xml

<servlet>  
    <servlet-name>spring-mvc</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <init-param>  
        <description>spring mvc</description>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath*:/spring/spring-servlet.xml</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
</servlet>

然后设置DispatcherServlet拦截的伏乞,此处的servlet-name,即凡者配置的DispatcherServlet的name,url-pattern设置也斜杠,则会拦所有请求,也就是静态资源html、css、js也一向伸手。

<servlet-mapping>  
<servlet-name>spring-mvc</servlet-name>  
<url-pattern>/</url-pattern>  
</servlet-mapping>

啊之,大家得安装,哪些资源不举办拦截

<servlet-mapping>  
      <servlet-name>default</servlet-name>  
      <url-pattern>/html/*</url-pattern>  
</servlet-mapping>  
<servlet-mapping>  
      <servlet-name>default</servlet-name>  
      <url-pattern>/js/*</url-pattern>  
</servlet-mapping>  
<servlet-mapping>  
       <servlet-name>default</servlet-name>  
      <url-pattern>/css/*</url-pattern>  
</servlet-mapping>  
     <servlet-mapping>  
<servlet-name>default</servlet-name>  
      <url-pattern>/images/*</url-pattern>  
</servlet-mapping>

 

交者,SpringMVC就可以正常使用了。

迎接页面的设置,原本此处只好设置视图名,*.jsp或者*.html,因为在spring-servlet.xml里安装了视图解析:<mvc:view-controller
path=”/” view-name=”login”
/>,所以,此处安装也welcome-file设置也login,容器便会以这些分析为视图login.jsp,绕了WEB-INFO下的资源无法直接看的限。

<welcome-file-list>  
     <welcome-file>login</welcome-file>  
</welcome-file-list>

俺们尚好装error-page的页面

<error-page>  
   <error-code>404</error-code>  
   <location>/html/error/404.html</location>  
</error-page>  
<error-page>  
   <error-code>500</error-code>  
   <location>/html/error/500.html</location>  
</error-page>

为集成hibernate,我们还要配置OpenSessionInViewFilter,此过滤器会将Hibernate的Session和同样糟完整的伸手过程绑定起来,事务控制,必须安排是过滤器。

<filter>  
    <filter-name>openSession</filter-name>  
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
 </filter>  
 <filter-mapping>  
<filter-name>openSession</filter-name>  
<url-pattern>/*</url-pattern>  
 </filter-mapping>

总体的web.xml的部署如下:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    id="WebApp_ID" version="3.0">  
    <filter>  
        <filter-name>CharacterEncodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>utf-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>CharacterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
            classpath*:/spring/spring-common.xml  
        </param-value>  
    </context-param>  
    <servlet>  
        <servlet-name>spring-mvc</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <description>spring mvc</description>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath*:/spring/spring-servlet.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <filter>  
        <filter-name>openSession</filter-name>  
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>openSession</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <servlet-mapping>  
        <servlet-name>spring-mvc</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>login</welcome-file>  
    </welcome-file-list>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/html/*</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/js/*</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/css/*</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/images/*</url-pattern>  
    </servlet-mapping>  
    <error-page>  
        <error-code>404</error-code>  
        <location>/html/error/404.html</location>  
    </error-page>  
    <error-page>  
        <error-code>500</error-code>  
        <location>/html/error/500.html</location>  
    </error-page>  
</web-app>

 

第五步:配置spring-common.xml(数据源、事务、sessionFactory)

布局数据源jdbc.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver  
jdbc.url=jdbc\:mysql\://121.40.90.125\:3306/test  
jdbc.username=root  
jdbc.password=exceptoin882465\[email protected]\#

解析properties:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
<bean id="dataSource" destroy-method="close"<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
<property name="dataSource" ref="dataSource" />  
<property name="hibernateProperties">  
    <props>  
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
            <prop key="hibernate.hbm2ddl.auto">update</prop>  
            <prop key="hibernate.show_sql">true</prop>  
            <prop key="hibernate.format_sql">true</prop>  
    </props>  
</property>  
<!-- 注解方式配置 -->  
<property name="packagesToScan">  
  <list>  
    <value>com.mvc.rest.entity</value>  
 </list>  
</property>  
 </bean>

packagesToScan扫描我们的hibernate实体文件。

最终安排事务

<bean id="txManager"  
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory" />  
    </bean>  
    <tx:advice id="txAdvice" transaction-manager="txManager">  
        <tx:attributes>  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="add*" propagation="REQUIRED" />  
            <tx:method name="edit*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="register*" propagation="REQUIRED" />  
            <tx:method name="all" propagation="REQUIRED" />  
            <tx:method name="changePassword*" propagation="REQUIRED" />  
            <tx:method name="restPassword*" propagation="REQUIRED" />  
            <tx:method name="authorize*" propagation="REQUIRED" />  
            <tx:method name="send*" propagation="REQUIRED" />  
            <tx:method name="init*" propagation="REQUIRED" />  
            <!-- <tx:method name="*" read-only="true"/> -->  
        </tx:attributes>  
    </tx:advice>  
    <aop:config>  
        <aop:pointcut id="serviceOperation"  
            expression="execution(* com.mvc.rest.service.impl.*.*(..))" />  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
</aop:config>

完的spring-common.xml的安排如下:

<?xml version="1.0" encoding="UTF-8"?>  
<!--suppress ALL -->  
<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:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:util="http://www.springframework.org/schema/util"  
    xmlns:websocket="http://www.springframework.org/schema/websocket"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd  
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">  
    <context:component-scan base-package="com.mvc.rest" />  
    <!-- properties文件解析器 -->  
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="locations">  
            <value>classpath:jdbc.properties</value>  
        </property>  
    </bean>  
    <!-- 配置数据源 -->  
    <bean id="dataSource" destroy-method="close"  
        class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName" value="${jdbc.driverClassName}" />  
        <property name="url" value="${jdbc.url}" />  
        <property name="username" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />  
    </bean>  
    <bean id="sessionFactory"  
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>  
            </props>  
        </property>  
        <!-- 注解方式配置 -->  
        <property name="packagesToScan">  
            <list>  
                <value>com.mvc.rest.entity</value>  
            </list>  
        </property>  
    </bean>  
    <bean id="txManager"  
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory" />  
    </bean>  
    <tx:advice id="txAdvice" transaction-manager="txManager">  
        <tx:attributes>  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="add*" propagation="REQUIRED" />  
            <tx:method name="edit*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="register*" propagation="REQUIRED" />  
            <tx:method name="all" propagation="REQUIRED" />  
            <tx:method name="changePassword*" propagation="REQUIRED" />  
            <tx:method name="restPassword*" propagation="REQUIRED" />  
            <tx:method name="authorize*" propagation="REQUIRED" />  
            <tx:method name="send*" propagation="REQUIRED" />  
            <tx:method name="init*" propagation="REQUIRED" />  
            <!-- <tx:method name="*" read-only="true"/> -->  
        </tx:attributes>  
    </tx:advice>  
    <aop:config>  
        <aop:pointcut id="serviceOperation"  
            expression="execution(* com.mvc.rest.service.impl.*.*(..))" />  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
    </aop:config>  
</beans>

顶之,基于全表明的SpringMVC+Spring4.2+hibernate4.3框架搭建好功告成。

<?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:mvc="http://www.springframework.org/schema/mvc"
    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
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!--默认的注解映射的支持 -->
    <mvc:annotation-driven/>
    <!--启用自动扫描 -->
    <context:component-scan base-package="controller"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

第六步:运行

DB安装:

图片 3

本,你免安装也是可的,本项目方可通过hibernate反为创造db和阐发,但数目没法创设,而且密码大家运用MD5加密,所以,为了方便,提出实行以下脚本,那多少个脚论是既包含了创办DB的了。

 

DB安装后,需要配置下项目的jdbc连接:

图片 4

布局如下:

图片 5

央依照自己之实际上意况修改。

 

然后是运作起来:

图片 6

顾表达的凡,启动自动扫描,spring会在指定的包下(例如我这里是controller包),自动扫描标注@Controller的类

代码下载:http://www.demodashi.com/demo/10217.html

prefix指的是回到的值为电动加一个前缀,同理suffix指的就是后缀

流动:本文作品权归作者,由demo大师发布,拒绝转载,转载需要作者授权

 

http://www.bkjia.com/Javabc/1305479.htmlwww.bkjia.comtruehttp://www.bkjia.com/Javabc/1305479.htmlTechArticle基于全注解的SpringMVC+Spring4.2+hibernate4.3框架搭建,
概述 从0到1使得您搭建spring+springMVC+hibernate整合框架,基于表明。
本教程框架为基于全注明…

图片 7

 

 图片 8

盼此也是够忙碌了,下边是叫起之完全目录,上面起头勾画逻辑代码,先打loginController起首

@Controller
public class LoginController {
    @RequestMapping(value="/",method=RequestMethod.GET)
    public String sayHello(){
        //model.addAttribute("msg", "Hello,World!");
        return "login";
    }

说下边代码,@Controller,标注是仿佛是Controller类,spring会自动举行围观,@Request
Mapping中的value指的是url中之地点后缀,设置成/的目标自然是为着便于啊,

按部就班启动工程时,url只需要输入什么localhost:8080/项目名为,它便晤面自动跳反到login页面;method指的是来之url是post请求仍然get请求

return的凡login字符串,大家还记上边说之prefix了咔嚓,它就是会师把您的url自动拼接上,完整路径就是是下面是

/WEB-INF/jsp/login.jsp

 接下来看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>login</title>
</head>
<body>
    <form action="login" method="post">
        用户名:<input type="text" name="username"/><br/>
        密&nbsp;&nbsp;码:<input type="password" name="password"/>
        <input type="submit" value="登陆"/>
        <a href="regist">注册</a>
    </form>
</body>
</html>

此的action再次来到的凡login,Controller会自动捕获到这请,于是当login
Controller中只要产生一个计来捕获那一个要

@RequestMapping(value="login",method=RequestMethod.POST)
    public String login(Model model, // 向前台页面传的值放入model中
            HttpServletRequest request){ // 从前台页面取得的值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String user_name = LoginCheck.check(username, password);
        if(user_name != null && user_name != ""){
            model.addAttribute("msg", user_name);
            return "success";
        }else{
            return "login2";
        }
    }

登陆嘛,当然假诺有表达,于是便时有发生矣LoginCheck,不多说,上代码

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dao.Dao;

public class LoginCheck {

    public static String check(String username,String password){
        try {
            Connection conn = Dao.getConnection();
            PreparedStatement p = conn.prepareStatement("select * from user_t where user_name=? and password=?");
            p.setString(1, username);
            p.setString(2, password);
            ResultSet rs = p.executeQuery();
            if(rs.next()){
                String user_name = rs.getString("user_name");
                Dao.close(rs, p, conn);
                return user_name;
            }
            Dao.close(rs, p, conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

向阳数据库查询就要生DAO啦,Dao网上还暴发,我的即是在网上随便找找一个改动就用了~

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Dao {
    // 获取数据库连接
    public static Connection getConnection(){

        Connection conn = null;
        String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong";
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","数据库密码");//大家分享代码的时候也不要暴露自己的数据库密码,这样是非常不安全的
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
            System.out.println("数据库驱动加载出错");
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据库出错");
        }
        return conn;
    }
     //关闭相关通道
    public static void close(ResultSet rs,PreparedStatement p,Connection conn)
    {
        try
        {
            if(!rs.isClosed()){
                rs.close();
            }
            if(!p.isClosed()){
                p.close();
            }
            if(!conn.isClosed()){
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据关闭出错");
        }
    }
    //关闭相关通道
    public static void close(PreparedStatement p,Connection conn)
    {
        try
        {
            if(!p.isClosed()){
                p.close();
            }
            if(!conn.isClosed()){
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据关闭出错");
        }
    }
}

吓了,如若查询的结果分外上数据库中询问及之价值了,那么即便得跨反到success页面了,success.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>
    登陆成功!
    欢迎~${msg};
</body>
</html>

login大功告成,接下的报页面和是道理相似,我未多废话了,把代码附上供我们参考

首先是regist.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>
    <form action="registSuccess" method="Post">
        用户名:<input type="text" name="username"/>
        密&nbsp;&nbsp;码<input type="text" name="password"/>
        年&nbsp;&nbsp;龄<input type="number" name="age"/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

通下去是RegistController

package controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import logic.RegistCheck;

@Controller
public class RegistController {
    @RequestMapping(value="regist",method=RequestMethod.GET)
    public String regist(){
        return "regist";
    }

    @RequestMapping(value="registSuccess",method=RequestMethod.POST)
    public String registSuccess(HttpServletRequest request,Model model){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String age = request.getParameter("age");

        if(RegistCheck.registCheck(username, password,age)){
            model.addAttribute("username", username);
            return "login";
        }else{
            return "regist2";
        }
    }
}

搭下是RegistCheck

 

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;

import dao.Dao;

public class RegistCheck {

    public static boolean registCheck(String username,String password,String age){
        String user_name = LoginCheck.check(username, password);
        if(user_name == null || user_name == ""){
            try {
                Connection conn = Dao.getConnection();
                PreparedStatement p = conn.prepareStatement("insert user_t(user_name,password,age) VALUES (?,?,?);");
                p.setString(1, username);
                p.setString(2, password);
                p.setString(3, age);
                p.executeUpdate();
                System.out.println("注册成功");
                Dao.close(p, conn);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}

再有一个registSuccess.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>
    注册成功!
</body>
</html>

吓了,现在完结login和报页面还写好了,新人刚到集团之时候异常容易碰到这样的粗练,哈哈哈说基本上矣,喜欢就点赞哈

接转载,转载请注解出处~

Java于上学及放弃,MySQL从删库到跑路,哈哈哈

 

相关文章

admin

网站地图xml地图