SpringMVC环境搭建

springmvc和stuts2相同是实现mvc的优秀框架,进行业务逻辑控制。最大的差别就是struts2通过filter拦截请求到Action。而spring用的是servlet获取请求到controller。再一个是springmvc不用过多进行配置,能够通过注解非常方便简单的进行开发。

SpringMVC+Spring+Hibernate环境搭建:

1 导入相应jar包:

2 在web.xml配置Spring的监听器,指定配置。配置SpringMVC的核心Servlet,指定哪些请求由SpringMVC的Controller处理。同一时候常常设置Spring的一个编码过滤器。指定编码格式防止乱码;

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" 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>SpringMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
   <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <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>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>Character Encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Character Encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

3 指定结果视图,须要指定controller所在的包,配置在web.xml的同级文件夹下

springmvc-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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

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

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>
        </beans>

4 配置spring的applicationContext.xml.这里配置的是hibernate和spring整合的内容

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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

	<context:component-scan base-package="com.mvc.dao,com.mvc.service,com.mvc.entity"></context:component-scan>
	<tx:annotation-driven transaction-manager="transactionManager" />

	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:c3p0.properties</value>
		</property>
	</bean>
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${driverClass}"></property>
		<property name="jdbcUrl" value="${jdbcUrl}"></property>
		<property name="user" value="${user}"></property>
		<property name="password" value="${password}"></property>
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="packagesToScan">
			<list>
				<value>com.mvc.entity</value>

			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

</beans>

c3p0.properties

driverClass=oracle.jdbc.driver.OracleDriver
jdbcUrl=jdbc:oracle:thin:@localhost:1521:XE
user=orcl
password=newsnews

5 dao层代码

package com.mvc.dao;

import java.util.List;

import com.mvc.entity.Goods;

public interface GoodsDao {
	void save(Goods goods);
	List<Goods> findAll();
	Goods findById(Integer id);
	void update(Goods goods);
	void delete(Goods goods);
}
package com.mvc.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.mvc.entity.Goods;
@Repository(value="goodsDao")
public class GoodsDaoImpl extends HibernateDaoSupport implements GoodsDao {
	@Resource
	public void setOne(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}

	@Override
	public void save(Goods goods) {
		this.getHibernateTemplate().save(goods);

	}

	@Override
	public List<Goods> findAll() {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().find("from Goods g");
	}

	@Override
	public Goods findById(Integer id) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().get(Goods.class, id);
	}

	@Override
	public void update(Goods goods) {
		this.getHibernateTemplate().update(goods);

	}

	@Override
	public void delete(Goods goods) {
		this.getHibernateTemplate().delete(goods);

	}

}

6 service层代码

package com.mvc.service;

import java.util.List;

import com.mvc.entity.Goods;

public interface GoodsService {
	void save(Goods goods);
	List<Goods> findAll();
	Goods findById(Integer id);
	void update(Goods goods);
	void delete(Goods goods);
}

package com.mvc.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mvc.dao.GoodsDao;
import com.mvc.entity.Goods;
@Service(value="goodsService")
@Transactional
public class GoodsServiceImpl implements GoodsService {
	private GoodsDao goodsDao;

	public GoodsDao getGoodsDao() {
		return goodsDao;
	}

	@Resource
	public void setGoodsDao(GoodsDao goodsDao) {
		this.goodsDao = goodsDao;
	}

	@Override
	public void save(Goods goods) {
		goodsDao.save(goods);

	}

	@Override
	public List<Goods> findAll() {
		// TODO Auto-generated method stub
		return goodsDao.findAll();
	}

	@Override
	public Goods findById(Integer id) {
		// TODO Auto-generated method stub
		return goodsDao.findById(id);
	}

	@Override
	public void update(Goods goods) {
		// TODO Auto-generated method stub
		goodsDao.update(goods);
	}

	@Override
	public void delete(Goods goods) {
		goodsDao.delete(goods);

	}

}

7 controller层代码,这里是被重定向的 RequestMapping须要设置GET方式

