java五大框架有哪些 您所在的位置:网站首页 java服务端框架有哪些 java五大框架有哪些

java五大框架有哪些

2023-04-24 17:38| 来源: 网络整理| 查看: 265

2017-6-13Lifusen 此文章仅代表个人观点,如有问题提出请联系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配置文件(文件名字不能修改)

/p>

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/sampe_h5_db

root

root

org.hibernate.dialect.MySQL5Dialect

true

true

update

none

注意: hibernate.hbm2ddl.auto属性不要乱用,也可以不用

(1) create-drop create-drop:表示在hebarinate初始化时创建表格,程序运行结束的时候会删除相应的表格,在实际项目中不用

(2)create在hibernate初始化时会创建表格,在运行结束之后不删除表格,而是在下一次运行的时候如果有旧的删掉,没有旧的,重新建表格

(3)update只是根据映射文件去和数据库中的表对应起来,如果不一致,就更新表的结构

(4)validate校验映射文件和数据库中的表是不是能对应起来,不能对应报错,实际中常用

最后一条javax.persistence.validation.mode可以不用,

加上

------------------------------------------------------------------------------------------------------------------------------------------@Entity

@Table(name="tbl_book")public classBook {

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)

@Column(name="bid")privateInteger id;

@Column(name="btitle")privateString title;

@ManyToOne

@JoinColumn(name="bcategoryid")privateCategory category;

category--- @OneToMany(mappedBy="category")private Setbooks;

@Column(name="otime")

@Temporal(TemporalType.TIMESTAMP)privateDate time;

@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER, mappedBy="order")级联,紧急加载private Set items = new HashSet();//组件注解:使用Embedded注解说明,我要使用ZhangHao(组件类)类中的属性来匹配表中的列(数据库没有实体对应)

@Embedded

@AttributeOverrides({

@AttributeOverride(name="username", column=@Column(name="uloginid")),

@AttributeOverride(name="password", column=@Column(name="uloginpsw"))

})privateZhangHao zhaoHao;

@ElementCollection(fetch=FetchType.EAGER) //将所有集合的默认抓取策略(fetch),LAZY(延迟加载)设置成EAGER(紧急加载)

@CollectionTable(name="tbl_tel", joinColumns=@JoinColumn(name="tuid"))

@Column(name="tphone")

@SortNaturalprivate SortedSet phones = new TreeSet();

@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 recieves = new HashMap();private Map scores = new HashMap();

@Column(name="uregistDate", updatable=false)//日期时间类型的注解

@Temporal(TemporalType.DATE)privateDate registDate;//计算列:该注解修饰的字段(count)是根据注解指定的语句查询计算出来的值,并不存在一个叫做count的列在表中

@Formula("(select count(*) from tbl_user)")privateInteger count;//瞬时属性的注解:表示Hibernate忽略该属性

@TransientprivateString other;

hql//查询出一组或一个实体对象//List 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 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 list =session.createQuery(hql).list();/*List orders = session.createCriteria(Order.class)

.add(Restrictions.ge("money", 300.0))

.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)

.list();*/连接池

hibernate.cfg.xml5

20

120

3000

org.hibernate.cache.ehcache.EhCacheRegionFactory

true

trueehcache.xml

maxElementsInMemory="1000"eternal="false"overflowToDisk="true"diskPersistent="true"timeToIdleSeconds="120"timeToLiveSeconds="240"maxElementsOnDisk="10000000"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU">

存储过程//创建了一个存储过程 调用器对象

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 orderinfos =output.getResultList();

System.out.println("下单顾客\t下单次数\t总消费额");for(Object[] orderinfo : orderinfos) {

System.out.println(orderinfo[0] + "\t" + orderinfo[1] + "\t" + orderinfo[2]);

}

System.out.println("\n订单金额在200以上的订单数量是:" +count );

}

命名查询//调用session的创建命名查询对象的方法:createNamedQuery

List 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

@Testpublic voidtestSencodLevelCache() {

Category c1= session.get(Category.class, 1);

System.out.println(c1.getId()+", " +c1.getName());

session.createQuery("from Category c").setCacheable(true).list();

}

@Testpublic voidtestSencodLevelCache2() {

Category c1= session.get(Category.class, 1);

System.out.println(c1.getId()+", " +c1.getName());

session.createQuery("from Category c").setCacheable(true).list();

}

二级缓存

List list = session.createQuery("from Book b left join fetch b.category").list();for(Book elem : list) {

System.out.println(elem);

}

List 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

struts2-filter

org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter

struts2-filter

