httpservletrequest中的request添加一个实例的类

重写了doPost方法,其中Student是一个学生信息类(包含set,get方法),studentDAO是一个sql处理语句方法类。我想把得到的结果Student类直接传出去,再用get方法调用,而不是先取出Student中的数据再传递数据。
所以我直接把得到的Student作为属性值添加进了request。

 request.setCharacterEncoding("utf-8");
        int id=Integer.parseInt(request.getParameter("idd"));
        String name=request.getParameter("name");
        String sex=request.getParameter("sex");
        int age=Integer.parseInt(request.getParameter("age"));
        float weight=Float.parseFloat(request.getParameter("weight"));
        float hight=Float.parseFloat(request.getParameter("hight"));
        Student stu=new Student(id,name,sex,age,weight,hight);
        studentDAO s=new studentDAO();
        Student stu2=null;
        try{stu2=s.find(stu);
        }catch(Exception e){
            e.printStackTrace();
        }
        request.setAttribute("student",stu2);
        request.getRequestDispatcher("/test.jsp").forward(request, response);

然后在test.jsp中取出Student类:

  <%request.setCharacterEncoding("utf-8");
  Student stu=null;
  try{
   stu=(Student)request.getAttribute("student");
   if(stu!=null){out.print("1");}
  }catch(Exception e){
  e.printStackTrace();}
   %>
 **   <%=stu.toString() %>**
   <table border="0" width="238" height="252">
  <tr><td>学号</td><td><%=stu.getId() %></td></tr>
  <tr><td>姓名</td><td><%=stu.getName() %></td></tr>
  <tr><td>性别</td><td><%=stu.getSex() %></td></tr>
  <tr><td>年龄</td><td><%=stu.getAge() %></td></tr>
  <tr><td>体重</td><td><%=stu.getWeigth() %></td></tr>
  <tr><td>身高</td><td><%=stu.getHight() %></td></tr>
  </table>

结果运行的时候出现以下错误:

 org.apache.jasper.JasperException: An exception occurred processing JSP page /test.jsp at line 36(加粗的哪一行)

 Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:481)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
**  servlet.find.doPost(find.java:71)**
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

java.lang.NullPointerException
    org.apache.jsp.test_jsp._jspService(test_jsp.java:156)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    servlet.find.doPost(find.java:71)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.5.11 logs.

加粗的哪一行对应:

 request.getRequestDispatcher("/test.jsp").forward(request, response);

我看到有个空指针异常,是不是因为request不能保存实例类?

1个回答

用session传递就可以了

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
HttpServletRequest下的getMethod()方法调用的问题

public interface HttpServletRequest extends ServletRequest接口下的public String getMethod()方法,没有实现类实例化,就直接调用了getMethod()方法

struts2 Action 实现了ServletRequestAware接口,但是获取不到request对象实例

struts2 的 Action 实现了ServletRequestAware接口,但是获取不到HttpServletRequest对象实例

多次请求会创建多个request对象吗?

两种情况: 1)我多次向同一应用发送不同请求 2)多人向同一应用发送请求

Spring作用域request和prototype的区别

<span style="font-size: medium;">我们知道,spring有singleton和prototype作用域,而且从spring2.0开始,又增加了三种作用域,request、session、global session。session、global session的作用域是HTTP session和全局session。对于request和prototype,每一次请求都会产生一个新的bean实例,那么它们的具体有什么区别呢?而且,Spring不能对一个prototype bean的整个生命周期负责,这一点我不太能理解,这样它占用的资源就很高昂了,那么prototype的好处是什么?要结束它的生命周围,要怎么做?而且,感觉request和prototype,除了prototype的生命周期不会被回调以外,它们的作用是不是一样?有什么具体的区别呢?</span>

如何通过注解实例化对象?

