首页 > 代码库 > springmvc的第一个程序
springmvc的第一个程序
文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。
web.xml配置:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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_2_5.xsd" id="WebApp_ID" version="2.5"> 3 <display-name>s3h3</display-name> 4 <context-param> 5 <param-name>contextConfigLocation</param-name> 6 <param-value>classpath:applicationContext*.xml</param-value> 7 </context-param> 8 <listener> 9 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 10 </listener> 11 12 <servlet> 13 <servlet-name>spring</servlet-name> 14 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 15 <load-on-startup>1</load-on-startup> 16 </servlet> 17 <servlet-mapping> 18 <servlet-name>spring</servlet-name> <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller --> 19 <url-pattern>*.do</url-pattern> 20 </servlet-mapping> 21 <welcome-file-list> 22 <welcome-file>index.jsp</welcome-file> 23 </welcome-file-list> 24 </web-app>
spring-servlet.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 6 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 7 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 9 10 <context:annotation-config /> 11 <!-- 把标记了@Controller注解的类转换为bean --> 12 <context:component-scan base-package="com.mvc.controller" /> 13 <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> 14 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 15 16 <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> 17 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 18 p:prefix="/WEB-INF/view/" p:suffix=".jsp" /> 19 20 <bean id="multipartResolver" 21 class="org.springframework.web.multipart.commons.CommonsMultipartResolver" 22 p:defaultEncoding="utf-8" /> 23 </beans>
applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 9 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 10 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 11 12 <context:annotation-config /> 13 <context:component-scan base-package="com.mvc" /> <!-- 自动扫描所有注解该路径 --> 14 15 <context:property-placeholder location="classpath:/hibernate.properties" /> 16 17 <bean id="sessionFactory" 18 class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 19 <property name="dataSource" ref="dataSource" /> 20 <property name="hibernateProperties"> 21 <props> 22 <prop key="hibernate.dialect">${dataSource.dialect}</prop> 23 <prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop> 24 <prop key="hibernate.hbm2ddl.auto">update</prop> 25 </props> 26 </property> 27 <property name="packagesToScan"> 28 <list> 29 <value>com.mvc.entity</value><!-- 扫描实体类,也就是平时所说的model --> 30 </list> 31 </property> 32 </bean> 33 34 <bean id="transactionManager" 35 class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 36 <property name="sessionFactory" ref="sessionFactory" /> 37 <property name="dataSource" ref="dataSource" /> 38 </bean> 39 40 <bean id="dataSource" 41 class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 42 <property name="driverClassName" value="http://www.mamicode.com/${dataSource.driverClassName}" /> 43 <property name="url" value="http://www.mamicode.com/${dataSource.url}" /> 44 <property name="username" value="http://www.mamicode.com/${dataSource.username}" /> 45 <property name="password" value="http://www.mamicode.com/${dataSource.password}" /> 46 </bean> 47 <!-- Dao的实现 --> 48 <bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"> 49 <property name="sessionFactory" ref="sessionFactory" /> 50 </bean> 51 <tx:annotation-driven transaction-manager="transactionManager" /> 52 <tx:annotation-driven mode="aspectj"/> 53 54 <aop:aspectj-autoproxy/> 55 </beans>
hibernate.properties 数据库连接配置
1 dataSource.password=123 2 dataSource.username=root 3 dataSource.databaseName=test 4 dataSource.driverClassName=com.mysql.jdbc.Driver 5 dataSource.dialect=org.hibernate.dialect.MySQL5Dialect 6 dataSource.serverName=localhost:3306 7 dataSource.url=jdbc:mysql://localhost:3306/test 8 dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password} 9 dataSource.hbm2ddl.auto=update
配置已经完成,下面开始例子
先在数据库建表,例子用的是mysql数据库
CREATE TABLE `test`.`student` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `psw` varchar(45) NOT NULL, PRIMARY KEY (`id`) )
建好表后,生成实体类
package com.mvc.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "student") public class Student implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Integer id; @Column(name = "name") private String user; @Column(name = "psw") private String psw; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPsw() { return psw; } public void setPsw(String psw) { this.psw = psw; } }
Dao层实现
package com.mvc.dao; import java.util.List; public interface EntityDao { public List<Object> createQuery(final String queryString); public Object save(final Object model); public void update(final Object model); public void delete(final Object model); }
DAO实现层:
package com.mvc.dao; import java.util.List; import org.hibernate.Query; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao{ public List<Object> createQuery(final String queryString) { return (List<Object>) getHibernateTemplate().execute( new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { Query query = session.createQuery(queryString); List<Object> rows = query.list(); return rows; } }); } public Object save(final Object model) { return getHibernateTemplate().execute( new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { session.save(model); return null; } }); } public void update(final Object model) { getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { session.update(model); return null; } }); } public void delete(final Object model) { getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { session.delete(model); return null; } }); } }
Dao在applicationContext.xml注入
<bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。
开始写view页面,WEB-INF/view下新建页面student.jsp,WEB-INF/view这路径是在spring-servlet.xml文件配置的,你可以配置成其它,也可以多个路径。
student.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="/include/head.jsp"%> <!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> <script language="javascript" src="http://www.mamicode.com/