controller类实现,只需把注解写上,spring就会自动帮你找到相应的bean,相应的注解标记意义,不明白的,可以自己查下@Service,@Controller,@Entity等等的内容。
package com.mvc.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.mvc.entity.Student;
import com.mvc.service.StudentService;
@Controller
@RequestMapping( " /student.do " )
public class StudentController {
protected final transient Log log=LogFactory
.getLog(StudentController.class);
@Autowired
private StudentService studentService;
public StudentController(){
}
@RequestMapping
public String load(ModelMap modelMap){
Listlist=studentService.getStudentList();
modelMap.put("list", list);
return "student";
}
@RequestMapping(params="method=add")
public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{
return "student_add";
}
@RequestMapping(params="method=save")
public String save(HttpServletRequest request, ModelMap modelMap){
String user=request.getParameter("user");
String psw=request.getParameter("psw");
Student st=new Student();
st.setUser(user);
st.setPsw(psw);
try{
studentService.save(st);
modelMap.put("addstate", "添加成功");
}
catch(Exception e){
log.error(e.getMessage());
modelMap.put("addstate", "添加失败");
}
return "student_add";
}
@RequestMapping(params="method=del")
public void del(@RequestParam("id") String id, HttpServletResponse response){
try{
Student st=new Student();
st.setId(Integer.valueOf(id));
studentService.delete(st);
response.getWriter()。print("{\"del\":\"true\"}");
}
catch(Exception e){
log.error(e.getMessage());
e.printStackTrace();
}
}
}
service类实现
package com.mvc.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mvc.dao.EntityDao;
import com.mvc.entity.Student;
@Service
public class StudentService {
@Autowired
private EntityDao entityDao;
@Transactional
public ListgetStudentList(){
StringBuffer sff=new StringBuffer();
sff.append("select a from ")。append(Student.class.getSimpleName())。append(" a ");
Listlist=entityDao.createQuery(sff.toString());
return list;
}
public void save(Student st){
entityDao.save(st);
}
public void delete(Object obj){
entityDao.delete(obj);
}
}
OK,例子写完。有其它业务内容,只需直接新建view,并实现相应comtroller和service就行了,配置和dao层的内容基本不变,也就是每次只需写jsp(view),controller和service调用dao就行了。
怎样,看了这个,spring mvc是不是比ssh实现更方便灵活。