springmvc 例

来源:互联网 发布:影楼网络推广包括什么 编辑:程序博客网 时间:2024/05/28 15:26

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 配置监听器 具体去网上搜索 *   */@Controllerpublic class CustomerAction {@Autowiredprivate 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 {//查询Customerpublic 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;@Repositorypublic class CustomerDao implements ICustomerDao {@Autowiredprivate 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;//身份证idprivate 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 {//查询Customerpublic 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;@Servicepublic class CustomerService implements ICustomerService{@Autowiredprivate ICustomerDao customerDao;public List<CustomerInfo> queryCustomer() {return customerDao.queryCustomer();}public String all() {// TODO Auto-generated method stubreturn 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连接那种类型的数据库服务器。--><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.xsdhttp://www.springframework.org/schema/contexthttp://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.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/mvchttp://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
原创粉丝点击