springmvc 例

1、结构


2、控制器

package com.ai.customer.controller;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import com.ai.customer.model.CustomerInfo;
import com.ai.customer.service.ICustomerService;

/*
 * @Controller
 * 控制器 
 * 
 * @Service
 * 用于标注业务层组件
 * 
 * @Repository
 * 用于标注数据訪问组件。即DAO组件
 * 
 * @Component
 *  泛指组件,当组件不好归类的时候我们能够使用这个注解进行标注,(如今能够都用此注解)
 *  同上事实上跟@Service/@Repository/@Controller 一样仅仅只是它们 利用分层 好区分
 * 
 * @Autowired\@Resource
 *  自己主动注入 实现的的是 setXxx()方法  getXxx()方法
 * 
 * @RequestMapping(value='xxx.do',method=RequestMethod.GET/RequestMethod.POST/..)
 * value訪问路径/method请发的方法,注:请求方法一旦设定仅仅能使用指定的方法訪问
 *  在类前面定义,则将url和类绑定。
 *  在方法前面定义,则将url和类的方法绑定
 * 
 * @RequestParam("name") ==uname
 *  一般用于将指定的请求參数付给方法中形參
 * 
 * @Scope 
 * 创建 bean的作用域 singleton-->多例  Property-->多例   还有request 等等
 * 使用reqeust 须要在web.xml 配置监听器 详细去网上搜索
 *  
 */


@Controller
public class CustomerAction {

	@Autowired
	private ICustomerService  customerService;
	
