java学习

java学习

 

用注解的方式加事务

在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:p
="http://www.springframework.org/schema/p"
         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-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

">
<!-- 使用注解支持事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 添加jdbc的任务管理器 -->
<bean  id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass"  value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl"  value="jdbc:mysql:///mydb"/>
<property name="properties">
<props>
    
<prop key="user">root</prop>
    
<prop key="password">root</prop>
    
</props>
</property>
</bean>
<bean id="simpleJdbcTemplate"  class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
    
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<!-- 在使用事务时不能配置jdbc模板,只能配置数据流 -->
<bean  id="userdao" class="com.yjw.dao.UserDao">
    
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="userService"  class="com.yjw.service.UserService">
    
<!-- name的值只和set方法后面的有关,要一样 -->
    
<property name="dao"  ref="userdao"></property>
</bean>
</beans>在service里加:
//在类的头上加上这个注解,代表这个类的所有方法都加上了事务,
//作用是某个方法里的代码要么都执行,要么都不执行
//默认是在发生RunTimeException是才回滚,发生Exception不回滚
//加上(rollbackFor=Exception.class)表示所有的异常都回滚
@Transactional(rollbackFor=Exception.class)
public class UserService {

    
private  UserDao  userdao;
    
    

    
public void setDao(UserDao userdao) {
        
this.userdao = userdao;
    }

    
    
public  void  save(User user){
        userdao.save(user);
    }

    
//只读,会使性能提高,推荐使用
    @Transactional(readOnly=true)
    
public  User findById(int id){
        
return userdao.findById(id);
    }

}

posted @ 2012-05-03 22:16 杨军威 阅读(2968) | 评论 (0)编辑 收藏

Spring对jdbc的支持

     摘要: Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->在applicationContext.xml文件里写:<?xml version="1.0" encoding="UTF-8"?><beans xmlns...  阅读全文

posted @ 2012-05-02 10:41 杨军威 阅读(6067) | 评论 (0)编辑 收藏

用struts2给的jar包解析json

1,添加jar包struts2-json-plugin-2.3.1.2.jar
2.在json-struts.xml里配置
    
<package name="myjson"  extends="json-default">
            
<action name="myjson"  class="com.yjw.web.MyjsonAction">
                
<result  type="json">
                    
<!--找到根节点-->
                
<param name="root">user</param>
                
<!--浏览器不要缓存-->
                
<param name="noCache">true</param>
                
<!--GZIP网页压缩协议,可以让传送更快,省流量-->
                
<param name="enableGZIP">true</param>
                    
<!--排除action里是null的属性-->
                
<param name="excludeNullProperties">true</param>
                
</result>
            
</action>
        
</package>
在MyjsonAction里写:
package com.yjw.web;

import com.opensymphony.xwork2.Action;

public class MyjsonAction  implements  Action {
    
private User user;
    
private String x;

    
public String execute() throws Exception {
        user 
= new  User();
        user.setId(
1);
        user.setMoney(
22);
        user.setName(
"tom");
        
        
return "success";
    }


    
public User getUser() {
        
return user;
    }


    
public void setUser(User user) {
        
this.user = user;
    }


    
public String getX() {
        
return x;
    }


    
public void setX(String x) {
        
this.x = x;
    }


}

posted @ 2012-05-01 10:42 杨军威 阅读(2036) | 评论 (1)编辑 收藏

输出xml

在struts2.Xml中写:
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE struts PUBLIC
    
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
    
<struts>
        
<package name="myxml"  extends="struts-default">
        
<!-- 输出xml的方法不写result -->
            
<action name="xml" class="com.yjw.web.MyxmlAction"></action>
        
</package>
    
</struts>
在action中写:
package com.yjw.web;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;

