接口:
- Java code
public interface UserService {
public void addUser(String username, String password);
public void deleteUser(int id);
public void updateUser(int id, String username);
public List queryUser(String username);
}
接口的实现:
- Java code
public class UserServiceImpl implements UserService {
private DataSource dataSource;
public void addUser(String username, String password) {
//正确的sql
String sql = "insert into aaa (t1,t2,t3) values (seq_food.nextval,'"+username+"','"+password+"')";
System.out.println(sql);
JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
jdbcTemplate.update(sql);
}
public void deleteUser(int id) {
}
public void updateUser(int id, String username) {
//错误的sql,测试回滚
String sql = "update aa set t2='"+username+"' where t1='"+id+"'";
System.out.println(sql);
JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
jdbcTemplate.update(sql);
}
public List queryUser(String username) {
return null;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
测试servlet:
- Java code
public class UserServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); try { UserService userService = (UserService) ctx.getBean("userService"); userService.addUser("1", "2"); userService.updateUser(10032190, "zf"); } catch (DataAccessException e) { e.printStackTrace(); } } }