SpringMVC项目里面是不是一定要有Service层?

jieyangchenjian 2013-11-22 11:28:36
...全文
3136 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
洋葱汤_ 2014-08-13
  • 打赏
  • 举报
回复
没有在spring中对userDAO做注册当然注入不了 或者在userDAO类前加responsitroy注解
快乐的2 2013-11-23
  • 打赏
  • 举报
回复
SpringMVC的配置文件里推荐仅包含Controller层的配置. 对于Service的配置方法applicationContext中去配置
jieyangchenjian 2013-11-23
  • 打赏
  • 举报
回复
User
package com.secondhand.entity;

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * User entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "user", catalog = "secondhand")
public class User implements java.io.Serializable {

	// Fields

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer useId;
	private String password;
	private String credit;
	private String userName;
	private String sex;
	private String department;
	private String label;
	private String telephone;
	private String address;
	private String email;
	private Timestamp registrationTime;
	private String number;

	// Constructors

	/** default constructor */
	public User() {
	}

	/** full constructor */
	public User(String password, String credit, String userName, String sex,
			String department, String label, String telephone, String address,
			String email, Timestamp registrationTime, String number) {
		this.password = password;
		this.credit = credit;
		this.userName = userName;
		this.sex = sex;
		this.department = department;
		this.label = label;
		this.telephone = telephone;
		this.address = address;
		this.email = email;
		this.registrationTime = registrationTime;
		this.number = number;
	}
	

	// Property accessors
	@Id
	@GeneratedValue
	@Column(name = "Use_id", unique = true, nullable = false)
	public Integer getUseId() {
		return this.useId;
	}

	public void setUseId(Integer useId) {
		this.useId = useId;
	}

	@Column(name = "Password", nullable = false, length = 20)
	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Column(name = "Credit", nullable = false, length = 10)
	public String getCredit() {
		return this.credit;
	}

	public void setCredit(String credit) {
		this.credit = credit;
	}