public class MyxmlAction implements  Action{

    
public String execute() throws Exception {
        HttpServletResponse  response 
= ServletActionContext.getResponse();
        response.setContentType(
"text/xml;charset=UTF-8");
        PrintWriter  out 
= response.getWriter();
        out.print(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.print(
"<root>");
        
for(int i=0;i<5;i++){
            out.print(
"<person>");
            out.print(
"<name>person"+i+"</name>");
            out.print(
"</person>");
        }

        out.print(
"</root>");
        
//一定要返回null
        return null;
    }


}

在jsp里写:
<body>
  
<input  type="button"  value="xml"  id="btnxml"/>
  
<div  id="mydiv"></div>
  
<script type="text/javascript"  src=js/jquery-1.5.1.min.js></script>
  
<script  type="text/javascript">
              $(document).ready(function()
{
                  $(
"#btnxml").click(function(){
                      $.get(
"xml.action",function(xml){
                          $(xml).find(
"person").each(function(){
                              var name 
= $(this).find("name").text();
                              $(
"#mydiv").html($("#mydiv").html()+name+'<br/>');
                          }
);
                      }
);
                      
                  }
);
              }
);
  
</script>
  
</body>

posted @ 2012-04-30 09:30 杨军威 阅读(1410) | 评论 (0)编辑 收藏

Struts2下载文件的程序

在jsp里写:
  
<a href="download.action">点此下载文件</a>

在struts.xml中:
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE struts PUBLIC
    
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
    
<struts>
        
<package name="mydown" extends="struts-default">
            
<action name="download" class="com.yjw.web.DownAction">
                
<param name="id">1</param>
                
<result type="stream">
                
                
                    
<!-- 下载文件的mime类型 -->
                    
<param name="contentType">${fileType}</param>
                    
<!-- 下载文件的描述 -->
                    
<param name="contentDisposition">attachment;filename=${fileName}</param>
                    
<!-- 设置缓冲区大小 -->
                    
<param name="bufferSize">1024</param>
                    
<!-- 获得文件名的getxxx方法的名字 ,不包含get-->
                    
<param name="inputName">inputStream</param>
                
</result>
            
</action>
        
</package>
    
</struts>
在action中的程序:
package com.yjw.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
public class DownAction implements  Action{
    
private String fileName;
    
private String id;
    
private String fileType;
    
public String execute() throws Exception {
        
return "success";
    }

public InputStream  getInputStream() throws IOException{
    String path 
= ServletActionContext.getServletContext().getRealPath("/");
    
if(id.equals("1")) {
        path 
= path + "download/less.pdf";
        fileName 
= "css.pdf";
        fileType 
= "application/pdf";
    }
 else {
        path 
= path + "download/data.xlsx";
        fileName 
= "data.xlsx";
        fileType 
= "application/vnd.ms-excel";
    }

        FileInputStream  stream 
= new  FileInputStream(new File(path));
    
return stream;
    }

public String getFileName() {
    
return fileName;
}

public void setFileName(String fileName) {
    
this.fileName = fileName;
}

public String getId() {
    
return id;
}

public void setId(String id) {
    
this.id = id;
}

public String getFileType() {
    
return fileType;
}

public void setFileType(String fileType) {
    
this.fileType = fileType;
}

}

posted @ 2012-04-29 19:36 杨军威 阅读(189) | 评论 (0)编辑 收藏

创建一个excel文件

HSSFWorkbook wb = new HSSFWorkbook();
    FileOutputStream fileout 
= new FileOutputStream("d:/b.xls");
    wb.write(fileout);
    fileout.close();

posted @ 2012-04-29 19:34 杨军威 阅读(127) | 评论 (0)编辑 收藏

验证码的使用



验证码:



1, 导入jarjcaptcha验证码



2.web.xml里配置<servlet>



     <servlet-name>j</servlet-name>



    <servlet-class>com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet</servlet-class>



   </servlet>



   <servlet-mapping>



     <servlet-name>j</servlet-name>



     <url-pattern>/jcaptcha.jpg</url-pattern>



