第一有一个web.xml文件。本课程框架为因全注解的SpringMVC+Spring4.2+hibernate4.3

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.

完目录结构使下图:

365体育网投 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包

 

365体育网投 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的注释只能在Spring的容器。也正好因为如此,事务的配备要写在Spring的容器。

下一场是对准范视图名称的分析,在伸手时模型视图名称添加前后缀(前缀是于控制器里返回的视图的父目录,此处配置的凡给容器在WEB-INF/view/下找寻对应之视图;后缀是给视图名称追加后缀名,此处配置的是jsp后缀)

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

布CommonsMultpartResolver,上传文件之时刻如果为此到CommonsMultpartResolver,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安装:

365体育网投 3

自然,你不设置为是足以的,本档好经hibernate反为创造db和发明,但多少没法创建,而且密码我们应用MD5加密,所以,为了省事,建议实行以下脚本,这个脚论是都包含了创造DB的了。

 

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

365体育网投 4

配备如下:

365体育网投 5

要根据自己的实际上情况修改。

 

下一场是运行起来:

365体育网投 6

在意说明的凡,启动自动扫描,spring会在指定的包下(例如我此是controller包),自动扫描标注@Controller的类似

代码下载365体育网投: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整合框架,基于注解。
本教程框架为根据全注解…

365体育网投 7

 

 365体育网投 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从删库到跑路,哈哈哈