我这个实现绕地球一周又回来了,还不如直接注入Map。有简单的解决思路吗 这是自定义的注解 @Target({ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface AutoChooseService { } 我想通过这个注解实例化service @RestController @RequestMapping("/user") public class UserController { private final String SERVICE_TYPE = "SERVICE_TYPE"; @AutoChooseService private UserService userService; @Autowired private HttpServletRequest request; @GetMapping("/create") public void createUser() { userService.createUser("1265"); } @GetMapping("/init/{type}") public String setSessionValue(@PathVariable String type, HttpServletRequest request) { request.getSession().setAttribute(SERVICE_TYPE,type); return "ok"; } public void choose() { // HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String type = (String) request.getSession().getAttribute(SERVICE_TYPE); if (type == null) { throw new RuntimeException("Errer Code 123"); } if(type.equalsIgnoreCase("db")){ userService = new UserServiceByDBImpl(); } else if (type.equalsIgnoreCase("file")) { userService = new UserServiceByFileImpl(); } else { throw new RuntimeException("Errer Code 123"); } } } 那么切面这块该怎么写呢 @Before("@annotation(com.hand.demo1.annotation.AutoChooseService)") public UserService setService(JoinPoint point) { return new UserServiceByDBImpl(); } @Pointcut(value = "execution(* com.hand.demo1.controller.UserController.*User(..))") public void cut1() { } @Before("cut1()") public void print(JoinPoint point) throws Exception { Class cls = point.getTarget().getClass(); Field[] fields = cls.getDeclaredFields(); for(Field field : fields) { String fieldName = field.getName(); if(fieldName.matches("^\\w+Service$")) { Annotation[] annotations = field.getDeclaredAnnotations(); for(Annotation annotation : annotations) { if( annotation instanceof AutoChooseService ){ Method m = cls.getDeclaredMethod("choose"); m.invoke(point.getTarget()); } } } } } }

request.getParameterMap()获取map集合泛型的问题,求解

Map<String, Object> map = request.getParameterMap();获取map集合泛型的问题 错误提示信息 Type mismatch: cannot convert from Map<String,String[]> to Map<String,Object>

fastjson解析http的get 参数,转换成java对象

我的http请求头如下 ```http http://localhost:8080/trace/Weather?temperatureMax=22&temperatureMin=1&humedityMax=52&humedityMin=2 ``` 当我请求后,json会得到一个这个 ```java weather = {"temperatureMax":["11"],"temperatureMin":["2"],"humidityMax":["55"],"humidityMin":["2"]} ``` 如果我使用parstObject()转换 weather java对象会报出一个异常"["无法转换 大概的意思是我想把 最大温度11 转到weather 对象中但是[11] 他当作一个整体. 如果我一个一个取出来使用Weather构造函数创造一个实例. 那么就成了一个数组 ```java jsonObject.getInteger("temperatureMax");//出现 [ 问题 jsonObject.get("tempertureMax"); //得到的是一个String数组但是只有一个数据. ``` 我最后处理办法 ```java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @SuppressWarnings("unchecked") JSONObject jsonWeather = new JSONObject(request.getParameterMap()); // GardenWeather weather = new GardenWeather(jsonWeather.getInteger("temperatureMax"), jsonWeather.getInteger("temperatureMin") // , jsonWeather.getInteger("humidityMax"), jsonWeather.getInteger("humidityMin")); // System.out.println(weather.toString()); log.info("weather = " + jsonWeather.toJSONString()); response.getWriter().write("temperatureMax = " + jsonWeather.toJSONString() ); response.getWriter().println(); String[] max = (String[]) jsonWeather.get("temperatureMax"); response.getWriter().write(new Integer(max[0]).toString()); weatherService.insertWeather(); } ``` 请问有没有更好的办法可以把http中的get请求转换成jave对象

关于controller里函数的参数问题

我要保存一个视频对象的时候使用DAO层里面的save(T o)方法 public void save(T o){ getSession().save(o); } controller里 public String fileUpload2(Long id,ModelMap map,HttpServletRequest request){ videoService.save(video); } 那么fileUpload2这个方法里要写Video video 这个参数吗?那这个参数又是怎么从jsp页面获得的呢? 挺急的。有木有大神指点一下?

#做一个简单的学生信息管理系统,实现增删改查的功能

还是新手小白,项目代码报错不会改,请求大佬的帮助 做一个简单的学生信息管理系统,实现增删改查的功能 # StudentDao package com.hdxy.Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.hdxy.Student.Student; public class StudentDao { //初始化Connection,Statement,ResultSet Connection conn = null; Statement st = null; ResultSet rs = null; //查询 public List<Student> testQuery(){ //查询表中所有学生,用集合来接收 List<Student> list = new ArrayList<Student>(); String sql ="select * from student order by id asc"; Connection conn = JDBCUtil.getInstance().getConnection();//获取连接 try { st = conn.createStatement();//预处理,创建集合接收数据 rs = st.executeQuery(sql);//结果集,创建集合接收数据 //循环遍历 while(rs.next()){ Student student = new Student();//实例化Student对象,要求要有Student对象 student.setId(rs.getInt("id"));//对象.方法或对象.属性。setI()想让id在前台显示打包赋值给student对象,getInt()获取学生信息 student.setName(rs.getString("name")); student.setSno(rs.getString("sno")); student.setSex(rs.getString("sex")); student.setAge(rs.getString("age")); list.add(student);//将student对象的数据传到list里 } }catch (Exception e){ e.printStackTrace(); } JDBCUtil.getInstance().closeConnection(rs,st,conn);//关闭,没有学生了就停止循环遍历 return list;//返回值类型return,返回list }//testQuery结束后拿到了所有学生的属性值 //添加数据 public void saveStudent(Student student){ //?:表示占位符.所谓占位符就是不知道要传递什么值,但是必须要有值 String sql = "insert into student(sno,name,sex,age) values(?,?,?,?)"; conn = JDBCUtil.getInstance().getConnection(); try { PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, student.getSno()); pst.setString(2, student.getName()); pst.setString(3, student.getSex()); pst.setString(4, student.getAge()); pst.execute(); } catch (SQLException e) { e.printStackTrace(); } JDBCUtil.getInstance().closeConnection(rs,st,conn); } public Student getStudent(int id){ Student stu = new Student(); String sql = "select id,sno,name,sex,age from student where id=?"; Connection conn = JDBCUtil.getInstance().getConnection();//获取连接 try { PreparedStatement st = conn.prepareStatement(sql); st.setInt(1, id); rs = st.executeQuery(); while(rs.next()){ stu.setId(rs.getInt("id")); stu.setSno(rs.getString("sno")); stu.setName(rs.getString("name")); stu.setSex(rs.getString("sex")); stu.setAge(rs.getString("age")); } } catch (SQLException e) { e.printStackTrace(); } JDBCUtil.getInstance().closeConnection(rs,st,conn); return stu; } //更改数据 public void updateStudent(Student student){ String sql = "update student set sno=?,name=?,sex=?,age=? where id=?"; Connection conn = JDBCUtil.getInstance().getConnection();//获取连接 try { PreparedStatement st = conn.prepareStatement(sql); st.setString(1, student.getSno()); st.setString(2, student.getName()); st.setString(3, student.getSex()); st.setString(4, student.getAge()); st.setInt(5, student.getId()); st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } JDBCUtil.getInstance().closeConnection(rs,st,conn); } //删除数据 public void deleteStudent(int id){ String sql = "delete from student where id=?"; Connection conn = JDBCUtil.getInstance().getConnection();//获取连接 try { PreparedStatement st = conn.prepareStatement(sql); st.setInt(1, id); st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } JDBCUtil.getInstance().closeConnection(rs,st,conn); } } # JDBC的工具类 package com.hdxy.Dao; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mysql.jdbc.Connection; //JDBC的工具类 public class JDBCUtil { //一.初始化数据库相关信息对象 static String driverClass="com.mysql.jdbc.Driver"; static String url="jdbc:mysql://localhost:3306/student?characterEncoding=utf-8";; static String name="root"; static String password="root"; static Connection conn = null; private static JDBCUtil instance = null; private JDBCUtil(){ } public static JDBCUtil getInstance(){ if(instance == null){ synchronized (JDBCUtil.class) { if(instance == null){ instance = new JDBCUtil(); } } } return instance; } //二.读取jdbc.properties文件并把相关信息赋予对象 static{ try{ String driver = null; Class.forName(driver); }catch(ClassNotFoundException e){ e.printStackTrace(); } } //三.获取连接对象 public Connection getConnection(){ try{ conn= (Connection) DriverManager.getConnection(url,name,password); }catch (Exception e) { e.printStackTrace(); } return conn; } public void closeConnection(ResultSet rs, Statement st, java.sql.Connection conn) { try { if(rs != null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); } finally{ try{ if(st != null){ st.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(conn != null){ conn.close(); } }catch(Exception e){ e.printStackTrace(); } } } } } # 服务类 package com.hdxy.Service; import java.util.List; import com.hdxy.Dao.StudentDao; import com.hdxy.Student.Student; //服务类 public class StudentService { public List<Student> testQuery(){ StudentDao studentDao = new StudentDao();//获取StudentDao实现类 List<Student> list = studentDao.testQuery(); return list;//返回值类型return,返回list } public void saveStudent(Student student){ StudentDao studentDao = new StudentDao(); studentDao.saveStudent(student); } public Student getStudent(int id){ StudentDao studentDao = new StudentDao(); return studentDao.getStudent(id); } public void deleteStudent(int id){ StudentDao studentDao = new StudentDao(); studentDao.deleteStudent(id); } public void updateStudent(Student student){ StudentDao studentDao = new StudentDao(); studentDao.updateStudent(student); } } # 实体类 package com.hdxy.Student; public class Student { private int id; private String sno; private String name; private String sex; private String age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSno() { return sno; } public void setSno(String sno) { this.sno = sno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Student(int id, String sno, String name, String sex, String age) { super(); this.id = id; this.sno = sno; this.name = name; this.sex = sex; this.age = age; } public Student() { } @Override public String toString() { return "Student [id=" + id + ", sno=" + sno + ", name=" + name + ", sex=" + sex + ", age=" + age + "]"; } } # Servlet package com.hdxy.Servlet; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hdxy.Student.Student; import com.hdxy.Service.StudentService; public class StudentServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); String method = request.getParameter("method"); if("testQuery".equals(method)){ testQuery(request,response); System.out.println("888"); }else if("toAdd".equals(method)){ toAdd(request,response); }else if("toEdit".equals(method)){ toEdit(request,response); }else if("saveStudent".equals(method)){ saveStudent(request,response); }else if("updateStudent".equals(method)){ updateStudent(request,response); }else if("deleteStudent".equals(method)){ deleteStudent(request,response); } System.out.println("777"); } private void testQuery(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ StudentService studentService = new StudentService(); List<Student> list = studentService.testQuery(); request.setAttribute("testQuery", list); RequestDispatcher dispatcher = request.getRequestDispatcher("/list.jsp"); dispatcher.forward(request, response); System.out.println("111"); } private void toAdd(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ RequestDispatcher dispatcher = request.getRequestDispatcher("/add.jsp"); dispatcher.forward(request, response); System.out.println("222"); } private void toEdit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ int id = Integer.parseInt(request.getParameter("id")); StudentService studentService = new StudentService(); Student student = studentService.getStudent(id); request.setAttribute("student", student); RequestDispatcher dispatcher = request.getRequestDispatcher("/edit.jsp"); dispatcher.forward(request, response); System.out.println("333"); } private void saveStudent(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ Student student = new Student(); student.setSno(request.getParameter("sno")); student.setName(request.getParameter("name")); student.setSex(request.getParameter("sex")); student.setAge(request.getParameter("age")); StudentService studentService = new StudentService(); studentService.saveStudent(student); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); System.out.println("444"); } private void updateStudent(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ Student student = new Student(); student.setSno(request.getParameter("sno")); student.setName(request.getParameter("name")); student.setSex(request.getParameter("sex")); student.setId(Integer.parseInt(request.getParameter("id"))); student.setAge(request.getParameter("age")); StudentService studentService = new StudentService(); studentService.updateStudent(student); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); System.out.println("555"); } private void deleteStudent(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ int id = Integer.parseInt(request.getParameter("id")); StudentService studentService = new StudentService(); studentService.deleteStudent(id); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); System.out.println("666"); } }

在Eclipse中运行程序时,跳转到Servlet的操作就执行一次

index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <jsp:forward page="/IndexServlet"></jsp:forward> IndexServlet.java package com.yxq.servlet; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.yxq.dao.ArticleDao; import com.yxq.valuebean.ArticleBean; /** * Servlet implementation class IndexServlet */ @WebServlet(urlPatterns={"/IndexServlet"}) public class IndexServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public IndexServlet() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); ArticleDao articleDao=new ArticleDao(); //获取主页面的显示内容 //获取前三篇文章 ArrayList<ArticleBean> articleList=articleDao.queryArticle(-1, null); //测试语句 System.out.println("长度"+articleList.size()); request.setAttribute("articleList", articleList); //还有其他的例如像左侧栏的一系列的内容,都要在主页显示,以后实现 //实现跳转到指定的页面 RequestDispatcher dispatcher=request.getRequestDispatcher("/front/FrontIndex.jsp"); dispatcher.forward(request, response); } } 以后重新启动服务器,不会更新内容,还是原来获取的内容

使用 springmvc 读取 form 表单元素

如题,各位大牛,小弟有一个 html页面的 form表单,内容为 name, email, intro 三个元素 使用 springmvc读取器内容 [code="java"]@RequestMapping(value="/register/", method=RequestMethod.POST) public ModelAndView handleRegisterRequest(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("tempUser") User tempUser) { }[/code] 对于 User, 有 [code="java"]class User { String name; String email; }[/code] 对于使用了 ModelAttribute 的方法,可以很容易读取 form表单传递的 name 和 email, 并且生成一个相应的 User 实例,但是对于与 User无关的intro属性,却无法获取,请教各位大牛,这个应该怎么做? 我试了下面方法,不行 [code="java"]@RequestMapping(value="/register/intro/{intro}/", method=RequestMethod.POST) public ModelAndView handleRegisterRequest(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("tempUser") User tempUser, @PathVariable String intro) { logger.debug(intro); // 打印的结果却是 {intro},说明没有传进该 controller }[/code] 万分感谢!

如何关闭SchedulerFactoryBean中的一个任务triggers

配置文件中有如下配置: <!-- 我的调度工厂 --> <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false"> <property name="triggers"> <list> <ref local="customCronTrigger" /> </list> </property> </bean> <!-- 自定义触发器 --> <bean id="customCronTrigger" class="com.gilight.dep.metadata.web.util.CustomCronTrigger"> <property name="jobDetail" ref="myJobDetail" /> <property name="initBackupTimeService" ref="initBackupTimeService"></property> </bean> <!-- 动态jobDetail备份系统 --> <bean id="myJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <ref bean="systemBackupService" /> </property> <property name="targetMethod" value="backupSystem" /> <property name="concurrent" value="false" /> </bean> 现在要实现一个改变定时任务的功能,需要在控制类中关闭原来的triggers,查源码发现,关闭triggers的方法在SchedulerFactoryBean中,是stop();但是在控制类中如何注入这个原来 的SchedulerFactoryBean使其关闭呢? 我写的是这样;但是不可以,会报一个类型转换异常的错StdScheduler cannot be cast to SchedulerFactoryBean public class SystemBackupController extends MetadataBaseController{ private SchedulerFactoryBean schedulerFactoryBean;//实现类无法bean注入????? private CustomCronTrigger customCronTrigger; private ISystemBackupService systemBackupService; private IInitBackupTimeService initBackupTimeService; private String backupTime;//前台时间 private Trigger[] triggers; /*get,set方法省略*/ @RequestMapping(value = "/start", method = RequestMethod.POST) public void start(@RequestBody String json,HttpServletRequest request) throws ParseException { System.out.println(json); Map<String, Object> map = (Map<String, Object>) JSON.parse(json); backupTime = (String) map.get("backupTime"); System.out.println(backupTime); ApplicationContext sac = RequestContextUtils.getWebApplicationContext(request); ConfigurableApplicationContext context = (ConfigurableApplicationContext) sac; //Bean的实例工厂 DefaultListableBeanFactory dbf = (DefaultListableBeanFactory) context.getBeanFactory(); schedulerFactoryBean =(SchedulerFactoryBean) dbf.getBean("schedulerFactoryBean"); String cronExpression = customCronTrigger.getCronExpression();// 原触发器的时间 saveBackupTime(backupTime); if (cronExpression != backupTime) { schedulerFactoryBean.stop(); customCronTrigger.setCronExpression(backupTime); triggers[0] = customCronTrigger; schedulerFactoryBean.setTriggers(triggers); schedulerFactoryBean.start(); } } public void saveBackupTime(String backupTime) { systemBackupService.saveBackupTime(backupTime); } }

Filter 简单应用实例求详解

web.xml <filter> <filter-name>AdminFilter</filter-name> <filter-class>szy.shopping.filter.AdminFilter</filter-class> <init-param> <param-name>url</param-name> <param-value>/admin/login.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>AdminFilter</filter-name> <url-pattern>/admin/index.jsp</url-pattern> </filter-mapping> AdminFilter.java public class AdminFilter implements Filter{ String url = "/"; @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req.getSession(); if (session.getAttribute("admin") == null) { res.sendRedirect(req.getContextPath() + url); return ; } chain.doFilter(request, response); } @Override public void init(FilterConfig config) throws ServletException { url = config.getInitParameter("url"); } } 能不能详细说明以上两段代码的具体解释?大致的流程是怎么样的? [b]问题补充:[/b] lianj_lee所说的这个权限判断是我写程序调用,还是它自动根据XML来调用验证是否登录? 还有 <filter> <filter-name>AdminFilter</filter-name> <filter-class>szy.shopping.filter.AdminFilter</filter-class> <init-param> <param-name>url</param-name> <param-value>/admin/login.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>AdminFilter</filter-name> <url-pattern>/admin/index.jsp</url-pattern> </filter-mapping> 可否在详细说明?谢谢~

关于RedirectAttributes的使用

需求:在页面重定向的时候传递参数,不使用session,使用RedirectAttributes 代码如下 @RequestMapping( value = "testForward" ) public String testForward( HttpServletRequest request, final RedirectAttributes attr ) { // return "forward:/index.jsp"; request.setAttribute( "aaa", "aaa" ); return "forward:/global/testRedirect.do"; } @RequestMapping( value = "testRedirect" ) public String testRedirect( HttpServletRequest request, final RedirectAttributes attr ) { // 下面这种方式参数将会被附在url后面传递过去 // attr.addAttribute( "aaa", request.getAttribute( "aaa" ) ); // 下面这种方式在jsp页面中就获取不到了 attr.addFlashAttribute( "aaa", request.getAttribute( "aaa" ) ); return "redirect:/index.jsp"; } 发现attr.addFlashAttribute( "aaa", request.getAttribute( "aaa" ) );的时候jsp页面使用${aaa}无法获取到参数。请各位大神解答,谢谢

id为integer类型怎么返回值

public ModelAndView FilecardAdd(HttpServletRequest request,Filecard filecard){ Integer id=new Integer(request.getParameter("id")); if(id==null){ id=UUID.randomUUID().toString(); } filecard.setId(id); fs.addFilecard(filecard); mv.setViewName("redirect:getFilecard.do"); return mv; } 在id=UUID.randomUUID().toString();一直报错; 哪位大神能解释一下上段代码的意思和具体怎么改啊 jsp里报错HTTP Status 500 - Request processing failed; nested exception is java.lang.NumberFormatException: null type Exception report message Request processing failed; nested exception is java.lang.NumberFormatException: null description The server encountered an internal error that prevented it from fulfilling this request. exception org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NumberFormatException: null org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) javax.servlet.http.HttpServlet.service(HttpServlet.java:650) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) com.record.filter.TestFilter.doFilter(TestFilter.java:45) root cause java.lang.NumberFormatException: null

Ext.Ajax.request做文件上传不执行回调函数?

我在做一个多文件上传,整体用的EXT,所以想用EXT的异步请求完成上传,上传没问题,就是上传完了,不执行回调函数,老自动弹一个下载"uploadFile.action"文件,其实就是一个json,好像是根本没执行回调函数,求各位老鸟解释下,并帮我解决,我不想别人上传完,总提示下载"uploadFile.action"。 页面代码: [code="java"] <form id="uploadForm" action="uploadFile.action"> <table border="0" cellspacing="1" class="fu_list"> <thead> <tr> <td colspan="2"><b>上传附件</b></td> </tr> </thead> <tbody> <tr> <td align="right" width="15%" style="line-height:35px;">添加附件:</td> <td><a href="javascript:void(0);" class="files" id="idFile"></a> <img id="idProcess" style="display:none;" src="../../images/upload/loading.gif" /></td> </tr> <tr id="fileList" style="display: none"> <td colspan="2"><table border="0" cellspacing="0"> <thead> <tr> <td>文件路径</td> <td width="100"></td> </tr> </thead> <tbody id="idFileList" name="idFileList"> </tbody> </table></td> </tr> <tr> <td colspan="2" style="color:gray">温馨提示:最多可同时上传 <b id="idLimit"></b> 个文件,只允许上传 <b id="idExt"></b> 文件。 </td> </tr> <tr id="uploadButton" style="display: none"> <td colspan="2" align="center" id="idMsg"><input type="button" value="开始上传" id="idBtnupload" disabled="disabled" /> &nbsp;&nbsp;&nbsp; <input type="button" value="全部取消" id="idBtndel" disabled="disabled" /> </td> </tr> </tbody> </table> </form> <SCRIPT type="text/javascript"> //以下为附件js代码 var isIE = (document.all) ? true : false; var $ = function (id) { return "string" == typeof id ? document.getElementById(id) : id; }; var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } } var Extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } } var Bind = function(object, fun) { return function() { return fun.apply(object, arguments); } } var Each = function(list, fun){ for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); } }; //提交操作 function doUpload(){ if(Efs.getExt("uploadForm").isValid()){ myMask.show(); Ext.Ajax.request({ //请求地址 url: 'uploadFile.action', //提交参数组 fileUpload: true, form: uploadForm, scope: uploadForm, //成功时回调 success: function(response, options) { //获取响应的json字符串 myMask.hide(); var json = response.responseText; var o= Ext.util.JSON.decode(json); // var s="<s:text name="o.msg"/>"; var s=o.msg; Ext.Msg.alert('<s:text name="msg_title"/>', s); }, failure: function (response,options){ myMask.hide(); var st='<s:text name="'+o.msg+'"/>'; Ext.Msg.alert('<s:text name="msg_title"/>', st); } }); } else Ext.Msg.alert('<s:text name="msg_title"/>', '<s:text name="msg_mustFill"/>'); } //文件上传 var FileUpload = Class.create(); FileUpload.prototype = { //表单对象,文件控件存放空间 initialize: function(form, folder, options) { this.Form = $(form);//表单 this.Folder = $(folder);//文件控件存放空间 this.Files = [];//文件集合 this.SetOptions(options); this.FileName = this.options.FileName; this._FrameName = this.options.FrameName; this.Limit = this.options.Limit; this.Distinct = !!this.options.Distinct; this.ExtIn = this.options.ExtIn; this.ExtOut = this.options.ExtOut; this.onIniFile = this.options.onIniFile; this.onEmpty = this.options.onEmpty; this.onNotExtIn = this.options.onNotExtIn; this.onExtOut = this.options.onExtOut; this.onLimite = this.options.onLimite; this.onSame = this.options.onSame; this.onFail = this.options.onFail; this.onIni = this.options.onIni; if(!this._FrameName){ //为每个实例创建不同的iframe this._FrameName = "uploadFrame_" + Math.floor(Math.random() * 1000); //ie不能修改iframe的name var oFrame = isIE ? document.createElement("<iframe name=\"" + this._FrameName + "\">") : document.createElement("iframe"); //为ff设置name oFrame.name = this._FrameName; oFrame.style.display = "none"; //在ie文档未加载完用appendChild会报错 document.body.insertBefore(oFrame, document.body.childNodes[0]); } //设置form属性,关键是target要指向iframe this.Form.target = this._FrameName; this.Form.method = "post"; //注意ie的form没有enctype属性,要用encoding this.Form.encoding = "multipart/form-data"; //整理一次 this.Ini(); }, //设置默认属性 SetOptions: function(options) { this.options = {//默认值 FileName: "files",//文件上传控件的name,配合后台使用 FrameName: "",//iframe的name,要自定义iframe的话这里设置name onIniFile: function(){},//整理文件时执行(其中参数是file对象) onEmpty: function(){},//文件空值时执行 Limit: 0,//文件数限制,0为不限制 onLimite: function(){},//超过文件数限制时执行 Distinct: true,//是否不允许相同文件 onSame: function(){},//有相同文件时执行 ExtIn: [],//允许后缀名 onNotExtIn: function(){},//不是允许后缀名时执行 ExtOut: [],//禁止后缀名,当设置了ExtIn则ExtOut无效 onExtOut: function(){},//是禁止后缀名时执行 onFail: function(){},//文件不通过检测时执行(其中参数是file对象) onIni: function(){}//重置时执行 }; Extend(this.options, options || {}); }, //整理空间 Ini: function() { //整理文件集合 this.Files = []; //整理文件空间,把有值的file放入文件集合 Each(this.Folder.getElementsByTagName("input"), Bind(this, function(o){ if(o.type == "file"){ o.value && this.Files.push(o); this.onIniFile(o); } })) //插入一个新的file var file = document.createElement("input"); file.name = this.FileName; file.type = "file"; file.onchange = Bind(this, function(){ this.Check(file); this.Ini(); }); this.Folder.appendChild(file); //执行附加程序 this.onIni(); //添加附件成功,显示列表 if(this.Files.length>0){ document.getElementById('fileList').style.display=""; document.getElementById('uploadButton').style.display=""; } }, //检测file对象 Check: function(file) { //检测变量 var bCheck = true; //空值、文件数限制、后缀名、相同文件检测 if(!file.value){ bCheck = false; this.onEmpty(); } else if(this.Limit && this.Files.length >= this.Limit){ bCheck = false; this.onLimite(); } else if(!!this.ExtIn.length && !RegExp("\.(" + this.ExtIn.join("|") + ")$", "i").test(file.value)){ //检测是否允许后缀名 bCheck = false; this.onNotExtIn(); } else if(!!this.ExtOut.length && RegExp("\.(" + this.ExtOut.join("|") + ")$", "i").test(file.value)) { //检测是否禁止后缀名 bCheck = false; this.onExtOut(); } else if(!!this.Distinct) { Each(this.Files, function(o){ if(o.value == file.value){ bCheck = false; } }) if(!bCheck){ this.onSame(); } } //没有通过检测 !bCheck && this.onFail(file); }, //删除指定file Delete: function(file) { //移除指定file this.Folder.removeChild(file); this.Ini(); if(this.Folder.getElementsByTagName("input").length==1){//没有附件时隐藏 document.getElementById('fileList').style.display="none"; document.getElementById('uploadButton').style.display="none"; } }, //删除全部file Clear: function() { //清空文件空间 Each(this.Files, Bind(this, function(o){ this.Folder.removeChild(o); })); this.Ini(); document.getElementById('fileList').style.display="none";//清空同样隐藏 document.getElementById('uploadButton').style.display="none"; } } var fu = new FileUpload("uploadForm", "idFile", { Limit: 3, ExtIn: [], onIniFile: function(file){ file.value ? file.style.display = "none" : this.Folder.removeChild(file); }, onEmpty: function(){ alert("请选择一个文件"); }, onLimite: function(){ alert("超过上传限制"); }, onSame: function(){ alert("已经有相同文件"); }, // ExtIn: ["jpg", "gif"] 可以限制上传文件后缀名,不写即为所有 // onNotExtIn: function(){ alert("只允许上传" + this.ExtIn.join(",") + "文件"); }, onFail: function(file){ this.Folder.removeChild(file); }, onIni: function(){ //显示文件列表 var arrRows = []; if(this.Files.length){ var oThis = this; Each(this.Files, function(o){ var a = document.createElement("a"); a.innerHTML = "取消"; a.href = "javascript:void(0);"; a.onclick = function(){ oThis.Delete(o); return false; }; arrRows.push([o.value, a]); }); } else { arrRows.push(["<font color='gray'>没有添加文件</font>", "&nbsp;"]); } AddList(arrRows); //设置按钮 //$("idBtnupload").disabled = $("idBtndel").disabled = this.Files.length <= 0; } }); $("idBtnupload").onclick = function(){ //显示文件列表 var arrRows = []; Each(fu.Files, function(o){ arrRows.push([o.value, "&nbsp;"]); }); AddList(arrRows); fu.Folder.style.display = "none"; $("idProcess").style.display = ""; $("idMsg").innerHTML = "正在添加文件到您的网盘中,请稍候……<br />有可能因为网络问题,出现程序长时间无响应,请点击“<a href='?'><font color='red'>取消</font></a>”重新上传文件"; doUpload(); $("idProcess").style.display = "none"; //fu.Form.submit(); } //用来添加文件列表的函数 function AddList(rows){ //根据数组来添加列表 var FileList = $("idFileList"), oFragment = document.createDocumentFragment(); //用文档碎片保存列表 Each(rows, function(cells){ var row = document.createElement("tr"); Each(cells, function(o){ var cell = document.createElement("td"); if(typeof o == "string"){ cell.innerHTML = o; }else{ cell.appendChild(o); } row.appendChild(cell); }); oFragment.appendChild(row); }) //ie的table不支持innerHTML所以这样清空table while(FileList.hasChildNodes()){ FileList.removeChild(FileList.firstChild); } FileList.appendChild(oFragment); } $("idLimit").innerHTML = fu.Limit; $("idExt").innerHTML = fu.ExtIn.join(","); $("idBtndel").onclick = function(){ fu.Clear(); } //在后台通过window.parent来访问主页面的函数 //function Finish(msg){ alert(msg); location.href = location.href; } <SCRIPT> [/code] struts配置文件(用的插件自动生成json): [code="java"] <action name="*File" method="{1}" class="com.web.action.UploadFile"> <result type="json" name="success"> <param name="includeProperties">msg</param> <param name="excludeNullProperties">true</param> </result> <result type="json" name="error"> <param name="includeProperties">msg</param> <param name="excludeNullProperties">true</param> </result> </action> [/code] 后台UploadFile.java的代码 [code="java"] package com.web.action; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.common.pojo.AppUser; import com.opensymphony.xwork2.ActionContext; /** * 负责文件的上传 */ public class UploadFile { private File[] files; private String[] filesFileName; private Map<String, String> filesPath;// 文件名及其上传后路径 private String msg; public String upload() { /* * Map session=ActionContext.getContext().getSession(); AppUser * user=(AppUser) session.get("user"); if(user==null){ return "error"; } */ msg="上传成功!"; for (int i = 0; i < files.length; i++) { fileCopy(files[i], filesFileName[i]); } return "success"; } private void fileCopy(File file, String fileName) { BufferedInputStream bis = null; BufferedOutputStream bos = null; String realPath = ServletActionContext. getServletContext().getRealPath("/upload/" + fileName); System.out.println(realPath); try { bis = new BufferedInputStream(new FileInputStream(file)); bos = new BufferedOutputStream(new FileOutputStream(new File( realPath))); byte[] buffer = new byte[1024 * 8]; int i = -1; while ((i = bis.read(buffer)) != -1) { bos.write(buffer,0,i); } bos.flush(); } catch (Exception e) { System.out.println("上传异常!"); msg="上传出错!"; e.printStackTrace(); }finally{ try { if (bis != null) bis.close(); if (bos != null) bos.close(); } catch (IOException e1) { System.out.println("上传结束异常!"); e1.printStackTrace(); } } } public File[] getFiles() { return files; } public void setFiles(File[] files) { this.files = files; } public String[] getFilesFileName() { return filesFileName; } public void setFilesFileName(String[] filesFileName) { this.filesFileName = filesFileName; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } [/code]

nginx中,前台使用ajax访问接口,传参数到后端接收为null,如何解决呢

如下是nginx的配置 ``` #前端界面 location / { root D:/ant-design-pro-master/dist; index index.html index.htm; } #后端接口 location ^~ /api/ { proxy_pass http://127.0.0.1:8085; } ``` axios传参代码如下 ``` axios.get(url, { params: { ID: 12345 }, }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); ``` 后台代码如下 ``` @RequestMapping(value = "${adminPath}/login", method = {RequestMethod.GET, RequestMethod.HEAD}) public String login(HttpServletRequest request, HttpServletResponse response, Model model) { Map m = request.getParameterMap(); String id = (String) request.getAttribute("ID"); ```

SSH框架的UndeclaredThrowableException问题

我正在学习SSH框架,用到了struts的异常捕获机制。我自定义了一个异常类型,在异常处理类里面通过判断是否是这个类的实例来进行不同的处理。可是我能接受到的异常,全部是UndeclaredThrowableException,这个何解?一下是抛出事件的类: `public class LoginInterceptor implements MethodBeforeAdvice { public void before(Method method, Object[] args, Object instance) throws Exception { ActionMapping mapping = (ActionMapping) args[0]; ActionForm form = (ActionForm) args[1]; HttpServletRequest request = (HttpServletRequest) args[2]; HttpServletResponse response = (HttpServletResponse) args[3]; boolean needsCheck = true; if (needsCheck && PersonUtil.getPersonInfo(request, response) == null) { throw new TempException("您还没有登录"); } } }` 一下是处理异常的类 public class ForumExceptionHandler extends ExceptionHandler { @Override public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException { System.out.println((ex.getClass()) + " aaaaaaa"); System.out.println((ae) + " aaaaaaa"); request.setAttribute("exception", ex); if (ex instanceof AccountException) { return new ActionForward("login", "/index.jsp", false); } return new ActionForward("exception", "/pages/exception.jsp", false); } } 一下是配置文件: <global-exceptions> <exception key="login" type="com.forum.exception.TempException" handler="com.forum.exception.ForumExceptionHandler"> </exception> <exception key="login" type="javax.security.auth.login.AccountException" handler="com.forum.exception.ForumExceptionHandler"> </exception> <exception key="login" type="java.lang.Exception" handler="com.forum.exception.ForumExceptionHandler"> </exception> </global-exceptions>

在servlet中怎么传集合显示在jsp页面

jsp页面: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>显示页面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="SelectAll" method="post"> <table border="1px" > <tr><td colspan="5" align="center"><h1>联系人列表</h1></td></tr> <tr><td colspan="5" align="right">新增联系人</td></tr> <tr><td>姓名</td><td>电话</td><td>邮箱</td><td>关系</td><td>操作</td></tr> <tr><td name="name"></td><td name="phone"></td><td name="email"></td><td name="contact"></td><td><a href="#">删除</a></td></tr> <tr><td name="name"></td><td name="phone"></td><td name="email"></td><td name="contact"></td><td><a href="#">删除</a></td></tr> <tr><td name="name"></td><td name="phone"></td><td name="email"></td><td name="contact"></td><td><a href="#">删除</a></td></tr> <tr><td name="name"></td><td name="phone"></td><td name="email"></td><td name="contact"></td><td><a href="#">删除</a></td></tr> </table> </form> </body> </html> servlet页面: package Servlet; import impl.ContactsDaoImpl; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dao.ContactsDao; import entity.Contacts; public class SelectAll extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理乱码 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //得到httpsession对象 HttpSession session=request.getSession(); //得到数组的值 String[] name=request.getParameterValues("name"); String[] phone=request.getParameterValues("phone"); String[] email=request.getParameterValues("email"); String[] contact=request.getParameterValues("contact"); //调用接口的实现方法; ContactsDao contactsdao=new ContactsDaoImpl(); List<Contacts> list=contactsdao.selectAll(); if (list!=null) { session.setAttribute("name", name); response.sendRedirect("show.jsp"); } } } 接口的实现方法类页面: package impl; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import dao.BaseDao; import dao.ContactsDao; import entity.Contacts; public class ContactsDaoImpl extends BaseDao implements ContactsDao { //查询所有 public List<Contacts> selectAll() { List<Contacts> list=new ArrayList<Contacts>(); String sql="select * from Contacts"; Contacts contacts=null; //调用basedao中的公共方法; rs=this.executeQuery(sql, null); try { while (rs.next()) { contacts=new Contacts(rs.getString("name"), rs.getString("phone"), rs.getString("email"), rs.getString("contact")); list.add(contacts); } } catch (SQLException e) { e.printStackTrace(); }finally{ this.closeAll(con, pstm, rs); } return list; } } ![图片说明](https://img-ask.csdn.net/upload/201509/10/1441857052_417553.jpg)

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

深入剖析Springboot启动原理的底层源码,再也不怕面试官问了!

大家现在应该都对Springboot很熟悉,但是你对他的启动原理了解吗?

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

立即提问
相关内容推荐