排行榜

  • 用户榜
  • 标签榜
  • 冲榜分奖金

频道

最新最热悬赏待采纳 筛选
  • 3

    回答

  • 28

    浏览

我跟着《Java Web从入门到精通》学习struts,在idea环境下配置struts.xml时提示cannot resolve symbol 'user_add.jsp',不知道如何解决,请教一下大佬们。 后来新创了个test项目重做了一遍,在打同一行时依然出现了该问题,但此时还未创建user_add.jsp文件,quick fix提示了创建这一文件,于是用idea自动帮忙创建了,上述问题就解决了。然后回到原项目里发现idea没有提示quick fix,但文件路径和test项目下一模一样,按理说不应该出现问题的。 结果当我再次打开test项目,发现原本由quick fix创建的jsp文件又无法解析了,报了同样的错误。太难了!  

  • 5

    回答

  • 42

    浏览

做了一个ssh框架的在线考试项目,现已实现了遍历数据库中所有的问题 数据库中建立了optionA,optionB等字段来显示问题,也有对应的answer字段(内容只能为ABCD其中一个字母) 用c:foreach方法遍历了问题的四个字段radio不同的value为“A”,“B”,“C”,“D”以用来比对answer字段 想问如何在jsp的前端进行判断或者把所有选项选中的value值传回后端action进行判断。 想了好几天了自己编程,有很多问题,请个大佬来指点迷津吧!

  • 0

    回答

  • 7

    浏览

在实验开发中,我想通过action 的result路径来传递参数: 像这样: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210413084513616.png) 可以看到在name=Nologin 的路径中我想带入一个error的参数到登录界面,这样可以根据error值作出相应的提醒。 如上,这样写,通过普通,转发的方式向jsp传递参数,jsp通过EL表达式是可以获取到值的。 但在此之前,我多次试用,type=“redirect”  或者 type=“redirectAction” 类型重定向并带参数error的方式传值,但在jsp页面却不能获取到值。 关于其原因,为什么重定向路径带的参数不能获取到值,我还没有找到答案,在此做个记录。

  • 5

    回答

  • 31

    浏览

