SpringMVC例子

StudentController:

package com.mvc.controller;   
  
import java.util.List;   
  
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   
  
import org.apache.commons.logging.Log;   
import org.apache.commons.logging.LogFactory;   
import org.springframework.beans.factory.annotation.Autowired;   
import org.springframework.stereotype.Controller;   
import org.springframework.ui.ModelMap;   
import org.springframework.web.bind.annotation.RequestMapping;   
import org.springframework.web.bind.annotation.RequestMethod;   
import org.springframework.web.bind.annotation.RequestParam;   
import org.springframework.web.servlet.ModelAndView;   
  
import com.mvc.entity.Student;   
import com.mvc.service.StudentService;   
  
@Controller
public class StudentController {   
    protected final transient Log log = LogFactory.getLog(StudentController.class);   
    @Autowired
    private StudentService studentService;   
    public StudentController(){   
           
    }   
       
    @RequestMapping("/wj.do")
    public String load(ModelMap modelMap){   
        List<Object> list = studentService.getStudentList();   
        modelMap.put("list", list);   
        return "student";   
    }   
       
    @RequestMapping(value="/wj.do",params = "method=add")   
    public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{   
        return "student_add";   
    }   
       
    @RequestMapping(value="/wj.do",params = "method=save")   
    public String save(HttpServletRequest request, ModelMap modelMap){   
        String user = request.getParameter("user");   
        String psw = request.getParameter("psw");   
        Student st = new Student();   
        st.setUser(user);   
        st.setPsw(psw);   
        try{   
            studentService.save(st);   
            modelMap.put("addstate", "添加成功");   
        }   
        catch(Exception e){   
            log.error(e.getMessage());   
            modelMap.put("addstate", "添加失败");   
        }   
           
        return "student_add";   
    }   
       
    @RequestMapping(value="/wj.do",params = "method=del")   
    public void del(@RequestParam("id") String id, HttpServletResponse response){   
        try{   
            Student st = new Student();   
            st.setId(Integer.valueOf(id));   
            studentService.delete(st);   
            response.getWriter().print("{\"del\":\"true\"}");   
        }   
        catch(Exception e){   
            log.error(e.getMessage());   
            e.printStackTrace();   
        }   
    }   
}


EntityDao:

package com.mvc.dao;   
  
import java.util.List;   


import org.springframework.stereotype.Repository;
@Repository
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);   
}


EntityDaoImpl:

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{   
    @SuppressWarnings("unchecked")
public List<Object> createQuery(final String queryString) {   
        return (List<Object>) getHibernateTemplate().execute(   
                new HibernateCallback() {   
                    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() {   
                    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() {   
            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() {   
            public Object doInHibernate(org.hibernate.Session session)   
                    throws org.hibernate.HibernateException {   
                session.delete(model);   
                return null;   
            }   
        });   
    }   
}


Student:

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


StudentService:

package com.mvc.service;   
  
import java.util.List;   


import javax.annotation.Resource;
  
import org.springframework.beans.factory.annotation.Autowired;   
import org.springframework.stereotype.Service;   
import org.springframework.transaction.annotation.Transactional;   
  
import com.mvc.dao.EntityDao;   
import com.mvc.entity.Student;   
  
@Service
public class StudentService {   
 @Autowired
 private EntityDao entityDao;   
    
// @Transactional  
 public List<Object> getStudentList(){   
  StringBuffer sff = new StringBuffer();   
  sff.append("select a from ").append(Student.class.getSimpleName()).append(" a ");   
  List<Object> list = entityDao.createQuery(sff.toString());   
  return list;   
 }   
    
 public void save(Student st){   
  entityDao.save(st);   
 }   
 public void delete(Object obj){   
  entityDao.delete(obj);   
 }   
}


applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>   
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">   

<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射,包括自动注入功能 -->
  <context:component-scan base-package="com.mvc" use-default-filters="true">
   <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  </context:component-scan>
   
 <context:property-placeholder location="classpath:/hibernate.properties" />   
  
 <bean id="sessionFactory"  
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">   
  <property name="dataSource" ref="dataSource" />   
  <property name="hibernateProperties">   
   <props>   
    <prop key="hibernate.dialect">${dataSource.dialect}</prop>   
    <prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop>   
    <prop key="hibernate.hbm2ddl.auto">update</prop>   
   </props>   
  </property>   
  <property name="packagesToScan">   
   <list>   
    <value>com.mvc.entity</value><!-- 扫描实体类,也就是平时所说的model -->   
   </list>   
    </property>   
 </bean>   
  
 <bean id="transactionManager"  
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">   
  <property name="sessionFactory" ref="sessionFactory" />   
  <property name="dataSource" ref="dataSource" />   
 </bean>   
  
 <bean id="dataSource"  
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">   
  <property name="driverClassName" value="${dataSource.driverClassName}" />   
  <property name="url" value="${dataSource.url}" />   
  <property name="username" value="${dataSource.username}" />   
  <property name="password" value="${dataSource.password}" />   
 </bean>   
 <!-- Dao的实现 -->   
 <bean id="entityDao" class="com.mvc.dao.EntityDaoImpl">     
  <property name="sessionFactory" ref="sessionFactory" />   
 </bean>   
 <tx:annotation-driven transaction-manager="transactionManager" />   
 <tx:annotation-driven mode="aspectj"/>   
     
    <aop:aspectj-autoproxy/>     
</beans>


hibernate.properties:

dataSource.password=123
dataSource.username=root
dataSource.databaseName=test
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.dialect=org.hibernate.dialect.MySQL5Dialect
dataSource.serverName=localhost:3306
dataSource.url=jdbc:mysql://localhost:3306/test
dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password}
dataSource.hbm2ddl.auto=update


log4j.properties:

#log4j.rootLogger=DEBUG, A1
#log4j.appender.A1.layout=org.apache.log4j.PatternLayout
#log4j.appender.A1.layout.ConversionPattern=>>> %d %5p [%t] (%F:%L) - %m%n
#log4j.appender.A1.DatePattern='.'yyyy-MM-dd
#log4j.appender.A1=org.apache.log4j.ConsoleAppender


spring-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-3.0.xsd   
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">   
        
  <!--context:annotation-config /  -->
   
 
      <!-- Bean创建功能 -->
   <context:component-scan base-package="com.mvc" use-default-filters="false">
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
   </context:component-scan>
   
      <!--bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /-->
      
      <!--bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /-->
      
      <!--bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/-->
      
      <!--bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/-->
      
       <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->     
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"     
          p:prefix="/WEB-INF/view/" p:suffix=".jsp" />     
           
       <bean id="multipartResolver"     
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"     
          p:defaultEncoding="utf-8" />     
 </beans>


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_2_5.xsd" id="WebApp_ID" version="2.5">   
  <display-name>ok</display-name>   
   <context-param>     
     <param-name>contextConfigLocation</param-name>     
     <param-value>classpath:applicationContext*.xml</param-value>     
 </context-param>     
  <listener>     
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>     
 </listener>     
  
 <servlet>     
     <servlet-name>spring</servlet-name>     
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>     
     <load-on-startup>1</load-on-startup>     
 </servlet>     
 <servlet-mapping>     
     <servlet-name>spring</servlet-name>  <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller -->   
     <url-pattern>*.do</url-pattern>     
 </servlet-mapping>     
  <welcome-file-list>   
    <welcome-file>index.jsp</welcome-file>   
  </welcome-file-list>   
</web-app>


tomcat6.0的server.xml文件添加如下语句:

<Context path="/mvc" debug="0" privileged="true" docBase="D:\workspace\mvc\web"/>

这句话放在<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false"></host>之间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值