首页 > 代码库 > springmvc环境的搭建

springmvc环境的搭建

最近应公司要求,用了2天时间学了springmvc的搭建,就简单总结一下:

springmvc和struts2的比较,因为我是学过struts的,它们都是基于mvc模式而设计的web层框架

它们最大的区别:

1、入口 

spring mvc的入口是servlet,而struts2是filter

(这里要指出,filter和servlet是不同的。以前认为filter是servlet的一种特殊),

这样就导致了二者的机制不同,这里就牵涉到servlet和filter的区别了。

 2、主要机制

springmvc是方法级别的拦截,一个方法对应一个request上下文,而方法同时又跟一个url对应,参数的传递是直接注入到方法中的,是该方法独有的。

struts2是类级别的拦截, 一个类对应一个request上下文, struts是在接受参数的时候,可以用属性来接受参数, 这就说明参数是让多个方法共享的,

这也就无法用注解或其他方式标识所属方法了

intercepter的实现机制。struts有以自己的interceptor机制,spring mvc 用的是独立的AOP方式。这样导致struts的配置文件量还是比spring mvc大,

虽然struts的配置能继承,spring mvc使用更加简洁。


springmvc环境的搭建:

建立一个web项目:

首先在目录/WEB-INF/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">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <!-- 配置前端控制器 -->
  <servlet>
   <servlet-name>springmvc</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <!-- 服务器开启的时候,SpringMVC也开启 -->
   <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
   <servlet-name>springmvc</servlet-name>
   <url-pattern>*.action</url-pattern>
  </servlet-mapping>
 
  <servlet-mapping>
   <servlet-name>springmvc</servlet-name>
   <!-- mvc的名称可以随便取, 这样前台可以通过 /项目名/mvc/控制器指定的name名称访问 -->
   <url-pattern>/mvc/*</url-pattern>
  </servlet-mapping>
 
</web-app>

 

然后还是/WEB-INF/springmvc-servlet.xml(注:该文件名是[servletname]-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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
 
 <!-- 配置controller,由spring来管理controller,前台通过name指定的值来获取访问相应的controller,
 因为ID不支持,后面action要和servlet中配置的后置相同 -->
 <bean class="com.controller.UserController" name="/list.action"></bean>
 
 <!-- 配置框架提供的视图解析器,通过配置前缀和后缀规则来解析,ModelAndView -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="http://www.mamicode.com/WEB-INF/jsp/"></property>
  <property name="suffix" value="http://www.mamicode.com/.jsp"></property>
 </bean>
 
</beans>

 

 

Controller层

/** * 基于注解的SpringMVC+Hibernate3.6的CRUD * @author Saiteam * */@Controllerpublic class UserController {		private UserDaoImpl userDao=new UserDaoImpl();		@RequestMapping(value="http://www.mamicode.com/list.action")	public String list(HttpServletRequest request){		List<User> user = userDao.list();		request.setAttribute("users", user);		return "list";	}	@RequestMapping(value="http://www.mamicode.com/saveForward.action")	public String saveForward(HttpServletRequest request){		return "add";	}	@RequestMapping(value="http://www.mamicode.com/add.action")	public String add(HttpServletRequest request) throws Exception{		request.setCharacterEncoding("UTF-8");		User user = new User();		user.setName(request.getParameter("name"));		user.setPassword(request.getParameter("password"));		user.setSex(request.getParameter("sex"));		user.setAddress(request.getParameter("address"));		user.setPhone(request.getParameter("phone"));		user.setEmail(request.getParameter("email"));		userDao.save(user);		request.setAttribute("users", userDao.list());		return "list";	}		@RequestMapping(value="http://www.mamicode.com/delete.action")	public String delete(HttpServletRequest request){		int id = Integer.parseInt(request.getParameter("id"));		userDao.delete(id);		request.setAttribute("users", userDao.list());		return "list";	}		@RequestMapping(value="http://www.mamicode.com/update.action")	public String update(HttpServletRequest request) throws Exception{		request.setCharacterEncoding("UTF-8");		User user = new User();		user.setId(Integer.parseInt(request.getParameter("id")));		user.setName(request.getParameter("name"));		user.setPassword(request.getParameter("password"));		user.setSex(request.getParameter("sex"));		user.setAddress(request.getParameter("address"));		user.setPhone(request.getParameter("phone"));		user.setEmail(request.getParameter("email"));		userDao.update(user);		request.setAttribute("users", userDao.list());		return "list";	}		@RequestMapping(value="http://www.mamicode.com/get.action")	public String get(HttpServletRequest request){		int id = Integer.parseInt(request.getParameter("id"));		request.setAttribute("user", userDao.get(id));		return "update";	}	/**	 * 登陆功能	 * @param request	 * @return	 * @throws Exception 	 */	@RequestMapping(value="http://www.mamicode.com/login.action")	public String login(HttpServletRequest request) throws Exception{		request.setCharacterEncoding("UTF-8");		String name = request.getParameter("name");		String password = request.getParameter("password");				//测试		System.out.println("-------name-----------"+name);		System.out.println("-------password-----------"+password);				if(name != null && !name.equals("")){			if(password != null && !password.equals("")){				User model = userDao.login(name, password);				//测试				System.out.println("-------------model--------"+model);								if(model != null && !model.equals("")){						request.setAttribute("users", userDao.list());						return "list";				}else{					request.setAttribute("error", "用户或密码错误!");					return "forward:/login.jsp";				}			}else{				request.setAttribute("error", "密码不能为空!");				return "forward:/login.jsp";			}		}else{			request.setAttribute("error", "用户名不能为空!");			return "forward:/login.jsp";		}			}		//实现注册功能	@RequestMapping(value="http://www.mamicode.com/register.action")	public String register(HttpServletRequest request) throws Exception{		request.setCharacterEncoding("UTF-8");		User user = new User();		user.setName(request.getParameter("name"));		user.setPassword(request.getParameter("password"));		user.setSex(request.getParameter("sex"));		user.setAddress(request.getParameter("address"));		user.setPhone(request.getParameter("phone"));		user.setEmail(request.getParameter("email"));		userDao.save(user);		return "forward:/index.jsp";	}			/**	 * 跳转到登陆页面	 * @param request	 * @return	 */	@RequestMapping(value="http://www.mamicode.com/loginForward.action")	public String loginForwad(HttpServletRequest request){		return "forward:/login.jsp";	}	/**	 * 转发到注册页面	 * @param request	 * @return	 */	@RequestMapping(value="http://www.mamicode.com/rgf.action")	public String registerForwad(HttpServletRequest request){		return "forward:/register.jsp";	}	}

 service层

public class UserDaoImpl implements UserDao {	public  void save(User user) {          Session session = HibernateSessionFactory.getSession();          Transaction tx = session.getTransaction();          try {              tx.begin();              session.save(user);              tx.commit();          } catch (HibernateException e) {              if (tx != null) { // 如果存在事务,则回滚                  tx.rollback();              }              throw e; // 抛出异常          } finally {              if (session != null) // 如果session存在,则关闭                  session.close();          }      }  	public  void delete(int id) {          Session session = HibernateSessionFactory.getSession();         String hql = "DELETE User u WHERE u.id=:id";        session.createQuery(hql).setInteger("id", id).executeUpdate();    }  	public void update(User user){		 Session session = HibernateSessionFactory.getSession(); 	     Transaction tx = session.getTransaction();           try {              tx.begin();             session.update(user);              tx.commit();          } catch (HibernateException e) {              if (tx != null) { // 如果存在事务,则回滚                  tx.rollback();              }              throw e; // 抛出异常          } finally {              if (session != null) // 如果session存在,则关闭                  session.close();          }  	}	  public  User get(int id) {  	        Session session = HibernateSessionFactory.getSession(); 	        try {  	            User user = (User) session.get(User.class, id);  	            return user;  	        } finally {  	            if (session != null) {  	                session.close();  	            }  	        }  	    }	public List<User> list(){		Session session = HibernateSessionFactory.getSession();		String hql = "FROM User";		return session.createQuery(hql).list();	}			//登陆功能	public User login(String name,String password){		Session session = HibernateSessionFactory.getSession();		String hql = "FROM User u WHERE u.name=:name AND u.password=:password";		return (User) session.createQuery(hql).setString("name", name).setString("password", password).uniqueResult();	}}

 jsp页面自己写