	@RequestMapping(value="/login.do")
	public String postLogingMethod(HttpServletRequest reqeust){
		System.out.println("訪问到了控制器");
		System.out.println(customerService);
		CustomerInfo cus=customerService.queryCustomer().get(0);
		System.out.println("身份证Id"+cus.getCardid());
		reqeust.getSession().setAttribute("cus", cus);
		return "page/admin/index";
	}
	
	
	/*
	 * @RequestParam 使用
	 * @RequestParam("name") ==uname 一般用于将指定的请求參数付给方法中形參
	 */
	@RequestMapping("/param.do" )
	public String paramMethod(@RequestParam("name")String uname){
		System.out.println("uname:"+uname);
		//重定向 页面
		return "redirect:index.jsp";
	}
	
	
	/*
	 *  页面传递过来的參数 自己主动赋值 xxx.do?

name=张三&customerid=12342423 post get请求皆可 * ajax $.xxx("xxx.do",{name:'张三',customerid:'123435345'},function(data){}); */ @RequestMapping("/rq.do") public String allMethod(String customerid,String name){ System.out.println(customerid+":"+name); return "index"; } /* * 封装实体对象 表单提交数据 表单中cus.name名 * <input type="text" name="cus.name"> * <input type="text" name="cus.customerid"> */ @RequestMapping("/cus.do") public String setCustomer(CustomerInfo cus){ System.out.println(cus.getCustomerid()+":"+cus.getName()); return "index"; } /*springmvc 中获取request对象 * 1、能够直接在方法中定义 getReqeust(CustomerInfo cus,HttpServletRequest req) * * 2、使用注解Autowired * @Autowired * private HttpServletRequest request; * * 3、使用例如以下方法 * ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); * servletRequestAttributes.getRequest(); * */ @RequestMapping("/reqeust.do") public String getReqeust(CustomerInfo cus,HttpServletRequest req){ //获取reqeust对象 req.setAttribute("cus", cus); //获取session对象 req.getSession(); return "index"; } /* 获取reponse 能够使用例如以下方法 也能够使用:在方法中传递 * getResponse(String name,String customerid,HttpservletResponse response) */ @RequestMapping("/response.do") public void getResponse(String name,String customerid,HttpServletResponse response){ response.setContentType("text/html;charset=utf-8"); System.out.println(name+":"+customerid); try { response.getWriter().write(customerid.toString()); } catch (IOException e) { e.printStackTrace(); } } /*ModelAndView 与 ModelMap 的差别 * * ModelAndView * 作用一 :设置转向地址/对象必须手动创建(主要差别) * * 作用二:用于传递控制方法处理结果数据到结果页面, * 也就是说我们把须要在结果页面上须要的数 * 据放到ModelAndView对象中就可以,他 * 的作用相似于request对象的setAttr * ibute方法的作用,用来在一个请求过程中 * 传递处理的数据。通过下面方法向页面传递 參数:addObject(String key,Object value); * * * ModelMap *一、 ModelMap的实例是由bboss mvc框架自己主动创建并作为控制器方法參数传入。 * 用户无需自己创建。 * * 二、ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上须要的数据放到ModelMap对象中就可以, * 他的作用相似于request对象的setAttribute方法的作用。用来在一个请求过程中传递处理的数据。

通过下面方法向页面传递參数: * addAttribute(String key,Object value); * 在页面上能够通过el变量方式$key或者bboss的一系列数据展示标签获取并展示modelmap中的数据。 * modelmap本身不能设置页面跳转的url地址别名或者物理跳转地址,那么我们能够通过控制器方法的返回值来设置跳转url地址 * 别名或者物理跳转地址。

*/ @RequestMapping("/modelmap.do") public String modelMapMethod(String name,ModelMap model) { //将数据放置到ModelMap对象model中,第二个參数能够是不论什么java类型 model.addAttribute("modelMap",name); //返回跳转地址 return "index"; } @RequestMapping("/modelandmap.do") public ModelAndView modelAndMapMethod(String name) { //构建ModelAndView实例,并设置跳转地址 ModelAndView view = new ModelAndView("index"); //将数据放置到ModelAndView对象view中,第二个參数能够是不论什么java类型 view.addObject("modelAndMap",name); //返回ModelAndView对象view return view; } }


3、DAO接口

package com.ai.customer.dao;

import java.util.List;

import com.ai.customer.model.CustomerInfo;

public interface ICustomerDao {

	//查询Customer
	public List<CustomerInfo> queryCustomer();
	public String all();
}

4、DAO接口实现

package com.ai.customer.daoimpl;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.ai.customer.dao.ICustomerDao;
import com.ai.customer.model.CustomerInfo;

@Repository
public class CustomerDao implements ICustomerDao {

	
	@Autowired
	private SessionFactory sessionFactory;
	
//	public void setSessionFactory(SessionFactory sessionFactory) {
//		this.sessionFactory = sessionFactory;
//	}

	public List<CustomerInfo> queryCustomer() {
		
		//System.out.println(sessionFactory);

		//Configuration config=new Configuration().configure("config/hibernet/hibernate.cfg.xml");
		
		//SessionFactory f=config.buildSessionFactory();
		
		Session session=sessionFactory.openSession();
		
		List<CustomerInfo> cus=session.createQuery("from CustomerInfo").list();
		
		session.close();
		
		
		return cus;
	}

	public String all(){
		
		return "注解成功";
	}
	
	public static void main(String[] args) {

		
		Configuration config=new Configuration().configure("config/hibernet/hibernate.cfg.xml");
		
		SessionFactory f=config.buildSessionFactory();
		
		Session session=f.openSession();
		
		List<CustomerInfo> cus=session.createQuery("from CustomerInfo").list();
		
		session.close();
		
		System.out.println(cus.get(0).getCustomerid());
		
		
//		System.out.println(f.getCurrentSession().createQuery("from CustomerInfo").list());
	}
}

5、实体类

package com.ai.customer.model;

import java.io.Serializable;

public class CustomerInfo implements Serializable {


	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private String customerid;//个人编号
	
	private String cardid;//身份证id
	
	private String name;//姓名
	
	private String sex;//性别(男、女)
	
	private String birthDate;//出生日期
	
	private String householdRegister;//户籍所在地址
	
	private String photo;//照片
	
	private String regTime;
	
	private String loginCount;
	
	private String lastLoginTime;

	public String getCustomerid() {
		return customerid;
	}

	public void setCustomerid(String customerid) {
		this.customerid = customerid;
	}

	public String getCardid() {
		return cardid;
	}

	public void setCardid(String cardid) {
		this.cardid = cardid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

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

	public String getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(String birthDate) {
		this.birthDate = birthDate;
	}

	public String getHouseholdRegister() {
		return householdRegister;
	}

	public void setHouseholdRegister(String householdRegister) {
		this.householdRegister = householdRegister;
	}

	public String getPhoto() {
		return photo;
	}

	public void setPhoto(String photo) {
		this.photo = photo;
	}

	public String getRegTime() {
		return regTime;
	}

	public void setRegTime(String regTime) {
		this.regTime = regTime;
	}

	public String getLoginCount() {
		return loginCount;
	}

	public void setLoginCount(String loginCount) {
		this.loginCount = loginCount;
	}

	public String getLastLoginTime() {
		return lastLoginTime;
	}

	public void setLastLoginTime(String lastLoginTime) {
		this.lastLoginTime = lastLoginTime;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
}

6、customer.hbm.xml配置文件

<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
   
   <hibernate-mapping>
   
   	<class name="com.ai.customer.model.CustomerInfo" table="customerInfo">
   	
   		<id name="customerid" column="customerid" type="java.lang.String">
   			<generator class="assigned"/>
   		</id>
   	
	   	<property name="cardid" type="java.lang.String"/>
	   	<property name="name" type="java.lang.String"/>
	   	<property name="sex" type="java.lang.String"/>
	   	<property name="birthDate" type="java.lang.String"/>
	   	<property name="householdRegister" type="java.lang.String"/>
	   	<property name="photo" type="java.lang.String"/>
	   	<property name="regTime" type="java.lang.String"/>
	   	<property name="loginCount" type="java.lang.String"/>
	   	<property name="lastLoginTime" type="java.lang.String"/>   	
   	</class>
   
   </hibernate-mapping>

7、service 接口

package com.ai.customer.service;

import java.util.List;

import com.ai.customer.model.CustomerInfo;

public interface ICustomerService {

	//查询Customer
	public List<CustomerInfo> queryCustomer();
	
	public String all();
}

8、service接口实现

package com.ai.customer.serviceImpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import com.ai.customer.dao.ICustomerDao;
import com.ai.customer.model.CustomerInfo;
import com.ai.customer.service.ICustomerService;

@Service
public class CustomerService implements ICustomerService{

	@Autowired
	private ICustomerDao customerDao;
	

	public List<CustomerInfo> queryCustomer() {
		return customerDao.queryCustomer();
	}



	public String all() {
		// TODO Auto-generated method stub
		return customerDao.all();
	}

}

9、hibernate.cfg.xml配置文件

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration> 
	    <!--表明下面的配置是针对session-factory配置的。SessionFactory是Hibernate中的一个类,这个类主要负责保存HIbernate的配置信息,以及对Session的操作-->
		<session-factory>
	
		<!--hibernate.dialect 仅仅是Hibernate使用的数据库方言,就是要用Hibernate连接那种类型的数据库server。

--> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.url"> jdbc:mysql://localhost:3306/data </property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <!--数据库连接池的大小--> <property name="hibernate.connection.pool.size">10</property> <!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错,程序执行时能够在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后能够设置为false,提高执行效率--> <property name="hibernate.show_sql">true</property> <!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。

Fetch Size设的越大,读数据库的次数越少,速度越快。Fetch Size越小。读数据库的次数越多。速度越慢--> <property name="jdbc.fetch_size">50</property> <!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快。相同耗用内存就越大--> <property name="jdbc.batch_size">23</property> <!--jdbc.use_scrollable_resultset是否同意Hibernate用JDBC的可滚动的结果集。对分页的结果集。对分页时的设置很有帮助--> <property name="jdbc.use_scrollable_resultset">false</property> <!--connection.useUnicode连接数据库时是否使用Unicode编码--> <property name="Connection.useUnicode">true</property> <!--connection.characterEncoding连接数据库时数据的传输字符集编码方式。最好设置为gbk。用gb2312有的字符不全--> <property name="connection.characterEncoding">gbk</property> <!--连接池的最小连接数--> <property name="hibernate.c3p0.min_size">5</property> <!--最大连接数--> <property name="hibernate.c3p0.max_size">500</property> <!--连接超时时间--> <property name="hibernate.c3p0.timeout">1800</property> <!--statemnets缓存大小--> <property name="hibernate.c3p0.max_statements">0</property> <!--每隔多少秒检測连接是否可正常使用 --> <property name="hibernate.c3p0.idle_test_period">121</property> <!--当池中的连接耗尽的时候,一次性添加的连接数量,默觉得3--> <property name="hibernate.c3p0.acquire_increment">5</property> <property name="hibernate.c3p0.validate">true</property> <mapping resource="com/ai/customer/model/CustomerInfo.hbm.xml" /> </session-factory> </hibernate-configuration>



10、spring-application.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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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-3.2.xsd">
	
	
	<!-- 配置数据源
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	
		
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		
		<property name="url" value="jdbc:mysql://localhost/data"/>
		
		<property name="username" value="root"/>
		
		<property name="password" value="123456"/>
	</bean>
	 -->
	<!-- hibernet 配置 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		
		<!-- <property name="dataSource" ref="dataSource"/> --> 
		
		<property name="configLocation">
			<value>classpath:config/hibernet/hibernate.cfg.xml</value>
		</property>
		
	</bean>
	
	<!-- 配置事务 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 使用代理配置事务管理 -->
	<bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
		<property name="transactionManager" ref="transactionManager" />
		<property name="transactionAttributes">  
	        <props>  
	        <!--  	假设当前没有事务,就新建一个事务,假设已经存在一个事务中,增加到这个事务中。 -->
	            <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>  
	            <prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>  
	            <prop key="del*">PROPAGATION_REQUIRED</prop>  
	            <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
	            <prop key="*">PROPAGATION_REQUIRED</prop>  
	        </props>  
	    </property>  
	</bean>
</beans>

11、spring-mvc.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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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-3.2.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
	
	
<!-- 扫描包 -->
<context:component-scan base-package="com.ai.customer" />

 <!-- 启动注解 -->
 <mvc:annotation-driven />


<!-- 文件上传 -->
 <bean id="multipartResolver"  
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 设置上传文件的最大尺寸为10MB -->  
   <property name="maxUploadSize">  
       <value>10000000</value>  
   </property>  
  </bean>  


<!--  静态文件訪问 -->
 <mvc:default-servlet-handler/> 
 <!-- 对模型视图名称的解析,即在模型视图名称加入前后缀 --> 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
 
 	<property name="prefix" value="/"/>
 	<property name="suffix" value=".jsp"/>	
 </bean> 
 
</beans>

12、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_sh</display-name> <welcome-file-list> <welcome-file>login/login.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring/spring-appliction.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> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring/spring-*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <filter> <filter-name>codeUTF-8</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>codeUTF-8</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <error-page> <error-code>404</error-code> <location>/login/loginIput.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/login/login.jsp</location> </error-page> </web-app>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值