/*

如果你的Action类没有继承ActionSupport,而你又没有在struts.xml中对应标签中用method属性指定你自己的方法的话,

默认就要找execute方法,这时是必须要实现execute方法的,否则Struts2会找不到对应的方法而报错。

src下面struts.xml

/WEB-INF/jsp/not-found.jsp

struts-user.xml

/WEB-INF/jsp/errorHandle.jsp

method="loginForm">

/WEB-INF/jsp/login.jsp

method="login">

userHome

userLoginForm

method="home">

/WEB-INF/jsp/home.jsp

method="registForm">

/WEB-INF/jsp/regist.jsp

userRegistForm

/WEB-INF/jsp/errorHandle.jsp

/WEB-INF/jsp/mgr/admin-login.jsp

标签

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 luckyNumbers;

private List parents;

private List games;

国际化资源包myRes_zh_CN.properties 、myRes_en_US.properties

中文 | English

user.home.header=Hello:{0},Welcome to the site!

前端:

后端:ctx.put("loginErrorMsg", super.getText("user.login.faile"));

服务器异常查看

服务器异常

function showDetails() {

document.getElementById('details').style.display = 'block';

}

Sorry,服务器出错了,请稍后再试!

技术人员,查看详情

${ exception }

传入id转成类

喜欢的游戏:

${g.name }?

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=\u7528\u6237\u5E74\u9F84\u503C\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u662F\u4E2A\u6574\u6570 //年龄格式错误,必须是个整数

invalid.fieldvalue.u.birthdate=\u51FA\u751F\u65E5\u671F\u683C\u5F0F\u9519\u8BEF\uFF0C\u5E94\u8BE5\u4F8B\u5982\uFF1A1995-01-01 //出生日期格式错误,应该例如:1995-01-01

如果没有就在xwork.default.invalid.fieldvalue=\u6570\u636E\u7684\u683C\u5F0F\u9519\u8BEF\u201C{0}\u201D //数据的格式错误

前端显示

格式验证失败返回input

上传文件

image/jpeg, image/png, image/gif

1024000

userRegistForm

userAction_zh_CH.properties

struts.messages.error.uploading=Error uploading: {0}

struts.messages.error.file.too.large=\u6587\u4EF6{1}\u592A\u5927\u4E86\uFF0C\u5FC5\u987B\u5C0F\u4E8E {4} \u5B57\u8282\uFF01

struts.messages.error.content.type.not.allowed=\u5934\u50CF\u6587\u4EF6\u5FC5\u987B\u662F\u56FE\u7247

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,newFile(realPath));

}catch(IOException e) {

e.printStackTrace();

}

}else{

System.out.println("用户未上传头像");

强加验证

UserAction-userRegist-validation.xml

年龄必填

18

40

年龄必须在18到40岁之间

true

出生日期不能为空

前端自定义验证类型

src validators.xml

class

public class ZipValidator extendsFieldValidatorSupport {

@Overridepublic void validate(Object action) throwsValidationException {

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

邮政编码格式错误!

拦截器

yyyy年MM月dd日 HH点mm分ss秒

文件下载

is

${contentType}

attchement;filename=${fileName}

4096

privateInteger rid;privateInputStream is;privateString fileName;private String contentType; //get set

public String download() throwsUnsupportedEncodingException {

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", "下载失败:必须是登录用户才能下载,现在马上去登录。");

returnSUCCESS;

}privateInputStream fengJingInputName;

@Overridepublic String execute() throwsException {this.fengJingInputName = ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/resources/Ajax:2.avi");returnSUCCESS;

}

fengJingInputName

attchement;filename=Ajax:2.avi

权限验证

loginForm,loginCheck

AuthorityInterceptor.java

@SuppressWarnings("serial")public class AuthorityInterceptor extendsMethodFilterInterceptor {

@Overrideprotected String doIntercept(ActionInvocation invocation) throwsException {

ActionContext ctx=invocation.getInvocationContext();if(ctx.getSession().get("currAdmin") == null) {

ctx.put("tip", "请先登录,再进行其他操作!");return "login";

}else{returninvocation.invoke();

}

}

}

bais

text/html;charset=UTF-8

action name="getAllAdmins" class="sample.s2.web.action.mgr.DemoAjaxAction" method="getAllAdmins">

admins

application/json;charset=UTF-8

privateString type;privateInputStream bais;private Listadmins;public String getRandom() throwsException {int offset = type.equals("small") ? 0 : 5;

String r= (int)(Math.random() * 5) + offset + ""; //"9"

bais= new ByteArrayInputStream(r.getBytes("utf-8"));returnSUCCESS;

}publicString getAllAdmins() {

admins=adminService.getAdmins();returnSUCCESS;

}

$(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

西游记

水浒传

三国演义

红楼梦

1.81

82

src test.properties

# a common properties file

name=\u5F20\u4E09

age=23sex=male

height=1.79

public voidtestProperties() {/*Properties props = System.getProperties();

for(Object key : props.keySet()) {

System.out.println(key + " = " + props.get(key));

}*/Properties props= newProperties();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 已经创建完成 -----------------------------\n");

context.getBean("zwj");

context.getBean("zwj");

ApplicationContext context= new ClassPathXmlApplicationContext("/applicationContext.xml");

System.out.println("-- ApplicationContext 已经创建完成 -----------------------------\n");

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下面

springmvc

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:/springmvc-servlet.xml

1

springmvc

/

src下面 springmvc-servlet.xml

controller页面

@Controller

@RequestMapping("/mvc")public class mvcController { //类上面

@Controller 负责注册一个bean 到spring 上下文中

@RequestMapping 注解为控制器指定可以处理哪些 URL 请求

Date类型转//the parameter was converted in initBinder

@RequestMapping("/date")publicString date(Date date){

System.out.println(date);return "hello";

}//At the time of initialization,convert the type "String" to type "date"

@InitBinderpublic voidinitBinder(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(Mapmap){

Person p=newPerson();

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 voidgetPerson(String name,PrintWriter pw){

pw.write("hello,"+name);

}

@RequestMapping("/name")publicString sayHello(){return "name";

}

前台用下面的Jquery代码调用

$(function(){

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

$.post("mvc/getPerson",{name:$("#name").val()},function(data){

alert(data);

});

});

});//redirect

@RequestMapping("/redirect")publicString redirect(){return "redirect:hello";

}



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有