   </servlet-mapping>



3.在页面上写



<form action="vali.action" method="post">



     <input type="text" name="name"/>



     <a href="javascript:void(0)"
id="mya"><img src="jcaptcha.jpg" id="myimg"/></a>



     <input type="submit" value="save"/>



   </form>



 <script type="text/javascript" src=js/jquery-1.5.1.min.js></script>



 <script type="text/javascript">



       $(document).ready(function(){



          $("#mya").click(function(){



            $("#myimg").attr("src","jcaptcha.jpg?xxx=" + Math.random());



          });



4.struts-vali.xml里写



<?xml version="1.0"
encoding="UTF-8"?>



 <!DOCTYPE struts
PUBLIC



   "-//Apache Software Foundation//DTD Struts
Configuration 2.1.7//EN"



   "http://struts.apache.org/dtds/struts-2.1.7.dtd">



   <struts>



     <package name="myvali"
extends="struts-default">



        <action name="vali" class="com.yjw.web.ValiAction">



       



          <result>WEB-INF/views/list.jsp</result>



          <result name="error">WEB-INF/views/main.jsp?id=1</result>



        </action>



     </package>



   </struts>



5.ValiAction里写:



package com.yjw.web;



 



import org.apache.struts2.ServletActionContext;



import
com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;



import com.opensymphony.xwork2.Action;



 



public class ValiAction implements Action{



   private String name;



   public String execute() throws Exception {



     boolean result = SimpleImageCaptchaServlet.validateResponse(ServletActionContext.getRequest(),
name);



     System.out.println(result);



     if(result){



        return "success";



     }else {



        return "error";



     }



    



   }



   public String getName() {



     return name;



   }



   public void setName(String name) {



     this.name = name;



   }



 



}


posted @ 2012-04-28 22:52 杨军威 阅读(364) | 评论 (0)编辑 收藏

java 中文件的复制,查询,删除

javaIO中,文件的查询和删除,文件的复制程序如下:

普通的复制是:

public class Acopy {

 public void copy(String oldpath,String  newpath ) throws IOException {

    File of = new File(oldpath);

    File nf = new File(newpath);

    if(!nf.exists()){

      nf.createNewFile();

    }

    FileInputStream i = new FileInputStream(of); 

    FileOutputStream o = new FileOutputStream(nf);

    int b= 0;

    byte[] buffer = new byte[100];

    while((b=i.read(buffer))!=-1){

      o.write(buffer, 0, b-1);

    }

    i.close();

    o.flush();

    o.close();

  }

}

加强的复制是:

public class Bcopy {

 public void copy(String opath,String npath) throws IOException{

    File of = new File(opath);

    File nf = new File(npath);

    if(!nf.exists()){

      nf.createNewFile();

    }

    FileInputStream i = new FileInputStream(of);

    BufferedInputStream bi = new BufferedInputStream(i);

    FileOutputStream o = new FileOutputStream(nf);

    BufferedOutputStream bo = new BufferedOutputStream(o);

    int b = 0;

    byte[] buffer = new byte[100];

    while((b=bi.read(buffer))!=-1){

      bo.write(buffer, 0, b-1);

    }

    bi.close();

    bo.flush();

    bo.close();

  }

}

文件的查询是:

public void show(String path){

    File f = new File(path);

    if(f.isFile()){

      System.out.println(f.getPath());

    }else if(f.isDirectory()){

      File[] files = f.listFiles();

      if(files!=null){

        for(File file : files){

          if(file.isFile()){

            System.out.println(file.getPath());

          }else if(file.isDirectory()){

            System.out.println("["+file.getPath()+"]");

            show(file.getPath());

          }

        }

      }

    }

  }

文件的删除是:

public void del(String path){

    File f = new File(path);

    if(f.isFile()){

      f.delete();

    }else if(f.isDirectory()){

      File[] files = f.listFiles();

      if(files.length==0){

        f.delete();

      }else if(files!=null){

        for(File file : files){

          if(file.isFile()){

            file.delete();

          }else if(file.isDirectory()){

            del(file.getPath());

          }

        }

      }

    }

    f.delete();

  }

posted @ 2011-11-26 12:27 杨军威 阅读(295) | 评论 (0)编辑 收藏

java线程

在建立线程时,有两种方式,1是继承java.lang.Thread类,重写run方法,此方法用于你想让线程干的事,在调用此方法时,不能直接调用run方法,要调用start方法,如果想访问此线程,使用Thread.currentThread()方法。2,是实现Runnable接口,在调用时,因为接口没有start方法,所以要先创建出实现类的的对象, 再创建出Thread的对象,把实现类的对象传入Thread的对象的构造方法中,再用Thread的对象调用start()方法。

线程有生命周期的,新建 ,就绪,运行,死亡。新建以后只有调用start方法才处于就绪队列,处于就绪队列的线程在获得处理机资源后处于运行,在运行过程中,如果调用sleep方法,或IO阻塞例如Scanner输入,或等待同步锁,或等待通知时就处于阻塞,这是释放处理机资源,在sleep时间到,或IO方法返回,或获得同步锁,或受到通知后,处于就绪队列,线程在run执行完成,或Error,或exeception时,就死亡。可以调用stop方法让线程死亡,但是禁止使用,可以使用isAlive方法判断线程是否死亡,该方法在线程处于就绪,运行,阻塞时返回true,处于新建和死亡时返回false,线程一旦死亡,不能再次调用start方法让线程重新执行。

当一个程序在执行中被另外一个线程插队,并且后来的线程需要先执行完后原来的线程才能执行,就要让插队线程先调用start方法,再调用join方法,进行插队。

守护线程就是在主线程死亡后,守护线程也随之死亡,在使用时让守护线程的对象先调用setDaemon(true)方法,再调用start方法。

当多个线程同时对同一个对象的实例属性进行操作时,会引起线程的同步问题,为了消除线程的同步,可用synchronized来修饰有可能引起线程同步的方法,也可用用synchronized(this)

{方法代码} ,设置同步代码块,在JDK1.5以上的版本可使用同步锁来操作,具体做法是:

Private final ReentrantLock  lock = new ReentrantLock();

在方法内部定义lock.lock();在程序执行完毕后,一定要解锁,lock.unlock();

posted @ 2011-11-25 18:33 杨军威 阅读(251) | 评论 (0)编辑 收藏

java中文件的处理1

一,复制文件
        File oldFile = new File("F:/FavoriteVideo/0CAMGLN0K.jpg");
File newFile = new File("F:/FavoriteVideo/yang.jpg");
if(!oldFile.exists()){
newFile.createNewFile();
}
FileInputStream input = new FileInputStream(oldFile);
/*如果你想让文件的复制加快BufferedInputStream bufferedInput = new BufferedInputStream(input);*/
FileOutputStream output = new FileOutputStream(newFile );
/*BufferedOutputStream bufferedOut = new BufferedOutputStream(output);*/
byte[]  buffer = new byte[512];
int b = 0;
long startTime = System.currentTimeMillis();
while(b!=-1){
b=input.read(buffer);
output.write(buffer, 0, buffer.length);
}
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
input.close();
output.flush();
output.close();
二文件的查询方法
public class ShowFilePath {
public void show(String path){
File f = new File(path);
if(f.isFile()){
System.out.println(f.getPath());
}else if(f.isDirectory()){
File[] files = f.listFiles();
if(files!=null){
for(File file:files ){
if(file.isFile()){
System.out.println(file.getPath());
}else {
System.out.println("["+file.getPath()+"]");
show(file.getPath());
}
}
}
}






posted @ 2011-11-18 13:13 杨军威 阅读(176) | 评论 (0)编辑 收藏

仅列出标题
共43页: First 上一页 35 36 37 38 39 40 41 42 43 下一页 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