原来代码是用static建立静态数据。StudentController.java如下:
@Controller
@RequestMapping("/student")
public class StudentController {
private static List<Student> studentList=new ArrayList<Student>();
static{
studentList.add(new Student(1,"张三",11));
studentList.add(new Student(2,"李四",12));
studentList.add(new Student(3,"王五",13));
}
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView mav=new ModelAndView();
mav.addObject("studentList", studentList);
mav.setViewName("student/list");
return mav;
}
@RequestMapping("/preSave")
public ModelAndView preSave(@RequestParam(value="id",required=false) String id){
ModelAndView mav=new ModelAndView();
if(id!=null){
mav.addObject("student", studentList.get(Integer.parseInt(id)-1));
mav.setViewName("student/update");
}else{
mav.setViewName("student/add");
}
return mav;
}
}
现在我把
static{
studentList.add(new Student(1,"张三",11));
studentList.add(new Student(2,"李四",12));
studentList.add(new Student(3,"王五",13));
}
这一数据,移到mysql里面去了。
并建立DbUtil.java文件
package com.java1234.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtil {
private String dbUrl="jdbc:mysql://localhost:3306/db_cityInfo";
private String dbUserName="root";
private String dbPassword="123456";
private String jdbcName="com.mysql.jdbc.Driver";
public Connection getCon()throws Exception{
Class.forName(jdbcName);
Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
return con;
}
public void close(Connection con)throws Exception{
if(con!=null){
con.close();
}
}
}
并建立类
package com.java1234.model;
import java.util.Date;
public class Info {
private int id;
private String name;
public int getId() {
return id;
}
public void setTitle(String name) {
this.name= name;
}
}
请问在StudentController.java应该怎样修改public ModelAndView list()和public ModelAndView preSave方法?
------解决思路----------------------
Controller中的写法
Connection conn=DbUtil.getConn();
PreparedStatement pstmt=conn.preparedStatement(yoursql);
Result rs=pstmt.getResult();
while(rs.hasNext()){
//得到数据库的数据
}
------解决思路----------------------
定