	@Column(name = "User_name", nullable = false, length = 20)
	public String getUserName() {
		return this.userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	@Column(name = "Sex", nullable = false, length = 5)
	public String getSex() {
		return this.sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Column(name = "Department", nullable = false, length = 15)
	public String getDepartment() {
		return this.department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	@Column(name = "Label", nullable = false, length = 20)
	public String getLabel() {
		return this.label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	@Column(name = "Telephone", nullable = false, length = 20)
	public String getTelephone() {
		return this.telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	@Column(name = "Address", nullable = false, length = 50)
	public String getAddress() {
		return this.address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Column(name = "Email", nullable = false, length = 20)
	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Column(name = "Registration_time", nullable = false, length = 19)
	public Timestamp getRegistrationTime() {
		return this.registrationTime;
	}

	public void setRegistrationTime(Timestamp registrationTime) {
		this.registrationTime = registrationTime;
	}

	@Column(name = "number", nullable = false, length = 20)
	public String getNumber() {
		return this.number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

}
jieyangchenjian 2013-11-23
  • 打赏
  • 举报
回复
UserController
package com.secondhand.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.secondhand.dao.UserDAO;
import com.secondhand.entity.User;

/**
 * @author ChenJian
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
	
	//@Resource(name="UserDAO")
	@Autowired
	UserDAO UserDAO;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/login.do", method=RequestMethod.POST)
	public String login(HttpServletRequest request, @SuppressWarnings("rawtypes") Map map, HttpSession session) throws IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user=new User();
		if(username!=null&&password!=null)
		{
			System.out.println(username+""+password);
			//System.out.println(userDao.getUser(username, password).toString());
			user = UserDAO.getUser(username, password);
			//user = userDao.findByUserName(username).get(0);
		}
		
		if (null == user) {
			map.put("error", "用户名或密码错误");
			return "error";
		}
		return "main";
	}

}
UserDao
package com.secondhand.dao;


import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.secondhand.entity.User;

/**
 	* A data access object (DAO) providing persistence and search support for User entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see com.secondhand.dao.User
  * @author MyEclipse Persistence Tools 
 */


public class UserDAO extends HibernateDaoSupport  {
		 private static final Log log = LogFactory.getLog(UserDAO.class);
		//property constants
	public static final String PASSWORD = "password";
	public static final String CREDIT = "credit";
	public static final String USER_NAME = "userName";
	public static final String SEX = "sex";
	public static final String DEPARTMENT = "department";
	public static final String LABEL = "label";
	public static final String TELEPHONE = "telephone";
	public static final String ADDRESS = "address";
	public static final String EMAIL = "email";
	public static final String NUMBER = "number";



	protected void initDao() {
		//do nothing
	}
    
    public void save(User transientInstance) {
        log.debug("saving User instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
	public void delete(User persistentInstance) {
        log.debug("deleting User instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
	
	/**
	 * 执行带参的HQL查询
	 * 
	 * @param sql
	 * @param params
	 * @return 查询结果
	 */
	@SuppressWarnings("unchecked")
	public List<User> find(String hql, Object... params) {
		return getHibernateTemplate().find(hql,params);
	}
    
    public User findById( java.lang.Integer id) {
        log.debug("getting User instance with id: " + id);
        try {
            User instance = (User) getHibernateTemplate()
                    .get("com.secondhand.dao.User", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    public User getUser(String username, String password) {
		String hql = "from User user where user.userName=? and user.password=?";
		Object[] args = new Object[]{username, password};
		List<User> list = this.find(hql, args);
		if (list.size() == 0)
			return null;
		else
			return (User) list.get(0);
	}
    
    public List<User> findByExample(User instance) {
        log.debug("finding User instance by example");
        try {
            @SuppressWarnings("unchecked")
			List<User> results = (List<User>) getHibernateTemplate().findByExample(instance); 
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    @SuppressWarnings("unchecked")
	public List<User> findByProperty(String propertyName, Object value) {
      log.debug("finding User instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from User as model where model." 
         						+ propertyName + "= ?";
		 return getHibernateTemplate().find(queryString, value);
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List<User> findByPassword(Object password
	) {
		return findByProperty(PASSWORD, password);
	}
	
	public List<User> findByCredit(Object credit
	) {
		return findByProperty(CREDIT, credit
		);
	}
	
	public List<User> findByUserName(Object userName
	) {
		return findByProperty(USER_NAME, userName
		);
	}
	
	public List<User> findBySex(Object sex
	) {
		return findByProperty(SEX, sex
		);
	}
	
	public List<User> findByDepartment(Object department
	) {
		return findByProperty(DEPARTMENT, department
		);
	}
	
	public List<User> findByLabel(Object label
	) {
		return findByProperty(LABEL, label
		);
	}
	
	public List<User> findByTelephone(Object telephone
	) {
		return findByProperty(TELEPHONE, telephone
		);
	}
	
	public List<User> findByAddress(Object address
	) {
		return findByProperty(ADDRESS, address
		);
	}
	
	public List<User> findByEmail(Object email
	) {
		return findByProperty(EMAIL, email
		);
	}
	
	public List<User> findByNumber(Object number
	) {
		return findByProperty(NUMBER, number
		);
	}
	

	public List<?> findAll() {
		log.debug("finding all User instances");
		try {
			String queryString = "from User";
		 	return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
    public User merge(User detachedInstance) {
        log.debug("merging User instance");
        try {
            User result = getHibernateTemplate()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(User instance) {
        log.debug("attaching dirty User instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(User instance) {
        log.debug("attaching clean User instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

	public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
    	return (UserDAO) ctx.getBean("UserDAO");
	}
	
	
}
jieyangchenjian 2013-11-23
  • 打赏
  • 举报
回复
引用 1 楼 duanwu2330323 的回复:
看了你百度提问里面其他人的回答,我觉得他们的回答貌似没有正面解决你的问题,我来说说我的观点吧 首先springMVC是不包括service和DAO的,我想这个你应该清楚了 然后在注入方面,一般来说action层注入的是service层组件,service层里注入的是DAO组件,在项目运行的时候就是action层调用业务层的方法去实现业务,业务层调用DAO成的方法来查询数据。 但是如果楼主的架构中没有service层,这也是可以的,也就是说楼主只有action和DAO两层,这样的话,楼主可以直接在action层里面注入DAO层组件,然后楼主的action在接收请求后直接在action层里面实现业务,然后调用DAO层的方法查询数据。 所以答案就是不一定需要service层。至于楼主的错误,应该是楼主在action层里面注入DAO层组件的时候发生了错误。具体错误,楼主需要贴代码才能看得出来! 以上纯属个人观点,谢谢!
首先先谢谢你的回答,终于有一个正面回答我的问题了!!我这就把代码贴上来,大家帮忙看一下~~ web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name></display-name>	
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath:/applicationContext.xml</param-value>
    </context-param>
    <servlet>
    	<servlet-name>springMVC</servlet-name>
    	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    	<init-param>
      		<param-name>contextConfigLocation</param-name>
      		<param-value>classpath:/springMVC.xml</param-value>
    	</init-param>
    	<load-on-startup>1</load-on-startup>
  	</servlet>
  	<servlet-mapping>
    	<servlet-name>springMVC</servlet-name>
    	<url-pattern>*.do</url-pattern>
  	</servlet-mapping>
  	<welcome-file-list>
    	<welcome-file>index.jsp</welcome-file>
  	</welcome-file-list>
</web-app>
applicationContext.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"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"
	>
	
	
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"
			value="com.mysql.jdbc.Driver">
		</property>
		<property name="url"
			value="jdbc:mysql://127.0.0.1:3306/secondhand">
		</property>
		<property name="username" value="root"></property>
		<property name="password" value="199209"></property>
	</bean>
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
			</props>
		</property>
		<property name="annotatedClasses">
			<list>
				<value>com.secondhand.dao.Browse</value>
				<value>com.secondhand.entity.Browse</value>
				<value>com.secondhand.entity.Operation</value>
				<value>com.secondhand.entity.Collection</value>
				<value>com.secondhand.entity.OperationInfo</value>
				<value>com.secondhand.entity.WishList</value>
				<value>com.secondhand.entity.GoodsState</value>
				<value>com.secondhand.entity.Evaluation</value>
				<value>com.secondhand.entity.Type</value>
				<value>com.secondhand.entity.Goods</value>
				<value>com.secondhand.entity.User</value></list>
		</property>
	</bean>
	<context:annotation-config />
	<bean id="BrowseDAO" class="com.secondhand.dao.BrowseDAO"></bean>
	<bean id="UserDAO"  class="com.secondhand.dao.UserDAO">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<bean id="TypeDAO" class="com.secondhand.dao.TypeDAO"></bean>
	<bean id="EvaluationDAO" class="com.secondhand.dao.EvaluationDAO"></bean>
	<bean id="GoodsStateDAO" class="com.secondhand.dao.GoodsStateDAO"></bean>
	<bean id="GoodsDAO" class="com.secondhand.dao.GoodsDAO"></bean>
	<bean id="WishListDAO" class="com.secondhand.dao.WishListDAO"></bean>
	<bean id="OperationDAO" class="com.secondhand.dao.OperationDAO"></bean>
	<bean id="OperationInfoDAO"
		class="com.secondhand.dao.OperationInfoDAO">
	</bean>
	<bean id="CollectionDAO" class="com.secondhand.dao.CollectionDAO"></bean>
</beans>
SpringMVC.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	 xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-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/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<mvc:annotation-driven/>
	<context:component-scan   base-package="com.secondhand.controller"  />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">

		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

  	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
		p:defaultEncoding="utf-8" />
    
</beans>
少羽 2013-11-23
  • 打赏
  • 举报
回复
看了你百度提问里面其他人的回答,我觉得他们的回答貌似没有正面解决你的问题,我来说说我的观点吧 首先springMVC是不包括service和DAO的,我想这个你应该清楚了 然后在注入方面,一般来说action层注入的是service层组件,service层里注入的是DAO组件,在项目运行的时候就是action层调用业务层的方法去实现业务,业务层调用DAO成的方法来查询数据。 但是如果楼主的架构中没有service层,这也是可以的,也就是说楼主只有action和DAO两层,这样的话,楼主可以直接在action层里面注入DAO层组件,然后楼主的action在接收请求后直接在action层里面实现业务,然后调用DAO层的方法查询数据。 所以答案就是不一定需要service层。至于楼主的错误,应该是楼主在action层里面注入DAO层组件的时候发生了错误。具体错误,楼主需要贴代码才能看得出来! 以上纯属个人观点,谢谢!
jieyangchenjian 2013-11-23
  • 打赏
  • 举报
回复
引用 8 楼 duanwu2330323 的回复:
@Autowired 这儿注解,我姐的有一个默认的name属性,也就是 @Autowired("name") 这个name属性可以不写,但是不写的情况下默认应该是属性名,在你那里也就是UserDAO,但是一般来说我们的属性名都是要以小写开头,不知道楼主的属性名是大写开头的情况下@Autowired这个标签默认的name到底是UserDao还是userDao了,楼主可以在@Autowired后面加上@Autowired("UserDao")再试试,但是不保证能行得通!
还是不行~~你有配置好的例子吗?或是如果你有时间帮我看看,能不能留个邮箱,我把整个工程发给你~~
少羽 2013-11-23
  • 打赏
  • 举报
回复
@Autowired 这儿注解,我姐的有一个默认的name属性,也就是 @Autowired("name") 这个name属性可以不写,但是不写的情况下默认应该是属性名,在你那里也就是UserDAO,但是一般来说我们的属性名都是要以小写开头,不知道楼主的属性名是大写开头的情况下@Autowired这个标签默认的name到底是UserDao还是userDao了,楼主可以在@Autowired后面加上@Autowired("UserDao")再试试,但是不保证能行得通!
jieyangchenjian 2013-11-23
  • 打赏
  • 举报
回复
引用 6 楼 duanwu2330323 的回复:
注解我用的比较少,不过在控制层里面的被注入的属性是不是应该也要有set和get方法啊?楼主现在是没有的。 另外既然楼主的使用了注解来注入属性的话,为什么不直接用注解来配置bean呢?还要在xml文件中用<bean>标签配置干什么?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.secondhand.dao.UserDAO com.secondhand.controller.UserController.UserDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.secondhand.dao.UserDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我在Controller里面加了UserDAO的Set和Get还是不行……
public void setUserDAO(UserDAO UserDAO)
	{
		this.UserDAO = UserDAO;
	}
	
	public UserDAO getUserDAO()
	{
		return this.UserDAO;
	}
我在XML写Bean是因为我之前是用Hibernate生成DAO的,它自动生成的时候就直接在配置文件里面写好了,我觉得它既然已经写在XML里面了,怎么会找不到呢?
少羽 2013-11-23
  • 打赏
  • 举报
回复
注解我用的比较少,不过在控制层里面的被注入的属性是不是应该也要有set和get方法啊?楼主现在是没有的。 另外既然楼主的使用了注解来注入属性的话,为什么不直接用注解来配置bean呢?还要在xml文件中用<bean>标签配置干什么?

67,549

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