package com.mvc.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mvc.entity.Goods;
import com.mvc.service.GoodsService;

@Controller
@RequestMapping(value="/Goods")
public class GoodsController {
	private GoodsService goodsService;
	@Resource
	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	@RequestMapping(value="/saveGoods.do",method=RequestMethod.POST)
	public String saveGoods(@ModelAttribute Goods goods){
		System.out.println("in save");
		goodsService.save(goods);
		return "redirect:findAllGoods.do";
	}

	@RequestMapping(value="/findAllGoods",method=RequestMethod.GET)
	public String findAllGoods(@ModelAttribute Goods goods,Model model){
		System.out.println("in findAll");
		List<Goods> goodss=goodsService.findAll();
		System.out.println(((Goods)goodss.get(0)).getGoodsName());
		model.addAttribute("goodss",goodss);
		return "goods_list";
	}
	@RequestMapping(value="/updateGoods.do",method=RequestMethod.GET)
	public String updateGoods(@ModelAttribute Goods goods,Model model){
		System.out.println("in update");
		Goods goods1=goodsService.findById(goods.getGoodsId());
		model.addAttribute("goods", goods1);
		return "goods_detail";
	}
	@RequestMapping(value="/updateGoodsDo.do",method=RequestMethod.POST)
	public String updateGoodsDo(@ModelAttribute Goods goods){
		System.out.println("in updatedo");
		goodsService.update(goods);

		return "redirect:findAllGoods.do";
	}
	@RequestMapping(value="/deleteGoods.do",method=RequestMethod.GET)
	public String deleteGoodsDo(@ModelAttribute Goods goods){
		System.out.println("in updatedo");
		Goods g=goodsService.findById(goods.getGoodsId());
		goodsService.delete(g);
		return "redirect:findAllGoods.do";
	}
}

8 jsp,在springmvc的controller里,假设给类加上RequestMapping,jsp跳进去总是存在和struts2的namespace类似路径问题。解决方案同样。就是在jsp中增加

<%

String path=request.getContextPath();

String basePath=request.getScheme()+"://"+request.getServerName()+":"

+request.getServerPort()+path+"/";

%>

<base href="<%=basePath %>">

来解决。

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="Goods/findAllGoods.do" method="get">

<input type="submit" value="go">
</form>
</body>
</html>

goods_list.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path=request.getContextPath();
    String basePath=request.getScheme()+"://"+request.getServerName()+":"
    +request.getServerPort()+path+"/";
 %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath %>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
	<td>商品名称</td><td>商品数量</td><td>编辑</td><td>删除</td>
</tr>
<c:forEach items="${goodss}" var="goods">
<tr>
	<td>${goods.goodsName}</td><td>${goods.goodsNumber}</td><td><a href="Goods/updateGoods.do?goodsId=${goods.goodsId }">编辑</a></td>
	<td><a href="Goods/deleteGoods.do?goodsId=${goods.goodsId }">删除</a></td>
</tr>
</c:forEach>
</table>
<a href="goods_save.jsp">add</a>
</body>
</html>

goods_save.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="Goods/saveGoods.do" method="post">
商品名称:<input type="text" name="goodsName"/><br>
商品数量:<input type="text" name="goodsNumber"/><br>
<input type="submit" value="go">
</form>
</body>
</html>

goods_detail.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%
    String path=request.getContextPath();
    String basePath=request.getScheme()+"://"+request.getServerName()+":"
    +request.getServerPort()+path+"/";
 %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath %>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Goods/updateGoodsDo.do" method="post">
<input type="hidden" name="goodsId" value="${goods.goodsId }"/>
商品名称:<input type="text" name="goodsName" value="${goods.goodsName }"/><br/>
商品数量:<input type="text" name="goodsNumber" value="${goods.goodsNumber }"><br/>
<input type="submit" value="update">
</form>
</body>
</html>



时间: 2024-10-25 19:34:18

SpringMVC环境搭建的相关文章

SpringMVC环境搭建(xml版本)