代码如下 import java.io.*; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Hello { private static final String PATH_OF_FILE = "D:/authors/"; // 待索引文件的目录 private static final String PATH_OF_INDEX = "D:/a-index/"; // 存放索引文件的目录2 /** * 测试时,要在D:/img/文件夹中准备几个包含内容的文件(比如txt格式的) * 然后先执行createIndex()方法,再执行searchFile()方法,最后观看控制台输出即可 */ public static void main(String[] args) { Hello h = new Hello(); String aa,bb; for (int j=44711;j<52601;j++){ String filePath1 = "D:/text/"+j+"-1.txt"; String filePath2 = "D:/text/"+j+"-2.txt"; // System.out.println(filePath1); // System.out.println(filePath2); aa=read(filePath1); bb=read(filePath2); // System.out.println(aa); // System.out.println(bb); h.testSearch(aa,j); System.out.println("#################"); h.testSearch(bb,j); System.out.println("#################"); // "res/"; // h.createIndex(); //先跑这一条,然后把String aa,bb一下到这一条的先注释掉,然后再把这一条注释掉,恢复上面的开始跑。 } private void createIndex();{ Directory directory = null;//指定索引被保存的位置 IndexWriter writer = null;//通过IndexWriter写索引 Document doc = null;//我们索引的有可能是一段文本or数据库中的一张表 try { // 这里是在硬盘上"D:/index/"文件夹中创建索引 directory = FSDirectory.open(new File(PATH_OF_INDEX)); // 这里通过IndexWriterConfig()构造方法的Version.LUCENE_41参数值指明索引所匹配的版本号,并使用了Lucene的标准分词器 writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_41, new StandardAnalyzer(Version.LUCENE_41))); for (File file : new File(PATH_OF_FILE).listFiles()) { doc = new Document(); doc.add(new Field("content", new FileReader(file))); doc.add(new Field("fileName", file.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("filePath", file.getAbsolutePath(), Field.Store.YES, Field.Index.NOT_ANALYZED)); writer.addDocument(doc); } } catch (Exception e) { System.out.println("创建索引的过程中遇到异常,堆栈轨迹如下"); e.printStackTrace(); } finally { if (null != writer) { try { writer.close(); // IndexWriter在用完之后一定要关闭 } catch (IOException ce) { System.out.println("关闭IndexWriter时遇到异常,堆栈轨迹如下"); ce.printStackTrace(); } } } } public static String read(String filePath) { // 读取txt内容为字符串 StringBuffer txtContent = new StringBuffer(); // 每次读取的byte数 byte[] b = new byte[8 * 1024]; InputStream in = null; try { // 文件输入流 in = new FileInputStream(filePath); while (in.read(b) != -1) { // 字符串拼接 txtContent.append(new String(b)); } // 关闭流 in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return txtContent.toString(); } private String getContentFromFile(File myFile) { StringBuffer sb = new StringBuffer(); if (!myFile.exists()) { return ""; } try { BufferedReader in = new BufferedReader(new FileReader(myFile)); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); } catch (IOException e) { e.getStackTrace(); } return sb.toString(); } /** * 搜索文件 * * @see 1、创建Directory * @see 2、创建IndexReader * @see 3、根据IndexReader创建IndexSearcher * @see 4、创建搜索的Query * @see 5、根据searcher搜索并返回TopDocs * @see 6、根据TopDocs获取ScoreDoc对象 * @see 7、根据searcher和ScoreDoc对象获取具体的Document对象 * @see 8、根据Document对象获取需要的值 * @see 9、关闭IndexReader */ @SuppressWarnings("deprecation") // private void searchFile() { // IndexReader reader = null; // try { // reader = IndexReader.open(FSDirectory.open(new File(PATH_OF_INDEX))); // IndexSearcher searcher = new IndexSearcher(reader); // // 创建基于Parser搜索的Query,创建时需指定其"搜索的版本,默认搜索的域,分词器"....这里的域指的是创建索引时Field的名字 // QueryParser parser = new QueryParser(Version.LUCENE_41, "content", new StandardAnalyzer(Version.LUCENE_41)); // Query query = parser.parse(" let her go no she had to confront it was a gift of something that would not irk her for the rest of eternity and yet a curse of more pain the choice of selfishness or selflessness when both loosed their boundaries and came together and that hurt more than anything that hurt the scorch of disappointment denial anxiety fear there was too much of it and yet she did not want him dead it had taken her time so much time to realize that but she did not wish death upon anyone having seen too much of it as the clock ticked away she had never wanted anyone to truly die gilbert beilschmidt though she hated him above all was no exception but in times such as now when war tore the world apart when history decided to twist itself about when the nations crumbled how could death not be a blessing at this point she could almost want them all to be dead roderich gilbert veneziano ludwig and yet she would watch with relief on the day that each of them would pick themselves up and charge into the distance with life she hated war she blinked rapidly staring always watching though she ached she let the next batter of coughing come to pass shock it overcame her then charging upward body screaming in protest she could only slap him with strength that came by habit before wrapping both arms around him wondering how and why in hell get off me woman he protested attempting to flail she saw now that the tin had been stripped away or at least most of it as she felt him flesh and cloth and hair from the unhealthy pallor of his skin from the dried hard uniform to the pinked and browned hair silver still shining boldly beneath the blood he was unusually warm hot even when she felt him clearly the cold had been warded off though his hands still felt like ice remembering the documents found in ludwig s office she realized that it was fever but his head feeling about the neck she knew it was there desperately feeling just to know how cruel death was she felt it finding no seam with a thin cry of joy and pain she kissed it squeezing him till he was strangled you re alive she breathed even as garbled speech flew from his lips she was going into spasms this was too unreal and yet it was he was so so solid his eyes were ruby no petty pink glaze upon the kingdom of prussia s gaze no death frosting them over clinging to him something told her that she would never let go a stupid little piece of wishful thought no doubt never let go how ridiculous and yet she did not release him as he calmed between her limbs resigning with guilty pleasure rigid with denial she could not even loosen about him there was nothing but the jail scene playing and replaying itself in her mind letting their hands drop parting and then the sickening sound of the guillotine s strike water red pink silver white black the swastika rose over all as if to mock where in isten s name have you been she muttered against his shoulder before lifting her head away hastily still though she did not let go she wanted to savor it as the vampire feasts on blood the scent of metal clung to him get off was the obstinate reply she lifted her hand and slapped him again not knowing what else to do ow where ve you been she said again you were supposed to be dead well i m so freaking not i saw your head she said voice reaching a higher octave it was a fake impossible she declared eyes widening before she finished it came to her suddenly the way it had fallen the sudden hush of death the blindfold of stars the blood she had seen it touched it waded in the water it buried itself in she had suffered with him at death you were dead she whispered it gave way to coughing and he only watched as she did held onto her and she held onto him i heard the thud if you were dead he grunted when she looked up his eyes were a bitter red the head was fake they held me down scowling he looked away admittance was ignominy they held me down up there there were lots of them hungary scheiße there was a lot of back up that we didn t notice i couldn t beat off all of them and my gun ran out his voice faded still his scowl deepened and he finished to his own satisfaction their leader was fun to kill though he laughed cruelly forcefully he found no love for death though he had seen enough of it to mind less elizaveta decided against shaking her head it could only be true she had known him for years since they were incomplete nations just children running about with swords of both wood and steel just as he had sifted out her identity from that of elisabeth wertheim s it was with ease that she found that this man in front of her was real as nations in human form they were allowed the same detached senses as those immortal stupid she scolded herself knowing not to trust so easily but it was what it was she noticed the shards of tin still upon his flesh then of course he could not have been thrown out so easily time was needed so much time some things did not change but could they trapped him shackled his person still not releasing he was too real too solid to let go she let the "); // 指定==>搜索域为content(即上一行代码指定的"content")中包含"java"的文档 // TopDocs tds = searcher.search(query, 10); // 第二个参数指定搜索后显示的条数,若查到5条则显示为5条,查到15条则只显示10条 // ScoreDoc[] sds = tds.scoreDocs; // TopDocs中存放的并不是我们的文档,而是文档的ScoreDoc对象 // for (ScoreDoc sd : sds) { // ScoreDoc对象相当于每个文档的ID号,我们就可以通过ScoreDoc来遍历文档 // Document doc = searcher.doc(sd.doc); // sd.doc得到的是文档的序号 // System.out.println(doc.get("fileName") + "[" + doc.get("filePath") + "]"); // 输出该文档所存储的信息 // } // } // catch (Exception e) { // System.out.println("搜索文件的过程中遇到异常,堆栈轨迹如下"); // e.printStackTrace(); // } // finally { // if (null != reader) { // try { // reader.close(); // } // catch (IOException e) { // System.out.println("关闭IndexReader时遇到异常,堆栈轨迹如下"); // e.printStackTrace(); // } // } // } // } public void testSearch(String aa,int i) { IndexReader reader = null; try { // 索引目录对象 // Directory directory = FSDirectory.open(new File(PATH_OF_INDEX)); reader = IndexReader.open(FSDirectory.open(new File(PATH_OF_INDEX))); // 索引读取工具 // 索引搜索工具 IndexSearcher searcher = new IndexSearcher(reader); BooleanQuery.setMaxClauseCount(Integer.MAX_VALUE); // 创建查询解析器,两个参数:默认要查询的字段的名称,分词器 QueryParser parser = new QueryParser(Version.LUCENE_41, "content", new StandardAnalyzer(Version.LUCENE_41)); //QueryParser parser = new QueryParser("title", new IKAnalyzer()); // 创建查询对象 String a=aa; Query query = parser.parse(a); // 搜索数据,两个参数:查询条件对象要查询的最大结果条数 // 返回的结果是 按照匹配度排名得分前N名的文档信息(包含查询到的总条数信息、所有符合条件的文档的编号信息)。 TopDocs topDocs = searcher.search(query, 10); // 获取总条数 System.out.println("本次搜索共找到" + topDocs.totalHits + "条数据"); // 获取得分文档对象(ScoreDoc)数组.SocreDoc中包含:文档的编号、文档的得分 ScoreDoc[] scoreDocs = topDocs.scoreDocs; BufferedWriter out = new BufferedWriter(new FileWriter("D:\\score\\score"+"-"+i+".txt",true)); for (ScoreDoc scoreDoc : scoreDocs) { // 取出文档编号 int docID = scoreDoc.doc; //Document doc = searcher.doc(sd.doc); // sd.doc得到的是文档的序号 // 根据编号去找文档 Document doc = reader.document(docID); System.out.println(doc.get("fileName")+"得分: " + scoreDoc.score); // 输出该文档所存储的信息 try { out.write(doc.get("fileName")+"得分: " + scoreDoc.score+"\n"); } catch (IOException e) { } //System.out.println("id: " + doc.get("id")); // System.out.println("title: " + doc.get("title")); // 取出文档得分 // System.out.println(); } out.write("\n"); out.close(); System.out.println("文件创建成功!"); } catch (Exception e) { System.out.println("搜索文件的过程中遇到异常,堆栈轨迹如下"); e.printStackTrace(); } finally { if (null != reader) { try { reader.close(); } catch (IOException e) { System.out.println("关闭IndexReader时遇到异常,堆栈轨迹如下"); e.printStackTrace(); } } } } }  

  • 1

    回答

  • 21

    浏览

    package com.mingrisoft.dao; import java.sql.Connection;                        //表示连接到某个数据库的连接 import java.sql.DriverManager;                    //用来获取数据库连接 import java.sql.PreparedStatement;                //用来执行SQL语句 import java.sql.ResultSet;                        //封装查询结果集 import java.sql.SQLException;                    //异常处理类 public class DB {     private Connection con;                            //声明一个Connection对象     private PreparedStatement pstm;                    //声明一个PreparedStatement对象     private String user="sa";                        //登录数据库的默认用户名     private String password="1";                        //登录数据库的密码     private String className="com.microsoft.sqlserver.jdbc.SQLServerDriver";        //数据库驱动类路径     private String url="jdbc:sqlserver://localhost:1433;DatabaseName=db_CityInfo";    //数据库URL          public DB(){                                    //DB类的构造方法         try{                                        //必须使用try-catch语句捕获加载数据库驱动时可能发生的异常             Class.forName(className);                //加载数据库驱动         }catch(ClassNotFoundException e){            //捕获ClassNotFoundException异常             System.out.println("加载数据库驱动失败!");             e.printStackTrace();                    //输出异常信息         }     }     /**创建数据库连接*/     public Connection getCon(){         try {             con=DriverManager.getConnection(url,user,password);    //建立连接,连接到由属性url指定的数据库URL,                                                             //并指定登录数据库的用户名和密码         } catch (SQLException e) {             System.out.println("创建数据库连接失败!");             con=null;             e.printStackTrace();         }         return con;     }          public void doPstm(String sql,Object[] params){         if(sql!=null&&!sql.equals("")){             if(params==null)params=new Object[0];             con = getCon();                                            //调用getCon()方法获取数据库连接             if(con!=null){                 try{                     pstm=con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,                                                 ResultSet.CONCUR_READ_ONLY);                     for(int i=0;i<params.length;i++){                         pstm.setObject(i+1,params[i]);                     }                     pstm.execute();                            //执行SQL语句                 }catch(SQLException e){                     System.out.println("doPstm()方法出错!");                     e.printStackTrace();                        //输出错误信息                 }             }         }     }          public ResultSet getRs() throws SQLException{         return pstm.getResultSet();            //调用PreparedStatement类对象的getResultSet()方法返回ResultSet对象     }     public int getCount() throws SQLException{         return pstm.getUpdateCount();        //调用PreparedStatement类对象的getResultSet()方法返回影响的记录数     }     public void closed(){         try{             if(pstm!=null)                 pstm.close();                     }catch(SQLException e){             System.out.println("关闭pstm对象失败!");             e.printStackTrace();         }         try{             if(con!=null){                 con.close();             }         }catch(SQLException e){             System.out.println("关闭con对象失败!");             e.printStackTrace();         }     } }

回答 LT__9527
采纳率33.3%
10天前
  • 5

    回答

  • 37

    浏览

application.properties: ##数据源配置 spring.datasource.url=jdbc:mysql://localhost:3306/zytj?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=admin spring.datasource.driver-class-name=com.mysql.jdbc.Driver ##配置方言 spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect ##运行时输出jpa执行的sql语句 spring.jpa.show-sql=true ##spring-boot-starter-data-jpa自动映射创建表动作 配置: 有表更新,无表创建 spring.jpa.hibernate.ddl-auto=update entity: package com.jlb.zytj.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.format.annotation.DateTimeFormat; import lombok.Data; @Data @Entity @Table @EntityListeners(AuditingEntityListener.class) public class Member {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private int id;//主键     @NotNull     @Column(name = "cardno",nullable = false)     private String cardNo;//会员卡号     @NotNull     @Column(nullable = false)     private String name;//姓名     private String sex;//性别     @Column(name = "category",columnDefinition = "tinyint default 0")     private int category=0;//身份,0表示学生,1表示老师     @Column(unique = true,length = 18)     private String card;//身份证号,唯一,用来保证每个用户只能有一个会员卡     private String department;//系     private String profession;//专业     private String grade;//年级     @NotNull     @Column(nullable = false,length = 11)     private String phone;//电话     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")     @CreatedDate     private Date regdate;//入会时间     @Column(name="status",columnDefinition="tinyint default 0")     private int status=0;//状态,0表示没有使用任何资源,其他状态填写资源id     private String remark;//备注 } dao: package com.jlb.zytj.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.jlb.zytj.model.Member; public interface IMemberDao extends JpaRepository<Member, Integer>,JpaSpecificationExecutor<Member>{ } Iservice接口: package com.jlb.zytj.service; import java.util.Map; import com.jlb.zytj.dto.MemberDto; public interface IMemberService {          Map<String, Object> findByCondition(MemberDto dto);   }   servies: package com.jlb.zytj.service; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import com.jlb.zytj.dao.IMemberDao; import com.jlb.zytj.dto.MemberDto; import com.jlb.zytj.model.Member; @Service @Transactional public class MemberService implements IMemberService{     @Resource     private IMemberDao memberdao;     @Override     public Map<String, Object> findByCondition(MemberDto dto) {         Map<String,Object> map = new HashMap<String,Object>();         Pageable pageable = PageRequest.of(dto.getPage()-1, dto.getSize(), Sort.by(Direction.DESC, "regdate"));         Page<Member> page = memberdao.findAll(getWhereClause(dto), pageable);         map.put("code", 0);         map.put("count", memberdao.count(getWhereClause(dto)));         map.put("msg", "查询成功");         map.put("data",page.getContent());         return map;     }          private Specification<Member> getWhereClause(MemberDto dto){         return new Specification<Member>() {             @Override             public Predicate toPredicate(Root<Member> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {                 List<Predicate> list=new ArrayList<Predicate>();                 if(dto.getCategory()==0) {//学生                     if(dto.getDepartment()!=null && ""!=dto.getDepartment()) {//系                         list.add(criteriaBuilder.equal(root.<String>get("department"), dto.getDepartment()));                     }                     if(dto.getProfession()!=null && ""!=dto.getProfession()) {//专业                         list.add(criteriaBuilder.equal(root.<String>get("profession"), dto.getProfession()));                     }                     if(dto.getGrade()!=null && ""!=dto.getGrade()) {//年级                         list.add(criteriaBuilder.equal(root.<String>get("grade"), dto.getGrade()));                     }                 }                                  if(dto.getName()!=null && ""!=dto.getName()) {//姓名模糊查询                     list.add(criteriaBuilder.like(root.<String>get("name"), "%"+dto.getName()+"%"));                 }                                  if(dto.getCardNo()!=null && ""!=dto.getCardNo()) {//会员卡号                     list.add(criteriaBuilder.equal(root.get("card_no").as(String.class), dto.getCardNo()));                 }                 if(dto.getPhone()!=null && ""!=dto.getPhone()) {//手机号                     list.add(criteriaBuilder.equal(root.get("phone").as(String.class), dto.getPhone()));                 }                 if(dto.getStartTime()!=null) {//入会时间                     list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("regdate").as(Date.class), dto.getStartTime()));                 }                 if(dto.getEndTime()!=null) {//入会时间                     list.add(criteriaBuilder.lessThanOrEqualTo(root.get("regdate").as(Date.class), dto.getEndTime()));                 }                 if(dto.getStatus()>0) {                     list.add(criteriaBuilder.lt(root.<Integer>get("status"), dto.getStatus()));                 }                 Predicate[] pre = new Predicate[list.size()];                 return query.where(list.toArray(pre)).getRestriction();             }         };     } } controller: package com.jlb.zytj.controller; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.jlb.zytj.dao.IMemberDao; import com.jlb.zytj.dto.MemberDto; import com.jlb.zytj.service.IMemberService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @RestController @Api(tags = "会员查询") @RequestMapping("/member") public class MemberController {          @Resource     private IMemberService memberservice;     @Resource     private IMemberDao memberdao;          @ApiOperation(value = "会员查询",notes = "会员查询")     @PostMapping("/findByCondition")     public Map<String, Object> findByCondition(MemberDto dto){         return memberservice.findByCondition(dto);     } } 前台页面(引用的模板):     <title>简单用法 - 数据表格</title>   <div class="layui-card layadmin-header">     <div class="layui-breadcrumb" lay-filter="breadcrumb">       <a lay-href="">主页</a>       <a><cite>组件</cite></a>       <a><cite>数据表格</cite></a>       <a><cite>简单用法</cite></a>     </div>   </div>     <div class="layui-fluid">     <div class="layui-row layui-col-space15">       <div class="layui-col-md12">         <div class="layui-card">           <div class="layui-card-header">简单用法</div>           <div class="layui-card-body">             <table class="layui-hide" id="test-table-simple"></table>           </div>         </div>       </div>     </div>   </div>     <script>   layui.use(['admin', 'table'], function(){     var table = layui.table;       table.render({       elem: '#test-table-simple'       ,method:'post'       ,page:true       ,url: '../member/findByCondition'       ,cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增       ,cols: [[           {field:'id', width:80, title: 'ID', sort: true}           ,{field:'card', width:80, title: '身份证'}           ,{field:'cardno', width:80, title: '会员卡号', sort: true}           ,{field:'category', width:80, title: '职业'}           ,{field:'department', title: '部门', minWidth: 150}           ,{field:'grade', width:80, title: '年级', sort: true}           ,{field:'name', width:80, title: '会员名', sort: true}           ,{field:'phone', width:80, title: '手机'}           ,{field:'profession', width:135, title: '专业', sort: true}           ,{field:'regdate', width:80, title: '日期', sort: true}           ,{field:'remark', width:80, title: '备注'}           ,{field:'sex', width:135, title: '性别', sort: true}           ,{field:'status', width:135, title: '状态', sort: true}       ]]              });   });   </script> 报的错误: java.lang.IllegalArgumentException: Page size must not be less than one!     at org.springframework.data.domain.AbstractPageRequest.<init>(AbstractPageRequest.java:50) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]     at org.springframework.data.domain.PageRequest.<init>(PageRequest.java:71) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]     at org.springframework.data.domain.PageRequest.of(PageRequest.java:96) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]     at com.jlb.zytj.service.MemberService.findByCondition(MemberService.java:37) ~[classes/:na]  

  • 1

    回答

  • 25

    浏览

实体类: import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.format.annotation.DateTimeFormat; import lombok.Data; @Data @Entity @Table @EntityListeners(AuditingEntityListener.class) public class Users {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private int id; // 用户编号UUID     @NotNull     @Column(unique = true,name = "loginname",nullable = false)     private String loginName; // 登录名     @Column(unique = true, name = "password",length = 8)     private String password; // 密码     @Column(name = "islockout",columnDefinition = "tinyint default 0")     private int isLockOut; // 是否锁定(0表示未锁定,1表示锁定)     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")     @CreatedDate     @Column(name = "createtime")     private Date createTime; // 账号创立时间     @Column(name = "lastlogintime")     private Date lastLoginTime; // 最后一次登录时间     @Column(name = "locktime")     private Date lockTime; // 被锁定时间     @Column(name = "psdwrongtime",columnDefinition = "tinyint default 0")     private Integer psdWrongTime; // 密码错误次数     @Column(name = "protectemail")     private String protectEmail; // 密保邮箱     @Column(unique = true,length = 11,name="protectmtel")     private String protectMTel; // 密保手机号 } service接口类: package com.sxd.crm.service; import java.util.Map; import com.sxd.crm.dto.UsersDto; import com.sxd.crm.model.Users; public interface IUsersService {         //根据条件查询         Map<String, Object> findByCondition(UsersDto dto);                  //锁定用户         void lockUser(int id);                  //锁定用户         void lockUsers(int id);                  //添加用户         void addUser(Users users);                  //删除用户         void delUser(int id); } service实现类: package com.sxd.crm.service; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import com.sxd.crm.dao.IUsersDao; import com.sxd.crm.dto.UsersDto; import com.sxd.crm.model.Users; @Service @Transactional public class UsersService implements IUsersService{     @Resource     private IUsersDao usersdao;     @Override     public Map<String, Object> findByCondition(UsersDto dto) {         Map<String, Object> map=new HashMap<String, Object>();         Pageable pageable = PageRequest.of(dto.getPage()-1, dto.getSize(), Sort.by(Direction.DESC, "lastLoginTime"));         Page<Users> page = usersdao.findAll(getWhereClause(dto), pageable);         map.put("code", 0);         map.put("count", usersdao.count(getWhereClause(dto)));         map.put("msg", "查询成功");         map.put("data",page.getContent());         return map;     }          private Specification<Users> getWhereClause(UsersDto dto){         return new Specification<Users>() {             @Override             public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {                 List<Predicate> list=new ArrayList<Predicate>();                 if(dto.getPassword()!=null&&""!=dto.getPassword()) {                     list.add(criteriaBuilder.equal(root.get("Password").as(String.class), dto.getPassword()));                 }                 if(dto.getLoginName()!=null&&""!=dto.getLoginName()) {//登录名                     list.add(criteriaBuilder.like(root.get("LoginName").as(String.class), "%"+dto.getLoginName()+"%"));                 }                 if(dto.getStartCreateTime()!=null) {                     list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("CreateTime").as(Date.class), dto.getStartCreateTime()));                 }                 if(dto.getEndCreateTime()!=null) {                     list.add(criteriaBuilder.lessThanOrEqualTo(root.get("CreateTime").as(Date.class), dto.getEndCreateTime()));                 }                 if(dto.getIsLockOut()>0) {                     list.add(criteriaBuilder.equal(root.get("IsLockout").as(Integer.class), dto.getIsLockOut()));                 }                 Predicate[] pre = new Predicate[list.size()];                 return query.where(list.toArray(pre)).getRestriction();             }         };     }     @Override     public void lockUser(int id) {         usersdao.lockUser(id);              }     @Override     public void lockUsers(int id) {         usersdao.lockUsers(id);              }     @Override     public void addUser(Users users) {         usersdao.save(users);     }     @Override     public void delUser(int id) {         usersdao.deleteById(id);     } } controller: package com.sxd.crm.controller; import java.util.Map; import javax.annotation.Resource; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.sxd.crm.dao.IUsersDao; import com.sxd.crm.dto.UsersDto; import com.sxd.crm.model.Users; import com.sxd.crm.service.IUsersService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Api(tags = "用户管理模块") @RestController @RequestMapping("/users") public class UsersController {     @Resource     private IUsersService usersservice;     @Resource     private IUsersDao usersdao;          @ApiOperation(value = "用户查询",notes = "用户条件查询")     @PostMapping("/findByCondition")     public Map<String, Object> findByCondition(UsersDto dto){         return usersservice.findByCondition(dto);     }     @ApiOperation(value = "锁定用户",notes = "锁定用户")     @PostMapping("/lockUser")     public void lockUser(int id) {         usersservice.lockUser(id);     }          @ApiOperation(value = "解锁用户",notes = "解锁用户")     @PostMapping("/lockUsers")     public void lockUsers(int id) {         usersservice.lockUsers(id);     }     @ApiOperation(value = "注册账号",notes = "注册账号")     @PostMapping(value = "/addUser",produces = "application/json;charset=UTF-8")     public void addUser(Users users) {         usersservice.addUser(users);     }          @ApiOperation(value = "删除账号",notes = "删除账号")     @DeleteMapping("/delUser")     public void delUser(int id) {         usersservice.delUser(id);     } }

  • 0

    回答

  • 5

    浏览

model: import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.format.annotation.DateTimeFormat; import lombok.Data; @Data @Entity @Table(name = "usersign") @EntityListeners(AuditingEntityListener.class) @DynamicUpdate public class UserSign {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     @Column(name = "id")     private int id;//签到ID     @Column(name = "uid")     private int uid;//用户ID     @Column(name = "uname")     private String uname;//用户姓名     @Column(name = "status",columnDefinition = "tinyint default 0")     private int status;//签到状态(0 为签到 1为签退)     @Column(name = "iscancle",columnDefinition = "tinyint default 0")     private int isCancle;//是否取消签到(0 为不是 1为是)     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")     @CreatedDate     @Column(name = "signtime")     private Date signTime;//签到时间     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")     @CreatedDate     @Column(name = "signouttime")     private Date signOutTime;//取消签到时间      } dto: package com.sxd.crm.dto; import java.util.Date; import com.sxd.crm.model.UserSign; import lombok.Getter; import lombok.Setter; @Getter @Setter public class UserSignDto extends UserSign {     private int page = 1;     private int size = 10;          private Date startSignTime;     private Date endSignTime; } dao: package com.sxd.crm.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import com.sxd.crm.model.UserSign; public interface IUserSignDao extends JpaRepository<UserSign, Integer>,JpaSpecificationExecutor<UserSign>{          //根据用户ID查询信息     @Query(value = "select * from usersign where uid=:uid order by signtime desc limit 1",nativeQuery = true)     UserSign findByUid(int uid); } Iservice接口: package com.sxd.crm.service; import java.util.Map; import com.sxd.crm.dto.UserSignDto; import com.sxd.crm.model.UserSign; public interface IUserSignService {     //根据条件查询用户签到     Map<String, Object> findAll(UserSignDto dto);          //签到     String sign(UserSign u);          //签退     String signOut(UserSign u);          //根据UID查询信息     UserSign findByUid(int uid);           }   sercive: package com.sxd.crm.service; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import com.sxd.crm.dao.IUserSignDao; import com.sxd.crm.dto.UserSignDto; import com.sxd.crm.model.UserSign; @Service @Transactional public class UserSignService implements IUserSignService{          @Resource     private IUserSignDao usersigndao;     @Override     public Map<String, Object> findAll(UserSignDto dto) {         Map<String, Object> map=new HashMap<String, Object>();         Pageable pageable = PageRequest.of(dto.getPage()-1, dto.getSize(), Sort.by(Direction.DESC, "signTime"));         Page<UserSign> page = usersigndao.findAll(getWhereClause(dto), pageable);         map.put("code", 0);         map.put("count", usersigndao.count(getWhereClause(dto)));         map.put("data", page.getContent());         return map;     }          private Specification<UserSign> getWhereClause(UserSignDto dto){         return new Specification<UserSign>() {                          @Override             public Predicate toPredicate(Root<UserSign> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {                 List<Predicate> list=new ArrayList<Predicate>();                 if(dto.getUname()!=null&&""!=dto.getUname()) {                     list.add(criteriaBuilder.like(root.get("uname").as(String.class), "%"+dto.getUname()+"%"));                 }                 if(dto.getStartSignTime()!=null) {                     list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("signtime").as(Date.class), dto.getStartSignTime()));                 }                 if(dto.getEndSignTime()!=null) {                     list.add(criteriaBuilder.lessThanOrEqualTo(root.get("signtime").as(Date.class), dto.getEndSignTime()));                 }                 if(dto.getStatus()>0) {                     list.add(criteriaBuilder.lt(root.get("status"), dto.getStatus()));                 }                 Predicate[] pre=new Predicate[list.size()];                 return query.where(list.toArray(pre)).getRestriction();             }};     }     @Override     public String sign(UserSign u) {         UserSign us=usersigndao.findByUid(u.getUid());             Calendar cal=Calendar.getInstance();//实例化             cal.setTime(new Date());//进去时间为当前签到时间             u.setSignTime(new Date());             cal.add(Calendar.MINUTE, 10);//系统自动设置时间未签到添加10分钟             u.setSignOutTime(cal.getTime());             u.setUname(us.getUname());             u.setStatus(0);             usersigndao.save(u);         return "success";     }     @Override     public UserSign findByUid(int uid) {         return usersigndao.findByUid(uid);              }     @Override     public String signOut(UserSign u) {         UserSign us=usersigndao.findByUid(u.getUid());         u.setSignOutTime(new Date());         u.setSignTime(us.getSignTime());         u.setUname(us.getUname());         u.setStatus(1);         usersigndao.save(u);         return "success";     } } controller: package com.sxd.crm.controller; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.sxd.crm.dto.UserSignDto; import com.sxd.crm.model.UserSign; import com.sxd.crm.service.IUserSignService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @RestController @Api(tags = "用户签到管理模块") @RequestMapping("/usersign") public class UserSignController {     @Resource     private IUserSignService usersignservice;          @ApiOperation(value = "查询签到用户",notes = "查询所有签到用户")     @PostMapping("/findAll")     public Map<String, Object> findAll(UserSignDto dto){         return usersignservice.findAll(dto);     }          @ApiOperation(value = "查询用户信息",notes = "根据用户ID查询信息")     @PostMapping("/findByUid")     public UserSign findByUid(int uid){                  return usersignservice.findByUid(uid);     }          @ApiOperation(value = "模拟签到",notes = "用户签到")     @PostMapping("/sign")     public String sign(UserSign u) {         String str="success";         if(u.getStatus()>0) {             return str =  usersignservice.signOut(u);         }                   return str;     }          @ApiOperation(value = "模拟签退",notes = "用户签退")     @PostMapping("/signOut")     public String signOut(UserSign u) {             return usersignservice.signOut(u);     } } 问题:: 不报错,但就是实现不了??? 另外实体类自动创建时间也出不来效果,改为时间戳(timestamp)也没有用?? 望哪个大神赐教,拜托拜托!!!  

回答 xs__xb
采纳率0%
5天前