<?xml version= " 1.0 " encoding= " UTF-8 " ?> |
03 | <display - name> s3h3 </display - name> |
05 | <param - name> contextConfigLocation </param - name> |
06 | <param - value> classpath:applicationContext * .xml </param - value> |
09 | <listener - class > org.springframework.web.context.ContextLoaderListener </listener - class > |
13 | <servlet - name> spring </servlet - name> |
14 | <servlet - class > org.springframework.web.servlet.DispatcherServlet </servlet - class > |
15 | <load - on - startup> </load - on - startup> |
18 | <servlet - name> spring </servlet - name> |
19 | <!-- 这里在配成spring,下边也要写一个名为spring - servlet.xml的文件,主要用来配置它的controller --> |
20 | <url - pattern>* . do </url - pattern> |
22 | <welcome - file - list> |
23 | <welcome - file> index.jsp </welcome - file> |
24 | </welcome - file - list> |
spring-servlet,主要配置controller的信息
01 | <?xml version= "1.0" encoding= "UTF-8" ?> |
05 | xsi:schemaLocation="http: |
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" /> |
16 | <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> |
17 | <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver" |
18 | p:prefix= "/WEB-INF/view/" p:suffix= ".jsp" /> |
20 | <bean id= "multipartResolver" |
21 | class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" |
22 | p:defaultEncoding= "utf-8" /> |
applicationContext.xml代码
01 | <?xml version= "1.0" encoding= "UTF-8" ?> |
12 | <context:annotation-config /> |
13 | <context:component-scan base- package = "com.mvc" /> <!-- 自动扫描所有注解该路径 --> |
15 | <context:property-placeholder location= "classpath:/hibernate.properties" /> |
17 | <bean id= "sessionFactory" |
18 | class = "org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" > |
19 | <property name= "dataSource" ref= "dataSource" /> |
20 | <property name= "hibernateProperties" > |
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> |
27 | <property name= "packagesToScan" > |
29 | <value> com.mvc.entity </value> <!-- 扫描实体类,也就是平时所说的model --> |
34 | <bean id= "transactionManager" |
35 | class = "org.springframework.orm.hibernate3.HibernateTransactionManager" > |
36 | <property name= "sessionFactory" ref= "sessionFactory" /> |
37 | <property name= "dataSource" ref= "dataSource" /> |
41 | class = "org.springframework.jdbc.datasource.DriverManagerDataSource" > |
42 | <property name= "driverClassName" value= "${dataSource.driverClassName}" /> |
43 | <property name= "url" value= "${dataSource.url}" /> |
44 | <property name= "username" value= "${dataSource.username}" /> |
45 | <property name= "password" value= "${dataSource.password}" /> |
48 | <bean id= "entityDao" class = "com.mvc.dao.EntityDaoImpl" > |
49 | <property name= "sessionFactory" ref= "sessionFactory" /> |
51 | <tx:annotation-driven transaction-manager= "transactionManager" /> |
52 | <tx:annotation-driven mode= "aspectj" /> |
54 | <aop:aspectj-autoproxy /> |
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: |
8 | dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password} |
9 | dataSource.hbm2ddl.auto=update |
配置已经完成,下面开始例子
先在数据库建表,例子用的是mysql数据库
1 | CREATE TABLE `test`.`student` ( |
2 | `id` int ( 10 ) unsigned NOT NULL AUTO_INCREMENT, |
3 | `name` varchar( 45 ) NOT NULL, |
4 | `psw` varchar( 45 ) NOT NULL, |
建好表后,生成实体类
01 | packagecom.mvc.entity; |
03 | import java.io.Serializable; |
05 | import javax.persistence.Basic; |
06 | import javax.persistence.Column; |
07 | import javax.persistence.Entity; |
08 | import javax.persistence.GeneratedValue; |
09 | import javax.persistence.GenerationType; |
10 | import javax.persistence.Id; |
11 | import javax.persistence.Table; |
14 | @Table (name= "student" ) |
15 | public class Student implements Serializable { |
16 | private static final long serialVersionUID=1L; |
18 | @Basic (optional= false ) |
19 | @GeneratedValue (strategy=GenerationType.IDENTITY) |
20 | @Column (name= "id" , nullable= false ) |
26 | public Integer getId() { |
29 | public void setId(Integer id) { |
33 | public String getUser() { |
36 | public void setUser(String user) { |
39 | public String getPsw() { |
42 | public void setPsw(String psw) { |
Dao层实现
03 | import java.util.List; |
05 | public interface EntityDao { |
06 | public List<Object> createQuery( final String queryString); |
07 | public Object save( final Object model); |
08 | public void update( final Object model); |
09 | public void delete( final Object model); |
03 | import java.util.List; |
05 | import org.hibernate.Query; |
06 | import org.springframework.orm.hibernate3.HibernateCallback; |
07 | import org.springframework.orm.hibernate3.support.HibernateDaoSupport; |
09 | public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao { |
10 | public List<Object> createQuery( final String queryString) { |
11 | return (List<Object>) getHibernateTemplate().execute( |
12 | new HibernateCallback<Object>() { |
13 | public Object doInHibernate(org.hibernate.Session session) |
14 | throws org.hibernate.HibernateException { |
15 | Query query=session.createQuery(queryString); |
16 | List<Object> rows=query.list(); |
21 | public Object save( final Object model) { |
22 | return getHibernateTemplate().execute( |
23 | new HibernateCallback<Object>() { |
24 | public Object doInHibernate(org.hibernate.Session session) |
25 | throws org.hibernate.HibernateException { |
31 | public void update( final Object model) { |
32 | getHibernateTemplate().execute( new HibernateCallback<Object>() { |
33 | public Object doInHibernate(org.hibernate.Session session) |
34 | throws org.hibernate.HibernateException { |
35 | session.update(model); |
40 | public void delete( final Object model) { |
41 | getHibernateTemplate().execute( new HibernateCallback<Object>() { |
42 | public Object doInHibernate(org.hibernate.Session session) |
43 | throws org.hibernate.HibernateException { |
44 | session.delete(model); |
Dao在applicationContext.xml注入
1 | <bean id= "entityDao" class = "com.mvc.dao.EntityDaoImpl" > |
2 | <property name= "sessionFactory" ref= "sessionFactory" /> |
Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。
开始写view页面,WEB-INF/view下新建页面student.jsp,WEB-INF/view这路径是在spring-servlet.xml文件配置的,你可以配置成其它,也可以多个路径。student.jsp代码
01 | <% @ page language= "java" contentType= "text/html;charset=UTF-8" |
02 | pageEncoding= "UTF-8" %> |
03 | <% @ include file= "/include/head.jsp" %> |
07 | <meta http-equiv= "Content-Type" content= "text/html;charset=UTF-8" > |
09 | <script language= "javascript" src="<%=request.getContextPath()%><!-- |
10 | /script/jquery.min.js"> |
13 | table{ border-collapse:collapse; } |
14 | td{ border:1px solid #f00; } |
15 | --></style><style mce_bogus= "1" >table |
student_add.jsp
01 | <% @ page language= "java" contentType= "text/html;charset=UTF-8" |
02 | pageEncoding= "UTF-8" %> |
03 | <% @ include file= "/include/head.jsp" %> |
07 | <meta http-equiv= "Content-Type" content= "text/html;charset=UTF-8" > |
09 | <mce:script type= "text/javascript" ><!-- |
11 | window.location.href= "<%=request.getContextPath()%>/student.do" ; |
16 | <form method= "post" action= "<%=request.getContextPath()%>/student.do?method=save" > |
17 | <div><c:out value= "${addstate}" ></c:out></div> |
19 | <tr><td> 姓名 </td><td><input id= "user" name= "user" type= "text" /></td></tr> |
20 | <tr><td> 密码 </td><td><input id= "psw" name= "psw" type= "text" /></td></tr> |
21 | <tr><td colSpan= "2" align= "center" ><input type= "submit" value= "提交" /><input type= "button" onclick= "turnback()" value= "返回" /> </td></tr> |
controller类实现,只需把注解写上,spring就会自动帮你找到相应的bean,相应的注解标记意义,不明白的,可以自己查下@Service,@Controller,@Entity等等的内容。
01 | package com.mvc.controller; |
03 | import java.util.List; |
05 | import javax.servlet.http.HttpServletRequest; |
06 | import javax.servlet.http.HttpServletResponse; |
08 | import org.apache.commons.logging.Log; |
09 | import org.apache.commons.logging.LogFactory; |
10 | import org.springframework.beans.factory.annotation.Autowired; |
11 | import org.springframework.stereotype.Controller; |
12 | import org.springframework.ui.ModelMap; |
13 | import org.springframework.web.bind.annotation.RequestMapping; |
14 | import org.springframework.web.bind.annotation.RequestMethod; |
15 | import org.springframework.web.bind.annotation.RequestParam; |
16 | import org.springframework.web.servlet.ModelAndView; |
18 | import com.mvc.entity.Student; |
19 | import com.mvc.service.StudentService; |
22 | @RequestMapping ( " /student.do " ) |
23 | public class StudentController { |
24 | protected final transient Log log=LogFactory |
25 | .getLog(StudentController. class ); |
27 | private StudentService studentService; |
28 | public StudentController(){ |
33 | public String load(ModelMap modelMap){ |
34 | List<Object> list=studentService.getStudentList(); |
35 | modelMap.put( "list" , list); |
39 | @RequestMapping (params= "method=add" ) |
40 | public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{ |
44 | @RequestMapping (params= "method=save" ) |
45 | public String save(HttpServletRequest request, ModelMap modelMap){ |
46 | String user=request.getParameter( "user" ); |
47 | String psw=request.getParameter( "psw" ); |
48 | Student st= new Student(); |
52 | studentService.save(st); |
53 | modelMap.put( "addstate" , "添加成功" ); |
56 | log.error(e.getMessage()); |
57 | modelMap.put( "addstate" , "添加失败" ); |
63 | @RequestMapping (params= "method=del" ) |
64 | public void del( @RequestParam ( "id" ) String id, HttpServletResponse response){ |
66 | Student st= new Student(); |
67 | st.setId(Integer.valueOf(id)); |
68 | studentService.delete(st); |
69 | response.getWriter().print( "{\"del\":\"true\"}" ); |
72 | log.error(e.getMessage()); |
service类实现
01 | package com.mvc.service; |
03 | import java.util.List; |
05 | import org.springframework.beans.factory.annotation.Autowired; |
06 | import org.springframework.stereotype.Service; |
07 | import org.springframework.transaction.annotation.Transactional; |
09 | import com.mvc.dao.EntityDao; |
10 | import com.mvc.entity.Student; |
13 | public class StudentService { |
15 | private EntityDao entityDao; |
18 | public List<Object> getStudentList(){ |
19 | StringBuffer sff= new StringBuffer(); |
20 | sff.append( "select a from " ).append(Student. class .getSimpleName()).append( " a " ); |
21 | List<Object> list=entityDao.createQuery(sff.toString()); |
25 | public void save(Student st){ |
28 | public void delete(Object obj){ |
29 | entityDao.delete(obj); |
OK,例子写完。有其它业务内容,只需直接新建view,并实现相应comtroller和service就行了,配置和dao层的内容基本不变,也就是每次只需写jsp(view),controller和service调用dao就行了。
怎样,看了这个,spring mvc是不是比ssh实现更方便灵活。