SpringMVC是Web层框架,它隶属于Spring框架,只是Spring这个庞大框架下的一个小模块,用于替换Servlet 1.下载jar包(20) http://zhidao.baidu.com/link?url=guH_VTC2FKGftWBtdCW_AU_z9t5QgyGqlr-DEwkryPCNhhlySr9wJACJVJu3hRiib50j_GNFkQNxZr4-k2v3z5jRpS1poxR3YZeb5dfThuS我是根据这个网址找到一个压缩包,解压后libs下会发现很多jar包

springmvc环境搭建以及常见问题解决

1.新建maven工程 a)  打开eclipse,file->new->project->Maven->Maven Project b)  下一步 c)   选择创建的工程为webapp,下一步 d)   填写项目的group id和artifact id.一般情况下,group id写域名的倒序,artifact id写项目名称即可.最后点完成. e)   最初建好后,项目目录结构如下 f)   一般的项目目录中,还有src/main/java,src/main/test/ja

spring入门(五)【springMVC环境搭建】

springMVC作为spring的一个WEB组件,是一个MVC的思想,减少了WEB开发的难度,现介绍springMVC环境的搭建,具体的原理放在后面介绍.用过框架的朋友都知道要在WEB项目中使用一个框架,必须要引入这个框架,和其他框架的引用方式一样,springMVC的引入方式是通过DispatcherServlet,那么我们就要在web.xml中配置此servlet,在lib目录下我已经把用到的jar包全部导入,下面看我的web.xml文件的配置, <?xml version="1.0

力所能及之springmvc环境搭建

小狼从12年学习java开始,就听老师说了若干springmvc的高大上,可是人家就吊你胃口,死活不给你讲.当然,小狼不是盈利机构,不需要赶时间,这个该讲,那个不该讲的.今天,小狼就说说springmvc的环境搭建. 开发环境:myeclipse8.6  spring4.0 开发需要的jar文件: 项目结构: web.xml配置: <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu

SpringMVC环境搭建之Idea

SpringMVC一.. SpringMVC重要组件介绍    1. DispacherServlet:前端控制器,接收所有请求,(如果配置/不包含jsp)    2. HandlerMapping:解析请求格式,判断希望要执行哪个方法    3. HandlerAdapter:负责调用具体的方法    4. ViewResovler:视图解析器,解析结果,准备跳转的具体的视图 spring的jar包官方下载地址: https://repo.spring.io/libs-release-loca

[精华]springMVC环境搭建基础入门总汇!

1.SpringMVC概述 SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于 Spring       FrameWork 的后续产品,已经融合在 Spring Web Flow 里面.Spring 框架提供了构建 Web 应用程序的全功 能 MVC 模块.使用 Spring 可插入的 MVC 架构,从而在使用 Spring 进行 WEB 开发时,可以选择使用 Spring 的 Spring MVC 框架或集成其他 MVC 开发框架,如

SpringMVC环境搭建--从简入手

一看到SpringMVC是什么东西?很多人第一个想知道,他能干嘛!怎么用?其实我自己的理解Spring MVC就是,Spring框架中的一个拓展,我们平时开发网站不用其他的框架,本身java Web自带的就有我们熟悉的Servlet对吧.Spring MVC分解开就是Model.View.Controller,Spring帮我们做了这三个东西.就是我们熟悉的MVC模式嘛! 1.帮我们如何去管理Model(如User类的set和get的管理). 2.帮我们如何传数据到View层.(JSP等) 3.

SpringMVC环境搭建---xml版及注解版

一.建立 JavaWeb 项目(基于Intellij 14.0.3搭建) 1.建立一个 Java 项目,在项目下新建一个文件夹 webapp ,然后在该文件夹下新建一个 WEB-INF 文件夹: 2.在 WEB-INF文件夹下建立 web.xml 文件,从 tomcat 安装路径 /conf/web.xml 中拷贝基本的文档结构,修改相应编码为 utf-8: 3.在 WEB-INF 下建立 jsp 文件夹,用来存放相关jsp 文件(MVC 中的 V): 4.在 WEB-INF 下建立 lib 文

简单springMVC环境搭建

web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app 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/ja