zoukankan      html  css  js  c++  java
  • Java五大框架

    2017-6-13 
    Lifusen 此文章仅代表个人观点,如有问题提出请联系Q:570429601
    1、Hibernate (开放源代码的对象关系映射框架) 
    Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。
    !(Hibernate默认用的是slf4j-nop.jar日志实现方式。
    但是我们可以替换成log4j的实现。但不是简单的加上log4j-1.2.17.jar就行了。
    中间还需要一个转换器slf4j-log4j12-1.5.8.jar)
    1.在src目录下创建hibernate.cfg.xml配置文件(文件名字不能修改)
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC 
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
    <session-factory>
    
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/sampe_h5_db</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <!-- 为Hibernate指定不同数据库的方言 -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    
    <mapping class="sample.h5.entity.User" />
    
        <!-- create and update the database automaticlly -->
    <property name="hbm2ddl.auto">update</property>
    
    <!-- javax.persistence.validation.mode默认情况下是auto的,就是说如果不设置的话它是会自动去你的classpath下面找一个
    bean-validation**包,但是找不到,所以beanvalitionFactory错误 -->
    <property name="javax.persistence.validation.mode">none</property>
    
    </session-factory>
    </hibernate-configuration>
    
    注意: hibernate.hbm2ddl.auto属性不要乱用,也可以不用
    (1)<property name="hibernate.hbm2ddl.auto"> create-drop </property>
    
    create-drop:表示在hebarinate初始化时创建表格,程序运行结束的时候会删除相应的表格,在实际项目中不用
    
    (2)<property name="hibernate.hbm2ddl.auto">create</property>
    
    在hibernate初始化时会创建表格,在运行结束之后不删除表格,而是在下一次运行的时候如果有旧的删掉,没有旧的,重新建表格
    
    (3)<property name="hibernate.hbm2ddl.auto">update</property>
    
    只是根据映射文件去和数据库中的表对应起来,如果不一致,就更新表的结构
    
    (4)<property name="hibernate.hbm2ddl.auto">validate</property>
    
    校验映射文件和数据库中的表是不是能对应起来,不能对应报错,实际中常用
    
    最后一条javax.persistence.validation.mode可以不用,
    加上<mapping class="sample.h5.entity.User" />
    ------------------------------------------------------------------------------------------------------------------------------------------
    @Entity
    @Table(name="tbl_book")
    public class Book {
    
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="bid")
    private Integer id;
    
    @Column(name="btitle")
    private String title;
    
    @ManyToOne    
    @JoinColumn(name="bcategoryid")
    private Category category;
    
    category---    @OneToMany(mappedBy="category")    
    private Set<Book> books;
    
    @Column(name="otime")
    @Temporal(TemporalType.TIMESTAMP)
    private Date time;
    
    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER, mappedBy="order")级联,紧急加载
    private Set<OrderItem> items = new HashSet<OrderItem>();
    
    //组件注解:使用Embedded注解说明,我要使用ZhangHao(组件类)类中的属性来匹配表中的列(数据库没有实体对应)
    @Embedded
    @AttributeOverrides({
    @AttributeOverride(name="username", column=@Column(name="uloginid")),
    @AttributeOverride(name="password", column=@Column(name="uloginpsw"))
    })
    private ZhangHao zhaoHao;
    
    @ElementCollection(fetch=FetchType.EAGER) // 将所有集合的默认抓取策略(fetch),LAZY(延迟加载)设置成EAGER(紧急加载)
    @CollectionTable(name="tbl_tel", joinColumns=@JoinColumn(name="tuid"))
    @Column(name="tphone")    
    @SortNatural
    private SortedSet<String> phones = new TreeSet<String>();
    
    @ElementCollection(fetch=FetchType.EAGER)
    @CollectionTable(name="tbl_score", joinColumns=@JoinColumn(name="suid"))
    @MapKeyColumn(name="scourse")
    @Column(name="sscore")
    @SortNatural
    
    @ElementCollection(fetch=FetchType.EAGER)
    @CollectionTable(name="tbl_recieve", joinColumns=@JoinColumn(name="ruid"))
    @MapKeyColumn(name="rname")    
    @OrderBy(clause="rid")
    private Map<String, Recieve> recieves = new HashMap<String, Recieve>();
    private Map<String, Integer> scores = new HashMap<String, Integer>();
    
    @Column(name="uregistDate", updatable=false)
    // 日期时间类型的注解
    @Temporal(TemporalType.DATE)
    private Date registDate;
    
    // 计算列:该注解修饰的字段(count)是根据注解指定的语句查询计算出来的值,并不存在一个叫做count的列在表中
    @Formula("(select count(*) from tbl_user)")
    private Integer count;
    
    // 瞬时属性的注解:表示Hibernate忽略该属性
    @Transient
    private String other;
    
    hql
    // 查询出一组或一个实体对象
    //List<Book> list = session.createQuery("from Book b where b.title = '西游记'").list();
    查出单个的对象(值)
    //Object result = session.createQuery("select avg(b.price) from Book b").uniqueResult();
    // hql的更新和修改
    //int row = session.createQuery("update Book b set b.price = b.price * 0.8").executeUpdate();    
    //System.out.println("修改了" + row +"本书的价格!");
    
    int pageSize = 2;
    int pageNO = 1;
    List<Book> list = session.createQuery("from Book b where b.price >= :price")
    .setParameter("price", 30.0)
    .setFirstResult((pageNO-1) * pageSize)
    .setMaxResults(pageSize)
    .list();
    //String hql = "from Book b where b.title <> '西游记' and b.price >= 50 ";
    //String hql = "from Book b where b.title like '%记%'";
    //String hql = "from Book b where b.price between 40 and 80";
    //String hql = "from Book b where b.author in ('吴承恩', '司马迁')";
    //String hql = "from Book b where b.category is not null";
    //String hql = "select b from Book b, Category c where b.category = c";
    //String hql = "select b.id, b.title, b.price from Book b";
    //String hql = "select new list(b.id, b.title, b.price) from Book b";
    //String hql = "select new map(b.id as ID, b.title as 标题, b.price as 价格) from Book b";
    //String hql = "select new Book(b.id, b.title, b.price) from Book b";
    //String hql = "from Book b where b.category.name = '历史'";
    //String hql = "select b from Book b left join b.category c where c.name = '历史' ";
    //String hql = "select distinct c from Category c left join fetch c.books b where b.price < 30.0";
    //String hql = "select c from Category c where size(c.books) > 0 order by c.id";
    String hql = "select new map(b.category.name as 分类, count(b) as 图书本数, avg(b.price) as 图书平均售价) from Book b group by b.category having avg(b.price) >= 40.0 order by 图书平均售价 desc";
    
    List<Map> list = session.createQuery(hql).list();
    /*
    List<Order> orders = session.createCriteria(Order.class)
    .add(Restrictions.ge("money", 300.0))
    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
    .list();
    */
    
    连接池
    hibernate.cfg.xml
    <property name="hibernate.c3p0.min_size">5</property><!-- 连接池中最小连接数 -->    
    <property name="hibernate.c3p0.max_size">20</property><!-- 连接池中最大连接数 -->    
    <property name="hibernate.c3p0.timeout">120</property><!-- 设定数据库连接超时时间,以秒为单位。如果连接池中某个数据库连接处于空闲状态且超过timeout秒时,就会从连接池中移除-->    
    <property name="hibernate.c3p0.idle_test_period">3000</property>
    
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    ehcache.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    
    <diskStore path="D:ehcacheData"/>
    
    
    <defaultCache
    maxElementsInMemory="1000"
    eternal="false"
    overflowToDisk="true"
    diskPersistent="true"
    timeToIdleSeconds="120"
    timeToLiveSeconds="240"
    maxElementsOnDisk="10000000"
    diskExpiryThreadIntervalSeconds="120"
    memoryStoreEvictionPolicy="LRU">
    </defaultCache>
    </ehcache>
    
    存储过程
    // 创建了一个存储过程 调用器对象
    ProcedureCall call = session.createStoredProcedureCall("getOrderDetails");
    call.registerParameter("m", Double.class, ParameterMode.IN).bindValue(300.0);
    call.registerParameter("c", Long.class, ParameterMode.OUT);
    
    ProcedureOutputs outputs = call.getOutputs();
    
    // 从存储过程的输出的对象组中,获取输出参数的值
    Long count = (Long) outputs.getOutputParameterValue("c");
    
    // 从存储过程的输出的对象组中获取结果集类型的输出结果
    ResultSetOutput output = (ResultSetOutput) outputs.getCurrent();
    // 从结果集类型的输出结果中,获取数据列表
    List<Object[]> orderinfos = output.getResultList();
    
    
    System.out.println("下单顾客	下单次数	总消费额");
    for(Object[] orderinfo : orderinfos) {
    System.out.println(orderinfo[0] + "	" + orderinfo[1] + "	" + orderinfo[2]);
    }
    System.out.println("
    订单金额在200以上的订单数量是:" + count );
    }
    命名查询
    // 调用session的创建命名查询对象的方法:createNamedQuery
    List<Order> orders = session.createNamedQuery("getOrdersByMoney", Order.class)
    .setParameter("minMoney", 300.0)
    .list();
    
    for(Order o : orders) {
    System.out.println(o.getId() + ", " + o.getCustomer() + ", " + o.getMoney() + ", " + o.getTime() + ", " + o.getItems());
    }
    }
    存储过程2
    @Test
    public void testSencodLevelCache() {
    Category c1 = session.get(Category.class, 1);
    System.out.println(c1.getId() +", " + c1.getName());
    
    session.createQuery("from Category c").setCacheable(true).list();
    }
    
    @Test
    public void testSencodLevelCache2() {
    Category c1 = session.get(Category.class, 1);
    System.out.println(c1.getId() +", " + c1.getName());
    session.createQuery("from Category c").setCacheable(true).list();
    }
    二级缓存
    List<Book> list = session.createQuery("from Book b left join fetch b.category").list();
    for(Book elem : list) {
    System.out.println(elem);
    }
    List<Category> list2 = session.createQuery("select distinct c from Category c left join fetch c.books").list();
    for(Category elem : list2) {
    System.out.println(elem);
    }
    总结:
    
    1、一级缓存是session级别的,二级缓存和查询缓存都是sessionfactory级别的,查询缓存和二级缓存是一起来使用的
    
    2、任何sql执行都会存入到同一个session的一级缓存中去
    
    3、同时开启查询缓存和二级缓存,可以在不同session间共享缓存的结果
    
    4、二级缓存缓存的是实体,不是属性
    
    5、查询缓存的结果如果只是属性,那么查询缓存中存储的是id和属性的值,如果是实体的集合,那么查询缓存存储的只是实体的id,对应的实体会存储到二级缓存中去。
    
    6、不同session间返回数据的顺序是,二级缓存先将数据返回,然后将数据存入本session的一级缓存中去,以便下次调用时的使用
    
    
    2、Struts2:Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互。Struts 2是Struts的下一代产品,是在 struts 1和WebWork的技术基础上进行了合并的全新的Struts 2框架。其全新的Struts 2的体系结构与Struts 1的体系结构差别巨大。Struts 2以WebWork为核心,采用拦截器的机制来处理用户的请求,这样的设计也使得业务逻辑控制器能够与ServletAPI完全脱离开,所以Struts 2可以理解为WebWork的更新产品。虽然从Struts 1到Struts 2有着太大的变化,但是相对于WebWork,Struts 2的变化很小。
    1. web.xml
    <filter>
    <filter-name>struts2-filter</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> 
    </filter>
    <filter-mapping>
    <filter-name>struts2-filter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    如果你的Action类没有继承ActionSupport,而你又没有在struts.xml中对应<action>标签中用method属性指定你自己的方法的话,
    默认就要找execute方法,这时是必须要实现execute方法的,否则Struts2会找不到对应的方法而报错。
    src下面struts.xml
    <struts>
    
    <!-- 配置的是全局的国际化资源包的基础包名 -->
    <constant name="struts.custom.i18n.resources" value="myRes" />
    
    <!-- 配置常量:struts.devMode是控制是否启用开发模式 -->
    <constant name="struts.devMode" value="false" />
    
    <constant name="struts.i18n.encoding" value="UTF-8" />
    
    <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>    
    
    <include file="struts-user.xml" />
    
    <package name="default" extends="struts-default">
    
    
    <!-- 指定当前包中的默认处理器为notFound处理器:当请求到当前包中时,没有匹配到对应的action,则执行该默认action
    <default-action-ref name="notFound" />
    -->
    <action name="notFound">
    <result>/WEB-INF/jsp/not-found.jsp</result>
    </action>
    
    </package>
    
    </struts>
    
    struts-user.xml
    <package name="zjp" extends="struts-default" namespace="/">
    
    <!-- 全局(包范围)结果定义 -->
    <global-results>
    <result name="ex">/WEB-INF/jsp/errorHandle.jsp</result>
    </global-results>
    
    <!-- 全局(包范围)“异常映射”定义 -->
    <global-exception-mappings>
    <exception-mapping result="ex" exception="java.lang.Exception" />
    </global-exception-mappings>
    
    <action name="userLoginForm" class="sample.s2.web.action.UserAction"
    method="loginForm">
    <result name="success" type="dispatcher">
    <param name="location">/WEB-INF/jsp/login.jsp</param>    
    </result>
    </action>
    
    <action name="userLogin" class="sample.s2.web.action.UserAction"
    method="login">
    <result name="success" type="redirectAction">userHome</result>
    <result name="error" type="chain">userLoginForm</result>
    </action>
    
    <action name="userHome" class="sample.s2.web.action.UserAction"
    method="home">
    <result>/WEB-INF/jsp/home.jsp</result>
    </action>
    
    <action name="userRegistForm" class="sample.s2.web.action.UserAction"
    method="registForm">    
    <result>/WEB-INF/jsp/regist.jsp</result>    
    </action>
    
    <action name="userRegist" class="sample.s2.web.action.UserAction" method="regist">    
    <result type="chain">userRegistForm</result>    
    </action>
    
    </package>
    
    <package name="back" extends="struts-default" namespace="/mgr">
    
    <global-results>
    <result name="ex">/WEB-INF/jsp/errorHandle.jsp</result>
    </global-results>
    
    <global-exception-mappings>
    <exception-mapping result="ex" exception="java.lang.Exception" />
    </global-exception-mappings>
    
    <action name="adminLoginForm">
    <result>/WEB-INF/jsp/mgr/admin-login.jsp</result>
    </action>
    </package>
    
    
    <s:debug></s:debug>标签
    type------------chain 、dispatcher 、stream 、redirect 、redirectAction 
    UserAction 继承ActionSupport
    private User u;    有get set 下面有
    private Integer id;
    private String name;
    private Integer age;
    private Date birthdate;
    private boolean married;
    private List<Integer> luckyNumbers; 
    private List<Parent> parents;
    private List<Game> games;
    
    国际化资源包myRes_zh_CN.properties 、myRes_en_US.properties
    <a href="/SampleStruts2/userLoginForm?request_locale=zh_CN">中文</a> | <a href="/SampleStruts2/userLoginForm?request_locale=en_US">English</a>
    user.home.header=Hello:{0},Welcome to the site!
    <h3><s:text name="user.home.header"><s:param>${currLoginId }</s:param></s:text></h3>
    前端:<p><s:text name="user.login.form.label.loginId" /><input type="text" name="u.loginId" value="${loginId }" /></p>
    后端:ctx.put("loginErrorMsg", super.getText("user.login.faile"));
    服务器异常查看
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>服务器异常</title>
    <script type="text/javascript">
    
    function showDetails() {
    document.getElementById('details').style.display = 'block';
    }
    </script>
    </head>
    <body>
    <h3>Sorry,服务器出错了,请稍后再试!</h3>
    <p><a href="javascript: showDetails();">技术人员,查看详情</a></p>
    
    <div id='details' style="font-size:12px; color: red; display:none;">
    <p style="font-size:14px; font-weight: bold;">${ exception }</p>
    
    <s:iterator value="#request.exception.stackTrace">
    <p><s:property /></p>
    </s:iterator>
    </div>
    </body>
    </html>
    
    传入id转成类
    <p>喜欢的游戏:
    <s:iterator value="#allGames" var="g">
    <input type="checkbox" name="u.games" value="${g.id }" />${g.name }&nbsp;
    </s:iterator>
    </p>
    src下面xwork-conversion.properties
    内容sample.s2.entity.Game=sample.s2.web.typeconverter.GameTypeConverter
    GameTypeConverter extends StrutsTypeConverter 内容
    @Override
    public Object convertFromString(Map context, String[] params, Class kls) {
    int id = Integer.parseInt(params[0]);
    Game game = new Game();
    game.setId(id);
    return game;
    }
    
    @Override
    public String convertToString(Map arg0, Object obj) {
    Game game = (Game)obj;
    return "游戏信息:id=" + game.getId() + ", name=" + game.getName();
    }
    
    struths验证 userAction
    private User u;    
    同包下面userAction_zh_CN.properties
    invalid.fieldvalue.u.age=u7528u6237u5E74u9F84u503Cu683Cu5F0Fu9519u8BEFuFF0Cu5FC5u987Bu662Fu4E2Au6574u6570 //年龄格式错误,必须是个整数
    invalid.fieldvalue.u.birthdate=u51FAu751Fu65E5u671Fu683Cu5F0Fu9519u8BEFuFF0Cu5E94u8BE5u4F8Bu5982uFF1A1995-01-01 //出生日期格式错误,应该例如:1995-01-01
    如果没有就在xwork.default.invalid.fieldvalue=u6570u636Eu7684u683Cu5F0Fu9519u8BEFu201C{0}u201D //数据的格式错误
    前端显示<s:property value="[0].fieldErrors" />
    格式验证失败返回input
    
    上传文件
    <action name="userRegist" class="sample.s2.web.action.UserAction" method="regist">
    <interceptor-ref name="fileUpload">
    <param name="allowedTypes">image/jpeg, image/png, image/gif</param>
    <param name="maximumSize">1024000</param>
    </interceptor-ref>
    <interceptor-ref name="myDefault"/>
    <result name="input" type="chain">userRegistForm</result>    
    </action>
    
    userAction_zh_CH.properties
    struts.messages.error.uploading=Error uploading: {0}
    struts.messages.error.file.too.large=u6587u4EF6{1}u592Au5927u4E86uFF0Cu5FC5u987Bu5C0Fu4E8E {4} u5B57u8282uFF01
    struts.messages.error.content.type.not.allowed=u5934u50CFu6587u4EF6u5FC5u987Bu662Fu56FEu7247
    struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}
    
    
    private File face;    
    if(face != null) {
    System.out.println("face: " + face);
    
    System.out.println("faceContentType: " + faceContentType);
    /* 获取相对网站根路径的相应的磁盘路径 */
    String realPath = ServletActionContext.getServletContext().getRealPath("/upload/" + faceFileName);
    try {
    FileUtils.copyFile(face, new File(realPath));
    } catch (IOException e) {
    e.printStackTrace();
    }
    } else {
    System.out.println("用户未上传头像");
    
    强加验证
    UserAction-userRegist-validation.xml
    <field name="u.age">
    <field-validator type="required">
    <message>年龄必填</message>
    </field-validator>
    <field-validator type="int">
    <param name="min">18</param>
    <param name="max">40</param>
    <message>年龄必须在18到40岁之间</message>
    </field-validator>
    </field>
    
    <field name="u.birthdate">
    <field-validator type="required">
    <param name="trim">true</param>
    <message>出生日期不能为空</message>
    </field-validator>
    </field>
    
    </validators>
    前端
    <s:property value="[1].fieldErrors['u.birthdate'][0]" />
    自定义验证类型
    src validators.xml
    <validators>
    <validator name="zip" class="sample.s2.web.validator.ZipValidator" />
    </validators>
    
    class
    public class ZipValidator extends FieldValidatorSupport {
    
    @Override
    public void validate(Object action) throws ValidationException {
    String fieldName = super.getFieldName(); // "zip"
    String fieldValue = (String) super.getFieldValue(fieldName, action); // "610000"
    if(fieldValue != null && !fieldValue.equals("")) {
    System.out.println("fieldName: " + fieldValue);
    System.out.println("fieldValue: " + fieldValue);
    if(!Pattern.matches("^\d{6}$", fieldValue)) {
    super.addFieldError(fieldName, action);
    }
    }
    }
    
    }
    
    UserAction-userRegist-validation.xml
    <field name="zip">
    <field-validator type="zip">    
    <message>邮政编码格式错误!</message>
    </field-validator>
    </field>
    
    拦截器
    <!-- 声明拦截器 -->
    <interceptors>
    <interceptor name="sample" class="sample.s2.web.interceptor.SampleInterceptor" />
    <interceptor name="log" class="sample.s2.web.interceptor.LogInterceptor">
    <param name="datePattern">yyyy年MM月dd日 HH点mm分ss秒</param>
    </interceptor>
    <interceptor-stack name="myDefault">
    <interceptor-ref name="log" />
    <interceptor-ref name="defaultStack" />
    </interceptor-stack>
    </interceptors>
    
    <!-- 配置默认拦截器引用: 该包下的所有未直接配置拦截器引用的action,都使用myDefault这个拦截器栈 -->
    <default-interceptor-ref name="myDefault" />
    
    文件下载
    <action name="download" class="sample.s2.web.action.ResourceAction" method="download">
    <result name="success" type="stream">
    <param name="inputName">is</param>
    <param name="contentType">${contentType}</param>
    <param name="contentDisposition">attchement;filename=${fileName}</param>
    <param name="bufferSize">4096</param>
    </result>
    </action>
    
    private Integer rid;
    
    private InputStream is;
    private String fileName;
    private String contentType; //get set
    public String download() throws UnsupportedEncodingException {
    
    System.out.println("download... rid: " + rid);
    if(rid == 1001) {
    // 想下载/WEB-INF/resources/bbs_gd.doc
    this.is = ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/resources/bbs_gd.doc");
    this.fileName = URLEncoder.encode("bbs设计文档.doc", "utf-8");
    System.out.println("fileName encode: " + this.fileName);
    System.out.println("fileName decode: " + URLDecoder.decode(this.fileName, "UTF-8"));
    this.contentType="application/msword";
    } else if(rid == 1002) {
    // 想下载10.jpg
    this.is = ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/resources/10.jpg");
    this.fileName = "10.jpg";
    this.contentType = "image/jpeg";
    }
    // ActionContext.getContext().put("downloadError", "下载失败:必须是登录用户才能下载,现在马上<a href='#'>去登录</a>。");
    return SUCCESS;
    }
    
    private InputStream fengJingInputName;
    
    @Override
    public String execute() throws Exception {
    
    this.fengJingInputName = ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/resources/Ajax:2.avi");
    return SUCCESS;
    }
    
    <action name="downloadFengJing" class="sample.s2.web.action.DownloadFengJingAction">
    <!-- 启用拦截器:为当前处理器 -->
    <interceptor-ref name="sample" />    
    <interceptor-ref name="myDefault" />
    <result type="stream">
    <param name="inputName">fengJingInputName</param>
    <param name="contentDisposition">attchement;filename=Ajax:2.avi</param>
    </result>
    </action>
    
    权限验证
    <package name="management" extends="json-default" namespace="/mgr">
    <interceptors>
    <!-- 声明“权限验证”拦截器 -->
    <interceptor name="authority" class="sample.s2.web.interceptor.mgr.AuthorityInterceptor">
    <param name="excludeMethods">loginForm,loginCheck</param>
    </interceptor>
    
    <!-- 声明“后台管理默认拦截器栈” -->
    <interceptor-stack name="mgrDefaultStack">
    <interceptor-ref name="authority" />
    <interceptor-ref name="defaultStack" />
    </interceptor-stack>
    </interceptors>
    
    AuthorityInterceptor.java
    
    @SuppressWarnings("serial")
    public class AuthorityInterceptor extends MethodFilterInterceptor {
    
    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {    
    ActionContext ctx = invocation.getInvocationContext();
    if(ctx.getSession().get("currAdmin") == null) {
    ctx.put("tip", "请先登录,再进行其他操作!");
    return "login";
    } else {
    return invocation.invoke();
    }    
    }
    
    }
    <action name="getRandom" class="sample.s2.web.action.mgr.DemoAjaxAction" method="getRandom">
    <result type="stream">
    <param name="inputName">bais</param>
    <param name="contentType">text/html;charset=UTF-8</param>
    </result>
    </action>
    action name="getAllAdmins" class="sample.s2.web.action.mgr.DemoAjaxAction" method="getAllAdmins">
    <result type="json">
    <param name="root">admins</param>
    <param name="contentType">application/json;charset=UTF-8</param>
    </result>
    </action>
    
    private String type;    
    private InputStream bais; 
    private List<Admin> admins;
    
    public String getRandom() throws Exception {
    
    int offset = type.equals("small") ? 0 : 5;
    
    String r = (int)(Math.random() * 5) + offset + "";    // "9"
    
    
    
    bais = new ByteArrayInputStream(r.getBytes("utf-8"));
    
    return SUCCESS;
    }
    
    public String getAllAdmins() {
    admins = adminService.getAdmins();
    return SUCCESS;
    }
    
    $(function(){
    
    $.get("/SampleStruts2/mgr/getRandom", {"type" : "small"}, function(data){    
    $("#num").text(data);    
    });
    
    $.getJSON("/SampleStruts2/mgr/getAllAdmins", function(data){
    alert(data.length);    
    });
    
    });
    
    
    3、Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。
    简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。
    src下面 applicationContext.xml
    <bean id="inkPrinter" class="demo.spring4.bean.InkPrinter" />
    
    <bean id="lesserPrinter" class="demo.spring4.bean.LesserPrinter" />
    
    <bean id="computer" class="demo.spring4.bean.Computer">
    <property name="printer" ref="lesserPrinter" />
    </bean>
    
    <bean id="zwj" class="demo.spring4.bean.Student" scope="prototype">
    <property name="name" value="张无忌" />
    <property name="age" value="23" />
    <property name="birthdate">
    <bean class="java.util.Date" />
    </property>
    <property name="lover" ref="zm" />
    <property name="loveBooks">
    <list>
    <value>西游记</value>
    <value>水浒传</value>
    <value>三国演义</value>
    <value>红楼梦</value>
    </list>
    </property>
    <property name="scores">
    <map>
    <entry key="HTML" value="95" />
    <entry key="JSP" value="87" />
    <entry key="JavaBasic" value="91" />
    </map>
    </property>
    <property name="healthPoster">
    <props>
    <prop key="height">1.81</prop>
    <prop key="weight">82</prop>
    </props>
    </property>
    </bean>
    
    <bean id="zm" class="demo.spring4.bean.Student">
    <constructor-arg index="0" value="赵敏" />
    <constructor-arg index="1" value="22" />    
    <property name="birthdate" ref="now" /><!-- ref属性代表引用了容器中的其他Bean的ID -->
    </bean>
    
    <bean id="now" class="java.util.Date" />
    
    src test.properties
    # a common properties file
    name=u5F20u4E09
    age=23
    sex=male
    height=1.79
    
    public void testProperties() {
    /*
    Properties props = System.getProperties();
    for(Object key : props.keySet()) {
    System.out.println(key + " = " + props.get(key));
    }
    */
    
    Properties props = new Properties();
    try {
    props.load(new InputStreamReader(Spring4Test.class.getResourceAsStream("/test.properties"), "UTF-8"));
    System.out.println(props);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    
    ApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml");
    System.out.println("-- ApplicationContext 已经创建完成 -----------------------------
    ");
    
    context.getBean("zwj");
    context.getBean("zwj");
    ApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml");
    System.out.println("-- ApplicationContext 已经创建完成 -----------------------------
    ");
    
    context.getBean("zwj");
    context.getBean("zwj");
    
    4、Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,
    从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等。
    WEB-INF下面
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    
    <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-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    </web-app>
    
    src下面    springmvc-servlet.xml
    <context:component-scan base-package="demo.springmvc.web.controller" />
    
    <mvc:annotation-driven />
    
    <!-- 防止无法正确访问静态资源 -->
    <mvc:default-servlet-handler/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
    </bean>
    
    controller页面
    @Controller
    @RequestMapping("/mvc")
    public class mvcController { //类上面
      @Controller 负责注册一个bean 到spring 上下文中
    
      @RequestMapping 注解为控制器指定可以处理哪些 URL 请求
    Date类型转
    //the parameter was converted in initBinder
    @RequestMapping("/date")
    public String date(Date date){
    System.out.println(date);
    return "hello";
    }
    
    //At the time of initialization,convert the type "String" to type "date"
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
    binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
    true));
    }
    
    //pass the parameters to front-end
    @RequestMapping("/show")
    public String showPerson(Map<String,Object> map){
    Person p =new Person();
    map.put("p", p);
    p.setAge(20);
    p.setName("jayjay");
    return "show";
    }
      前台可在Request域中取到"p"
    
    //pass the parameters to front-end using ajax
    @RequestMapping("/getPerson")
    public void getPerson(String name,PrintWriter pw){
    pw.write("hello,"+name); 
    }
    @RequestMapping("/name")
    public String sayHello(){
    return "name";
    }
      前台用下面的Jquery代码调用
    
    
    $(function(){
    $("#btn").click(function(){
    $.post("mvc/getPerson",{name:$("#name").val()},function(data){
    alert(data);
    });
    });
    });
    
    //redirect 
    @RequestMapping("/redirect")
    public String redirect(){
    return "redirect:hello";
    }
    
     
  • 相关阅读:
    SQL 索引
    SQL 存储
    C#编程中的66个好习惯,你有多少个?
    Delphi中如何让窗口最小化至系统托盘
    浅谈 堆和堆栈
    C#编程中的66个好习惯
    用ADO连接oracle的步骤
    如何卸载ocx包
    数据库中,Decimal数据类型
    [转载]内存区划分、内存分配、常量存储区、堆、栈、自由存储区、全局区
  • 原文地址:https://www.cnblogs.com/lifusen/p/7278873.html
Copyright © 2011-2022 走看看